velvetkit 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +1 -1
  3. data/lib/velvetkit/version.rb +1 -1
  4. data/registry/app/components/ui/file_field.html.erb +4 -0
  5. data/registry/app/components/ui/file_field.rb +73 -0
  6. data/registry/app/components/ui/session_tabs/add.html.erb +1 -0
  7. data/registry/app/components/ui/session_tabs/add.rb +52 -0
  8. data/registry/app/components/ui/session_tabs/tab.html.erb +37 -0
  9. data/registry/app/components/ui/session_tabs/tab.rb +243 -0
  10. data/registry/app/components/ui/session_tabs.html.erb +15 -0
  11. data/registry/app/components/ui/session_tabs.rb +101 -0
  12. data/registry/app/components/ui/skeleton.html.erb +1 -0
  13. data/registry/app/components/ui/skeleton.rb +30 -0
  14. data/registry/app/components/ui/toast/viewport.html.erb +4 -0
  15. data/registry/app/components/ui/toast/viewport.rb +41 -0
  16. data/registry/app/components/ui/toast.html.erb +11 -0
  17. data/registry/app/components/ui/toast.rb +89 -0
  18. data/registry/app/javascript/controllers/ui/file_field_controller.ts +49 -0
  19. data/registry/app/javascript/controllers/ui/menu_controller.ts +3 -0
  20. data/registry/app/javascript/controllers/ui/session_tabs_controller.ts +732 -0
  21. data/registry/app/javascript/controllers/ui/toast_controller.ts +62 -0
  22. data/registry/app/javascript/controllers/ui/toast_viewport_controller.ts +82 -0
  23. data/registry/app/javascript/velvetkit_icons.ts +21 -9
  24. data/registry/components.yml +8 -0
  25. data/registry/config/locales/velvetkit.en.yml +19 -0
  26. data/registry/test/components/previews/ui/file_field_preview/multiple_files.html.erb +3 -0
  27. data/registry/test/components/previews/ui/file_field_preview/with_error.html.erb +3 -0
  28. data/registry/test/components/previews/ui/file_field_preview.rb +18 -0
  29. data/registry/test/components/previews/ui/session_tabs_preview/handling_events.html.erb +46 -0
  30. data/registry/test/components/previews/ui/session_tabs_preview/saved_views.html.erb +16 -0
  31. data/registry/test/components/previews/ui/session_tabs_preview/touch_with_confirmation.html.erb +20 -0
  32. data/registry/test/components/previews/ui/session_tabs_preview.rb +35 -0
  33. data/registry/test/components/previews/ui/skeleton_preview/card_placeholder.html.erb +10 -0
  34. data/registry/test/components/previews/ui/skeleton_preview/shapes.html.erb +9 -0
  35. data/registry/test/components/previews/ui/skeleton_preview.rb +15 -0
  36. data/registry/test/components/previews/ui/toast_preview/live_viewport.html.erb +21 -0
  37. data/registry/test/components/previews/ui/toast_preview/variants.html.erb +7 -0
  38. data/registry/test/components/previews/ui/toast_preview/with_action.html.erb +7 -0
  39. data/registry/test/components/previews/ui/toast_preview.rb +29 -0
  40. data/registry/test/components/ui/file_field_test.rb +101 -0
  41. data/registry/test/components/ui/session_tabs/add_test.rb +52 -0
  42. data/registry/test/components/ui/session_tabs_test.rb +281 -0
  43. data/registry/test/components/ui/skeleton_test.rb +65 -0
  44. data/registry/test/components/ui/toast/viewport_test.rb +72 -0
  45. data/registry/test/components/ui/toast_test.rb +183 -0
  46. metadata +39 -1
@@ -0,0 +1,62 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // Matches the exit animation's `duration-300` in UI::Toast (and its
4
+ // EXIT_DURATION constant). Removing on a fixed timer, rather than the exit
5
+ // animation's `animationend`, sidesteps a real race: a toast dismissed while
6
+ // its own *entrance* animation is still playing would otherwise have its
7
+ // entrance's animationend fire moments later and remove the element early,
8
+ // before the exit animation ever got a chance to play.
9
+ const EXIT_DURATION = 300;
10
+
11
+ /**
12
+ * UI::Toast controller — owns one toast's lifecycle, however it arrived
13
+ * (rendered by ERB, appended by a Turbo Stream, or cloned by the
14
+ * toast-viewport controller from its templates).
15
+ *
16
+ * Auto-dismisses after durationValue ms, pausing while the pointer is over
17
+ * it. durationValue of 0 means "stays until dismissed".
18
+ */
19
+ export default class extends Controller<HTMLElement> {
20
+ static values = { duration: { type: Number, default: 5000 } };
21
+
22
+ declare durationValue: number;
23
+
24
+ private timeout: number | null = null;
25
+
26
+ connect() {
27
+ this.arm();
28
+ }
29
+
30
+ disconnect() {
31
+ this.disarm();
32
+ }
33
+
34
+ pause() {
35
+ this.disarm();
36
+ }
37
+
38
+ resume() {
39
+ this.arm();
40
+ }
41
+
42
+ dismiss = (event?: Event) => {
43
+ event?.preventDefault();
44
+ this.disarm();
45
+ if (this.element.dataset.state === 'closed') return;
46
+ this.element.dataset.state = 'closed';
47
+ window.setTimeout(() => this.element.remove(), EXIT_DURATION);
48
+ };
49
+
50
+ private arm() {
51
+ this.disarm();
52
+ if (!this.durationValue) return;
53
+ this.timeout = window.setTimeout(this.dismiss, this.durationValue);
54
+ }
55
+
56
+ private disarm() {
57
+ if (this.timeout) {
58
+ clearTimeout(this.timeout);
59
+ this.timeout = null;
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,82 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ export interface ToastOptions {
4
+ description?: string;
5
+ variant?: 'default' | 'success' | 'destructive' | 'warning' | 'info';
6
+ /** Seconds before it dismisses itself; 0 leaves it until clicked away. */
7
+ duration?: number;
8
+ }
9
+
10
+ /**
11
+ * Pushes a toast from client-side JS, no server round trip. Dispatches an
12
+ * event the toast-viewport controller below listens for; it builds the
13
+ * toast by cloning one of the templates UI::Toast::Viewport renders (one per
14
+ * variant), so a JS-triggered toast is pixel-identical to a server-rendered
15
+ * one and never needs its own copy of the component's styling.
16
+ *
17
+ * Import `toast` from this same controller file, then call it:
18
+ * toast("Saved", { variant: "success" }).
19
+ *
20
+ * For a toast pushed from the server, skip this and append a UI::Toast to
21
+ * UI::Toast::Viewport::ID in a Turbo Stream response instead.
22
+ */
23
+ export function toast(title: string, options: ToastOptions = {}) {
24
+ window.dispatchEvent(new CustomEvent<ToastOptions & { title: string }>('toast:show', {
25
+ detail: { title, ...options },
26
+ }));
27
+ }
28
+
29
+ /**
30
+ * UI::Toast::Viewport controller — listens for toast:show and clones the
31
+ * matching variant template into itself. The cloned toast then connects its
32
+ * own ui--toast controller like any other toast, which is what actually
33
+ * drives its auto-dismiss and animations.
34
+ */
35
+ export default class extends Controller<HTMLElement> {
36
+ static targets = ['template'];
37
+
38
+ declare readonly templateTargets: HTMLTemplateElement[];
39
+
40
+ connect() {
41
+ window.addEventListener('toast:show', this.show as EventListener);
42
+ }
43
+
44
+ disconnect() {
45
+ window.removeEventListener('toast:show', this.show as EventListener);
46
+ }
47
+
48
+ private show = (event: Event) => {
49
+ const detail = (event as CustomEvent<ToastOptions & { title?: string }>).detail || {};
50
+ const template = this.findTemplate(detail.variant);
51
+ if (!template) return;
52
+
53
+ const node = template.content.firstElementChild?.cloneNode(true) as HTMLElement | undefined;
54
+ if (!node) return;
55
+
56
+ this.fill(node, 'title', detail.title);
57
+ this.fill(node, 'description', detail.description);
58
+
59
+ if (detail.duration !== undefined) {
60
+ node.setAttribute('data-ui--toast-duration-value', String(detail.duration * 1000));
61
+ }
62
+
63
+ this.element.appendChild(node);
64
+ };
65
+
66
+ private findTemplate(variant?: string) {
67
+ return (
68
+ this.templateTargets.find((t) => t.dataset.variant === variant) ||
69
+ this.templateTargets.find((t) => t.dataset.variant === 'default')
70
+ );
71
+ }
72
+
73
+ private fill(node: HTMLElement, target: string, text?: string) {
74
+ const el = node.querySelector<HTMLElement>(`[data-ui--toast-target="${target}"]`);
75
+ if (!el) return;
76
+ if (text) {
77
+ el.textContent = text;
78
+ } else {
79
+ el.remove();
80
+ }
81
+ }
82
+ }
@@ -13,6 +13,7 @@ import {
13
13
  ChevronRight,
14
14
  ChevronsUpDown,
15
15
  CircleAlert,
16
+ CircleCheck,
16
17
  Ellipsis,
17
18
  Eye,
18
19
  EyeOff,
@@ -23,6 +24,7 @@ import {
23
24
  Moon,
24
25
  PanelLeft,
25
26
  Sun,
27
+ Upload,
26
28
  X,
27
29
  } from 'lucide';
28
30
 
@@ -34,6 +36,7 @@ const icons = {
34
36
  ChevronRight,
35
37
  ChevronsUpDown,
36
38
  CircleAlert,
39
+ CircleCheck,
37
40
  Ellipsis,
38
41
  Eye,
39
42
  EyeOff,
@@ -44,15 +47,24 @@ const icons = {
44
47
  Moon,
45
48
  PanelLeft,
46
49
  Sun,
50
+ Upload,
47
51
  X,
48
52
  };
49
53
 
50
- // Turbo replaces markup without a full page load, so icons are drawn again
51
- // after every kind of render, not just the first.
52
- [
53
- 'turbo:load',
54
- 'turbo:frame-load',
55
- 'turbo:render',
56
- 'turbo:submit-end',
57
- 'turbo:render-stream',
58
- ].forEach((event) => document.addEventListener(event, () => createIcons({ icons })));
54
+ // Icons are drawn whenever one is added to the page, however it arrives: a
55
+ // Turbo visit, frame or stream, or a controller's own markup. Only <i> is
56
+ // watched: the SVG that replaces it keeps data-lucide, and drawing on that
57
+ // would draw forever.
58
+ const draw = () => createIcons({ icons });
59
+ const added = (records: MutationRecord[]) =>
60
+ records.some((record) =>
61
+ Array.from(record.addedNodes).some(
62
+ (node) => node instanceof Element && (node.matches('i[data-lucide]') || node.querySelector('i[data-lucide]') !== null),
63
+ ),
64
+ );
65
+
66
+ draw();
67
+ new MutationObserver((records) => added(records) && draw()).observe(document.documentElement, {
68
+ childList: true,
69
+ subtree: true,
70
+ });
@@ -53,6 +53,8 @@ components:
53
53
  description: A modal dialog on the native <dialog> element.
54
54
  divider:
55
55
  description: A horizontal or vertical rule, optionally labelled.
56
+ file_field:
57
+ description: A drag-and-drop file picker with a label, hint and error message, standalone or with a form builder.
56
58
  form_field:
57
59
  description: A label, hint and error message wired to any form control.
58
60
  icon:
@@ -82,10 +84,14 @@ components:
82
84
  description: The browser's own select, styled closed; best for phones' system pickers.
83
85
  select:
84
86
  description: A styled dropdown with keyboard navigation and type-ahead, posting like a native select.
87
+ session_tabs:
88
+ description: Browser-style tabs the user opens, renames, duplicates, reorders and closes.
85
89
  sheet:
86
90
  description: A panel that slides in from an edge of the screen.
87
91
  sidebar:
88
92
  description: A collapsible application sidebar with groups and menus.
93
+ skeleton:
94
+ description: A pulsing placeholder shown in a piece of content's shape while it loads.
89
95
  spinner:
90
96
  description: A loading indicator.
91
97
  switch:
@@ -104,6 +110,8 @@ components:
104
110
  description: A light/dark/system theme switcher.
105
111
  files:
106
112
  - app/views/layouts/_theme_script.html.erb
113
+ toast:
114
+ description: A stacked, auto-dismissing message, pushed from the client or a Turbo Stream.
107
115
  tooltip:
108
116
  description: A hint shown on hover and focus.
109
117
  typography:
@@ -49,6 +49,20 @@ en:
49
49
  no_matches: 'No matches'
50
50
  # Shown on a multiple select once more than two options are ticked.
51
51
  selected: '%{count} selected'
52
+ session_tabs:
53
+ label: 'Open tabs'
54
+ add: 'New tab'
55
+ options: 'Tab options'
56
+ rename: 'Rename'
57
+ rename_label: 'Tab name'
58
+ duplicate: 'Duplicate'
59
+ move_left: 'Move left'
60
+ move_right: 'Move right'
61
+ close: 'Close'
62
+ confirm_close:
63
+ title: 'Close this tab?'
64
+ cancel: 'Keep it open'
65
+ confirm: 'Close tab'
52
66
  theme_toggle:
53
67
  label: 'Change theme'
54
68
  heading: 'Theme'
@@ -56,3 +70,8 @@ en:
56
70
  light: 'Light'
57
71
  dark: 'Dark'
58
72
  system: 'System'
73
+ toast:
74
+ close_label: 'Dismiss'
75
+ file_field:
76
+ browse: 'Click to upload'
77
+ drop: 'or drag and drop'
@@ -0,0 +1,3 @@
1
+ <div class="max-w-sm">
2
+ <%= render(UI::FileField.new(label: "Attachments", hint: "Drop as many as you like", multiple: true)) %>
3
+ </div>
@@ -0,0 +1,3 @@
1
+ <div class="max-w-sm">
2
+ <%= render(UI::FileField.new(label: "Resume", error: "Must be a PDF under 5MB")) %>
3
+ </div>
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UI::FileFieldPreview < ViewComponent::Preview
4
+ # @label Playground
5
+ # @param label text
6
+ # @param hint text
7
+ # @param multiple toggle
8
+ # @param disabled toggle
9
+ def playground(label: "Avatar", hint: "PNG or JPG, up to 5MB", multiple: false, disabled: false)
10
+ render(UI::FileField.new(label: label, hint: hint, multiple: multiple, disabled: disabled))
11
+ end
12
+
13
+ # @label With Error
14
+ def with_error; render_with_template; end
15
+
16
+ # @label Multiple Files
17
+ def multiple_files; render_with_template; end
18
+ end
@@ -0,0 +1,46 @@
1
+ <%# Every action dispatches a cancelable ui--session-tabs:<action> event.
2
+ This page logs them, refuses to close "Pinned", and handles "add" itself
3
+ by cloning a <template>. In a real app, pass URLs instead and let the
4
+ server re-render. %>
5
+ <div class="max-w-2xl space-y-3" id="session-tabs-events-demo">
6
+ <%= render(UI::SessionTabs.new) do |tabs| %>
7
+ <% tabs.with_tab(value: "pinned", active: true, rename: true, move: true, close: true) { "Pinned" } %>
8
+ <% tabs.with_tab(value: "notes", rename: true, duplicate: true, move: true, close: true) { "Notes" } %>
9
+ <% tabs.with_add %>
10
+ <% end %>
11
+ <pre class="h-40 overflow-auto rounded-md bg-muted p-3 text-xs" data-log></pre>
12
+ </div>
13
+ <script>
14
+ (() => {
15
+ const root = document.getElementById("session-tabs-events-demo");
16
+ const log = root.querySelector("[data-log]");
17
+ let n = 0;
18
+ const write = (line) => { log.textContent = line + "\n" + log.textContent; };
19
+
20
+ for (const action of ["select", "add", "rename", "duplicate", "move", "close"]) {
21
+ root.addEventListener(`ui--session-tabs:${action}`, (event) => {
22
+ write(`${action} ${JSON.stringify(event.detail)}`);
23
+
24
+ if (action === "close" && event.detail.value === "pinned") {
25
+ event.preventDefault();
26
+ write(" ↳ cancelled: Pinned can't be closed");
27
+ }
28
+
29
+ if (action === "add" || action === "duplicate") {
30
+ // The app supplies new markup; here, copy an existing tab.
31
+ const list = root.querySelector('[role="tablist"]');
32
+ const source = list.querySelector('[data-value="notes"]') || list.lastElementChild;
33
+ const copy = source.cloneNode(true);
34
+ n += 1;
35
+ const value = `new-${n}`;
36
+ copy.dataset.value = value;
37
+ copy.dataset.state = "inactive";
38
+ copy.querySelectorAll("[id]").forEach((el) => { el.id = `${el.id}-${value}`; });
39
+ copy.querySelector('[data-ui--session-tabs-target="label"]').textContent =
40
+ action === "add" ? `New tab ${n}` : `Copy ${n}`;
41
+ list.appendChild(copy);
42
+ }
43
+ });
44
+ }
45
+ })();
46
+ </script>
@@ -0,0 +1,16 @@
1
+ <%# A "Default" view the user can't close or rename, plus views they made. %>
2
+ <div class="max-w-2xl">
3
+ <%= render(UI::SessionTabs.new(label: "Saved views")) do |tabs| %>
4
+ <% tabs.with_tab(value: "default", active: true, duplicate: true) do |tab| %>
5
+ <% tab.with_meta { "128" } %>Default
6
+ <% end %>
7
+ <% tabs.with_tab(value: "unpaid", rename: true, duplicate: true, move: true, close: true) do |tab| %>
8
+ <% tab.with_meta { "12" } %>Unpaid
9
+ <% end %>
10
+ <% tabs.with_tab(value: "this-week", rename: true, duplicate: true, move: true, close: true) do |tab| %>
11
+ <% tab.with_meta { "41" } %>This week
12
+ <% end %>
13
+ <% tabs.with_add %>
14
+ <% end %>
15
+ <div class="rounded-b-md border border-t-0 p-4 text-sm text-muted-foreground">The table for the selected view goes here.</div>
16
+ </div>
@@ -0,0 +1,20 @@
1
+ <%# Touch size: 44px tabs; long-press a tab to open its menu. Tabs with
2
+ unsaved work ask before closing; empty ones close straight away. %>
3
+ <div class="max-w-2xl space-y-3">
4
+ <%= render(UI::SessionTabs.new(size: :touch, return_focus: "#session-tabs-demo-input")) do |tabs| %>
5
+ <% tabs.with_tab(value: "1", active: true, rename: true, move: true, close: true,
6
+ close_confirm: "This tab has 3 unsaved items. They will be lost.") do |tab| %>
7
+ <% tab.with_meta { "3 items" } %>Tab 1
8
+ <% end %>
9
+ <% tabs.with_tab(value: "2", rename: true, move: true, close: true,
10
+ close_confirm: "This tab has 1 unsaved item. It will be lost.") do |tab| %>
11
+ <% tab.with_meta { "1 item" } %>Tab 2
12
+ <% end %>
13
+ <% tabs.with_tab(value: "3", rename: true, move: true, close: true) do |tab| %>
14
+ <% tab.with_meta { "Empty" } %>Tab 3
15
+ <% end %>
16
+ <% tabs.with_add %>
17
+ <% end %>
18
+ <input id="session-tabs-demo-input" class="h-11 w-full rounded-md border border-input bg-background px-3 text-sm"
19
+ placeholder="Focus comes back here after each tab action (return_focus:)">
20
+ </div>
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Tabs the user manages: rename, duplicate, reorder, close, add.
4
+ #
5
+ # Each action is opt-in per tab and takes either a URL (submitted as a Turbo
6
+ # form — rename PATCH, duplicate POST, move PATCH with a 1-based `position`,
7
+ # close DELETE) or `true` (only the cancelable `ui--session-tabs:<action>`
8
+ # event fires). These previews use events only, so nothing is saved.
9
+ class UI::SessionTabsPreview < ViewComponent::Preview
10
+ # @label Playground
11
+ # @param size select { choices: [default, touch] }
12
+ # @param min_tabs number
13
+ # @param rename toggle
14
+ # @param duplicate toggle
15
+ # @param move toggle
16
+ # @param close toggle
17
+ def playground(size: :default, min_tabs: 1, rename: true, duplicate: true, move: true, close: true)
18
+ render(UI::SessionTabs.new(size: size.to_sym, min_tabs: min_tabs.to_i)) do |tabs|
19
+ %w[Default Drafts Archive].each_with_index do |name, i|
20
+ tabs.with_tab(value: name.downcase, active: i.zero?,
21
+ rename: rename, duplicate: duplicate, move: move, close: close) { name }
22
+ end
23
+ tabs.with_add
24
+ end
25
+ end
26
+
27
+ # @label Saved views
28
+ def saved_views; render_with_template; end
29
+
30
+ # @label Touch, with close confirmation
31
+ def touch_with_confirmation; render_with_template; end
32
+
33
+ # @label Handling the events
34
+ def handling_events; render_with_template; end
35
+ end
@@ -0,0 +1,10 @@
1
+ <%= render(UI::Card.new(class: "w-80 p-6")) do %>
2
+ <div class="flex items-center gap-4">
3
+ <%= render(UI::Skeleton.new(shape: :circle)) %>
4
+ <div class="flex-1 space-y-2">
5
+ <%= render(UI::Skeleton.new(shape: :text, class: "w-3/4")) %>
6
+ <%= render(UI::Skeleton.new(shape: :text, class: "w-1/2")) %>
7
+ </div>
8
+ </div>
9
+ <%= render(UI::Skeleton.new(shape: :rectangle, class: "mt-4")) %>
10
+ <% end %>
@@ -0,0 +1,9 @@
1
+ <div class="flex flex-col gap-6">
2
+ <div class="space-y-2">
3
+ <%= render(UI::Skeleton.new(shape: :text, class: "w-64")) %>
4
+ <%= render(UI::Skeleton.new(shape: :text, class: "w-48")) %>
5
+ <%= render(UI::Skeleton.new(shape: :text, class: "w-56")) %>
6
+ </div>
7
+ <%= render(UI::Skeleton.new(shape: :circle)) %>
8
+ <%= render(UI::Skeleton.new(shape: :rectangle, class: "w-64")) %>
9
+ </div>
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UI::SkeletonPreview < ViewComponent::Preview
4
+ # @label Playground
5
+ # @param shape select { choices: [text, circle, rectangle] }
6
+ def playground(shape: :text)
7
+ render(UI::Skeleton.new(shape: shape.to_sym, class: shape.to_sym == :circle ? nil : "w-64"))
8
+ end
9
+
10
+ # @label Shapes
11
+ def shapes; render_with_template; end
12
+
13
+ # @label Card Placeholder
14
+ def card_placeholder; render_with_template; end
15
+ end
@@ -0,0 +1,21 @@
1
+ <div class="flex flex-wrap gap-2">
2
+ <%
3
+ demos = {
4
+ default: ["Notification", "Heads up, something happened."],
5
+ success: ["Saved", "Your changes have been saved."],
6
+ destructive: ["Something broke", "There was a problem with your request."],
7
+ warning: ["Careful", "This action cannot be undone."],
8
+ info: ["FYI", "Here's some helpful information."]
9
+ }
10
+ %>
11
+ <% demos.each do |variant, (title, description)| %>
12
+ <% payload = { title: title, description: description, variant: variant }.to_json %>
13
+ <%= render(UI::Button.new(variant: :outline, size: :sm,
14
+ onclick: "window.dispatchEvent(new CustomEvent('toast:show', { detail: #{payload} }))")) { title } %>
15
+ <% end %>
16
+ <% persistent = { title: "Stays until dismissed", description: "duration: 0 skips the auto-dismiss timer.", variant: :default, duration: 0 }.to_json %>
17
+ <%= render(UI::Button.new(variant: :outline, size: :sm,
18
+ onclick: "window.dispatchEvent(new CustomEvent('toast:show', { detail: #{persistent} }))")) { "Persistent" } %>
19
+ </div>
20
+
21
+ <%= render(UI::Toast::Viewport.new) %>
@@ -0,0 +1,7 @@
1
+ <div class="flex flex-col gap-4 max-w-sm">
2
+ <%= render(UI::Toast.new(variant: :default, title: "Default", description: "Heads up, something happened.")) %>
3
+ <%= render(UI::Toast.new(variant: :success, title: "Success", description: "Your changes have been saved.")) %>
4
+ <%= render(UI::Toast.new(variant: :destructive, title: "Destructive", description: "There was a problem with your request.")) %>
5
+ <%= render(UI::Toast.new(variant: :warning, title: "Warning", description: "This action cannot be undone.")) %>
6
+ <%= render(UI::Toast.new(variant: :info, title: "Info", description: "Here's some helpful information.")) %>
7
+ </div>
@@ -0,0 +1,7 @@
1
+ <div class="max-w-sm">
2
+ <%= render(UI::Toast.new(variant: :default, title: "Update available", duration: 0)) do |toast| %>
3
+ <% toast.with_action do %>
4
+ <%= render(UI::Button.new(size: :sm)) { "Reload" } %>
5
+ <% end %>
6
+ <% end %>
7
+ </div>
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UI::ToastPreview < ViewComponent::Preview
4
+ # @label Playground
5
+ # @param variant select { choices: [default, success, destructive, warning, info] }
6
+ # @param title text
7
+ # @param description text
8
+ # @param duration number Seconds before it auto-dismisses; 0 stays until dismissed.
9
+ # @param dismissible toggle
10
+ def playground(variant: :success, title: "Saved", description: "Your changes have been saved.",
11
+ duration: 5, dismissible: true)
12
+ render(UI::Toast.new(variant: variant.to_sym, title: title, description: description,
13
+ duration: duration, dismissible: dismissible))
14
+ end
15
+
16
+ # @label All Variants
17
+ def variants; render_with_template; end
18
+
19
+ # @label With Action
20
+ def with_action; render_with_template; end
21
+
22
+ # @label Live Viewport
23
+ #
24
+ # Each button fires the same `toast:show` event the `toast()` helper
25
+ # dispatches, so this is exactly what a client-triggered toast looks like:
26
+ # stacking, auto-dismiss and pause-on-hover all come from the real
27
+ # UI::Toast::Viewport and ui--toast controllers, not a preview-only stand-in.
28
+ def live_viewport; render_with_template; end
29
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "test_helper"
4
+
5
+ class UI::FileFieldTest < ViewComponent::TestCase
6
+ def setup_fixtures(*); end
7
+ def teardown_fixtures(*); end
8
+
9
+ def test_renders_a_file_input
10
+ render_inline(UI::FileField.new)
11
+ assert_selector "input[type='file']"
12
+ end
13
+
14
+ def test_input_is_screen_reader_only_not_hidden
15
+ render_inline(UI::FileField.new)
16
+ input = page.find("input", visible: :all)
17
+ assert_includes input[:class].split, "sr-only"
18
+ refute input[:hidden]
19
+ end
20
+
21
+ def test_dropzone_is_a_label_pointing_at_the_input
22
+ render_inline(UI::FileField.new)
23
+ label = page.find("label")
24
+ input = page.find("input", visible: :all)
25
+ assert_equal input[:id], label[:for]
26
+ end
27
+
28
+ def test_dropzone_wired_to_controller
29
+ render_inline(UI::FileField.new)
30
+ label = page.find("label")
31
+ assert_equal "ui--file-field", label["data-controller"]
32
+ assert_includes label["data-action"], "dragover->ui--file-field#dragOver"
33
+ assert_includes label["data-action"], "dragleave->ui--file-field#dragLeave"
34
+ assert_includes label["data-action"], "drop->ui--file-field#drop"
35
+ end
36
+
37
+ def test_input_wired_to_update_names_on_change
38
+ render_inline(UI::FileField.new)
39
+ input = page.find("input", visible: :all)
40
+ assert_includes input["data-action"], "change->ui--file-field#updateNames"
41
+ end
42
+
43
+ def test_not_multiple_by_default
44
+ render_inline(UI::FileField.new)
45
+ refute page.find("input", visible: :all)[:multiple]
46
+ end
47
+
48
+ def test_multiple
49
+ render_inline(UI::FileField.new(multiple: true))
50
+ assert page.find("input", visible: :all)[:multiple]
51
+ end
52
+
53
+ def test_accept
54
+ render_inline(UI::FileField.new(accept: "image/*"))
55
+ assert_equal "image/*", page.find("input", visible: :all)[:accept]
56
+ end
57
+
58
+ def test_disabled
59
+ render_inline(UI::FileField.new(disabled: true))
60
+ assert page.find("input", visible: :all)[:disabled]
61
+ assert_includes page.find("label")[:class], "opacity-50"
62
+ end
63
+
64
+ def test_error_true_marks_the_input_invalid
65
+ render_inline(UI::FileField.new(error: true))
66
+ input = page.find("input", visible: :all)
67
+ assert_equal "true", input["aria-invalid"]
68
+ assert_includes page.find("label")[:class], "border-destructive"
69
+ end
70
+
71
+ # --- form-builder binding (Rails convention) ---
72
+
73
+ class User
74
+ include ActiveModel::Model
75
+ attr_accessor :avatar
76
+ end
77
+
78
+ def form_builder_for(record)
79
+ ActionView::Helpers::FormBuilder.new(:user, record, vc_test_controller.view_context, {})
80
+ end
81
+
82
+ def test_form_binding_scopes_the_field_name
83
+ render_inline(UI::FileField.new(form: form_builder_for(User.new), field: :avatar))
84
+ assert_selector "input[type='file'][name='user[avatar]']"
85
+ end
86
+
87
+ def test_label_is_derived_from_the_attribute_name
88
+ render_inline(UI::FileField.new(form: form_builder_for(User.new), field: :avatar))
89
+ assert_selector "label", text: "Avatar"
90
+ end
91
+
92
+ def test_hint_renders
93
+ render_inline(UI::FileField.new(hint: "PNG or JPG, up to 5MB"))
94
+ assert_text "PNG or JPG, up to 5MB"
95
+ end
96
+
97
+ def test_html_attrs_passthrough
98
+ render_inline(UI::FileField.new(id: "my-id", data: { test_id: "f" }))
99
+ assert_selector "input#my-id[data-test-id='f']", visible: :all
100
+ end
101
+ end