velvetkit 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +23 -0
  3. data/lib/velvetkit/version.rb +1 -1
  4. data/registry/app/components/ui/carousel.html.erb +9 -4
  5. data/registry/app/components/ui/carousel.rb +42 -1
  6. data/registry/app/components/ui/file_tree/file_item.html.erb +9 -0
  7. data/registry/app/components/ui/file_tree/file_item.rb +50 -0
  8. data/registry/app/components/ui/file_tree/folder.html.erb +9 -0
  9. data/registry/app/components/ui/file_tree/folder.rb +76 -0
  10. data/registry/app/components/ui/file_tree.html.erb +1 -0
  11. data/registry/app/components/ui/file_tree.rb +93 -0
  12. data/registry/app/components/ui/rating.html.erb +16 -0
  13. data/registry/app/components/ui/rating.rb +200 -0
  14. data/registry/app/javascript/controllers/ui/carousel_controller.ts +59 -1
  15. data/registry/app/javascript/controllers/ui/file_tree_controller.ts +189 -0
  16. data/registry/app/javascript/controllers/ui/rating_controller.ts +117 -0
  17. data/registry/components.yml +4 -0
  18. data/registry/config/locales/velvetkit.en.yml +13 -0
  19. data/registry/test/components/previews/ui/carousel_preview/with_indicators.html.erb +10 -0
  20. data/registry/test/components/previews/ui/carousel_preview.rb +7 -3
  21. data/registry/test/components/previews/ui/file_tree_preview/changes.html.erb +13 -0
  22. data/registry/test/components/previews/ui/file_tree_preview/from_data.html.erb +14 -0
  23. data/registry/test/components/previews/ui/file_tree_preview/picking_a_file.html.erb +25 -0
  24. data/registry/test/components/previews/ui/file_tree_preview/without_guides.html.erb +10 -0
  25. data/registry/test/components/previews/ui/file_tree_preview.rb +41 -0
  26. data/registry/test/components/previews/ui/image_preview/radii.html.erb +3 -3
  27. data/registry/test/components/previews/ui/image_preview/sizing.html.erb +9 -4
  28. data/registry/test/components/previews/ui/image_preview.rb +14 -1
  29. data/registry/test/components/previews/ui/rating_preview/in_form.html.erb +6 -0
  30. data/registry/test/components/previews/ui/rating_preview/model_errors.html.erb +20 -0
  31. data/registry/test/components/previews/ui/rating_preview/playground.html.erb +5 -0
  32. data/registry/test/components/previews/ui/rating_preview/scores.html.erb +18 -0
  33. data/registry/test/components/previews/ui/rating_preview/sizes.html.erb +6 -0
  34. data/registry/test/components/previews/ui/rating_preview.rb +28 -0
  35. data/registry/test/components/ui/carousel_test.rb +48 -0
  36. data/registry/test/components/ui/file_tree_test.rb +187 -0
  37. data/registry/test/components/ui/rating_test.rb +271 -0
  38. metadata +25 -1
@@ -4,14 +4,17 @@ import { Controller } from '@hotwired/stimulus';
4
4
  //
5
5
  // The strip scrolls by itself (scroll-snap); this only moves it a page at a
6
6
  // time from the buttons, and shows each button while there's more that way.
7
+ // With indicators, it shows one for each place the strip can stop, lights the
8
+ // one in view, and scrolls to an indicator's card.
7
9
  const EDGE = 2;
8
10
 
9
11
  export default class extends Controller<HTMLElement> {
10
- static targets = ['track', 'previous', 'next'];
12
+ static targets = ['track', 'previous', 'next', 'indicator'];
11
13
 
12
14
  declare readonly trackTarget: HTMLElement;
13
15
  declare readonly previousTarget: HTMLButtonElement;
14
16
  declare readonly nextTarget: HTMLButtonElement;
17
+ declare readonly indicatorTargets: HTMLButtonElement[];
15
18
 
16
19
  private frame?: number;
17
20
  private observer?: ResizeObserver;
@@ -35,6 +38,12 @@ export default class extends Controller<HTMLElement> {
35
38
  this.page(1);
36
39
  }
37
40
 
41
+ go({ params }: { params: { index: number } }) {
42
+ const track = this.trackTarget;
43
+ const forward = getComputedStyle(track).direction === 'rtl' ? -1 : 1;
44
+ track.scrollTo({ left: forward * this.stops()[params.index] });
45
+ }
46
+
38
47
  update() {
39
48
  if (this.frame) return;
40
49
 
@@ -45,6 +54,7 @@ export default class extends Controller<HTMLElement> {
45
54
  const scrolled = Math.abs(track.scrollLeft);
46
55
  this.show(this.previousTarget, this.nextTarget, scrolled > EDGE);
47
56
  this.show(this.nextTarget, this.previousTarget, scrolled + track.clientWidth < track.scrollWidth - EDGE);
57
+ if (this.indicatorTargets.length) this.light(scrolled);
48
58
  });
49
59
  }
50
60
 
@@ -55,6 +65,54 @@ export default class extends Controller<HTMLElement> {
55
65
  track.scrollBy({ left: direction * forward * track.clientWidth * 0.85 });
56
66
  }
57
67
 
68
+ // How far the strip scrolls to bring each card to its start, held to the
69
+ // end: the last few cards can't reach the start, so they share the end.
70
+ private stops() {
71
+ const track = this.trackTarget;
72
+ const rtl = getComputedStyle(track).direction === 'rtl';
73
+ const box = track.getBoundingClientRect();
74
+ const scrolled = Math.abs(track.scrollLeft);
75
+ const end = track.scrollWidth - track.clientWidth;
76
+ const starts = Array.from(track.children, (item) => {
77
+ const card = item.getBoundingClientRect();
78
+ return (rtl ? box.right - card.right : card.left - box.left) + scrolled;
79
+ });
80
+ return starts.map((start) => Math.min(Math.max(start - starts[0], 0), end));
81
+ }
82
+
83
+ // An indicator for each place the strip can stop, and none when it can't scroll.
84
+ // Between two stops, the one it's leaving empties as the one it's nearing
85
+ // fills, in step with the scroll, so the pill slides with a finger rather
86
+ // than jumping halfway. The current one is the fuller of the two.
87
+ private light(scrolled: number) {
88
+ const stops = this.stops();
89
+ const shown = this.indicatorTargets.flatMap((_, index) =>
90
+ index === 0 || stops[index] - stops[index - 1] > EDGE ? [index] : [],
91
+ );
92
+ const fills = this.indicatorTargets.map(() => 0);
93
+ const after = shown.findIndex((index) => stops[index] > scrolled);
94
+ if (after <= 0) {
95
+ fills[shown[after === 0 ? 0 : shown.length - 1]] = 1;
96
+ } else {
97
+ const from = shown[after - 1];
98
+ const to = shown[after];
99
+ const progress = (scrolled - stops[from]) / (stops[to] - stops[from]);
100
+ fills[from] = 1 - progress;
101
+ fills[to] = progress;
102
+ }
103
+ const lit = fills.indexOf(Math.max(...fills));
104
+ const scrolls = shown.length > 1;
105
+
106
+ this.indicatorTargets.forEach((indicator, index) => {
107
+ const hidden = !scrolls || !shown.includes(index);
108
+ if (hidden && scrolls && document.activeElement === indicator) this.indicatorTargets[lit].focus();
109
+ indicator.hidden = hidden;
110
+ indicator.style.setProperty('--fill', fills[index].toFixed(3));
111
+ if (index === lit) indicator.setAttribute('aria-current', 'true');
112
+ else indicator.removeAttribute('aria-current');
113
+ });
114
+ }
115
+
58
116
  // A button that hides under the keyboard would drop focus to the page.
59
117
  private show(button: HTMLButtonElement, other: HTMLButtonElement, shown: boolean) {
60
118
  if (!shown && document.activeElement === button) other.focus();
@@ -0,0 +1,189 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // A file tree after the WAI-ARIA tree pattern: one row in the tab order, the
4
+ // arrow keys to move and to open and close folders, a letter to jump to a name.
5
+ // Picking a file that isn't a link selects it and dispatches
6
+ // `ui--file-tree:select` with `{ value, name }`.
7
+
8
+ // The curve iOS sheets and drawers settle on: quick to start, a long soft
9
+ // landing.
10
+ const EASING = 'cubic-bezier(0.32, 0.72, 0, 1)';
11
+ const OPEN_MS = 380;
12
+ const CLOSE_MS = 300;
13
+
14
+ export default class extends Controller<HTMLElement> {
15
+ static targets = ['item'];
16
+
17
+ declare readonly itemTargets: HTMLElement[];
18
+
19
+ private animations = new Map<HTMLElement, Animation>();
20
+ private reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
21
+
22
+ disconnect() {
23
+ this.animations.forEach((animation) => animation.finish());
24
+ }
25
+
26
+ connect() {
27
+ const visible = this.visibleItems();
28
+ const start = visible.find((item) => item.getAttribute('aria-selected') === 'true') ?? visible[0];
29
+ if (start) this.makeTabbable(start);
30
+ }
31
+
32
+ click(event: MouseEvent) {
33
+ const item = this.itemFor(event.target);
34
+ if (!item) return;
35
+ this.makeTabbable(item);
36
+ if (this.isFolder(item)) this.setOpen(item, !this.isOpen(item));
37
+ else this.select(item);
38
+ }
39
+
40
+ keydown(event: KeyboardEvent) {
41
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
42
+ const item = this.itemFor(event.target);
43
+ if (!item) return;
44
+ const visible = this.visibleItems();
45
+ const index = visible.indexOf(item);
46
+ const rtl = getComputedStyle(this.element).direction === 'rtl';
47
+ const key = rtl && event.key === 'ArrowLeft' ? 'ArrowRight' : rtl && event.key === 'ArrowRight' ? 'ArrowLeft' : event.key;
48
+ let next: HTMLElement | null | undefined;
49
+
50
+ switch (key) {
51
+ case 'ArrowDown':
52
+ next = visible[index + 1];
53
+ break;
54
+ case 'ArrowUp':
55
+ next = visible[index - 1];
56
+ break;
57
+ case 'Home':
58
+ next = visible[0];
59
+ break;
60
+ case 'End':
61
+ next = visible[visible.length - 1];
62
+ break;
63
+ case 'ArrowRight':
64
+ if (!this.isFolder(item)) break;
65
+ if (this.isOpen(item)) next = this.childrenOf(item)[0];
66
+ else this.setOpen(item, true);
67
+ break;
68
+ case 'ArrowLeft':
69
+ if (this.isFolder(item) && this.isOpen(item)) this.setOpen(item, false);
70
+ else next = this.parentOf(item);
71
+ break;
72
+ case 'Enter':
73
+ case ' ':
74
+ // Enter on a link follows it, and the click that makes marks it.
75
+ if (key === 'Enter' && item instanceof HTMLAnchorElement) return;
76
+ item.click();
77
+ break;
78
+ default:
79
+ if (key.length !== 1 || key === ' ') return;
80
+ next = this.startingWith(visible, index, key);
81
+ if (!next) return;
82
+ }
83
+
84
+ event.preventDefault();
85
+ if (next) {
86
+ this.makeTabbable(next);
87
+ next.focus();
88
+ }
89
+ }
90
+
91
+ private itemFor(target: EventTarget | null): HTMLElement | null {
92
+ const item = (target as Element | null)?.closest<HTMLElement>('[role="treeitem"]');
93
+ return item && this.itemTargets.includes(item) ? item : null;
94
+ }
95
+
96
+ // A closing group is still drawn until its animation ends, but its rows are
97
+ // already out of reach of the keyboard.
98
+ private visibleItems(): HTMLElement[] {
99
+ return this.itemTargets.filter((item) => !item.closest('[role="group"][data-state="closed"]'));
100
+ }
101
+
102
+ private isFolder(item: HTMLElement) {
103
+ return item.hasAttribute('aria-expanded');
104
+ }
105
+
106
+ private isOpen(item: HTMLElement) {
107
+ return item.getAttribute('aria-expanded') === 'true';
108
+ }
109
+
110
+ private groupOf(item: HTMLElement): HTMLElement | null {
111
+ const id = item.getAttribute('aria-owns');
112
+ return id ? document.getElementById(id) : null;
113
+ }
114
+
115
+ private setOpen(item: HTMLElement, open: boolean) {
116
+ item.setAttribute('aria-expanded', String(open));
117
+ const group = this.groupOf(item);
118
+ if (!group) return;
119
+ group.dataset.state = open ? 'open' : 'closed';
120
+ this.animate(group, open);
121
+ }
122
+
123
+ // Grows or shrinks the group between nothing and its full height while its
124
+ // rows fade and settle into place. Clicked again part way, it turns round
125
+ // from wherever it has got to rather than starting over.
126
+ private animate(group: HTMLElement, open: boolean) {
127
+ const running = this.animations.get(group);
128
+ const from = group.hidden ? 0 : group.getBoundingClientRect().height;
129
+ const opacity = group.hidden ? 0 : Number(getComputedStyle(group).opacity);
130
+ running?.cancel();
131
+ group.hidden = false;
132
+ group.inert = !open;
133
+
134
+ if (this.reducedMotion.matches) {
135
+ group.hidden = !open;
136
+ return;
137
+ }
138
+
139
+ const to = open ? group.scrollHeight : 0;
140
+ const animation = group.animate(
141
+ [
142
+ { height: `${from}px`, opacity, transform: `translateY(${open && !running ? -6 : 0}px)` },
143
+ { height: `${to}px`, opacity: open ? 1 : 0, transform: `translateY(${open ? 0 : -4}px)` },
144
+ ],
145
+ { duration: open ? OPEN_MS : CLOSE_MS, easing: EASING },
146
+ );
147
+ group.style.overflow = 'hidden';
148
+ this.animations.set(group, animation);
149
+
150
+ animation.onfinish = () => {
151
+ this.animations.delete(group);
152
+ group.style.overflow = '';
153
+ group.inert = false;
154
+ if (!open) group.hidden = true;
155
+ };
156
+ }
157
+
158
+ private childrenOf(item: HTMLElement): HTMLElement[] {
159
+ const group = this.groupOf(item);
160
+ return group ? Array.from(group.querySelectorAll<HTMLElement>(':scope > li > [role="treeitem"]')) : [];
161
+ }
162
+
163
+ private parentOf(item: HTMLElement): HTMLElement | null {
164
+ const group = item.closest<HTMLElement>('[role="group"]');
165
+ return group?.parentElement?.querySelector<HTMLElement>(':scope > [role="treeitem"]') ?? null;
166
+ }
167
+
168
+ // The next visible row, after this one and round to the top, whose name
169
+ // starts with the letter typed.
170
+ private startingWith(visible: HTMLElement[], index: number, letter: string) {
171
+ const wanted = letter.toLocaleLowerCase();
172
+ for (let step = 1; step <= visible.length; step++) {
173
+ const candidate = visible[(index + step) % visible.length];
174
+ if (candidate?.dataset.name?.toLocaleLowerCase().startsWith(wanted)) return candidate;
175
+ }
176
+ return undefined;
177
+ }
178
+
179
+ private makeTabbable(item: HTMLElement) {
180
+ this.itemTargets.forEach((other) => (other.tabIndex = other === item ? 0 : -1));
181
+ }
182
+
183
+ private select(item: HTMLElement) {
184
+ this.itemTargets.forEach((other) => {
185
+ if (other.hasAttribute('aria-selected')) other.setAttribute('aria-selected', String(other === item));
186
+ });
187
+ this.dispatch('select', { detail: { value: item.dataset.value ?? '', name: item.dataset.name ?? '' } });
188
+ }
189
+ }
@@ -0,0 +1,117 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // Connects to data-controller="ui--rating"
4
+ //
5
+ // Each half-star is the label of a radio, and CSS fills the stars up to the
6
+ // checked one. Over a half-star, this lights that half and the ones before it,
7
+ // and grows the star it's in; leaving the stars, or choosing one, hands them
8
+ // back. It also gives the choice some feedback: a chosen star settles back to
9
+ // size, or pops when chosen from the keyboard. Choosing also clears the field's error, if it has one, and
10
+ // shows its thanks, if it has those, and writes the score beside the stars, if
11
+ // it's shown; resetting the form brings them back as they were (the score is an
12
+ // <output>, which the form resets itself).
13
+ export default class extends Controller<HTMLElement> {
14
+ static targets = ['star'];
15
+ static values = { error: String, thanks: String, score: String };
16
+
17
+ declare readonly starTargets: HTMLLabelElement[];
18
+ declare readonly errorValue: string;
19
+ declare readonly thanksValue: string;
20
+ declare readonly scoreValue: string;
21
+
22
+ // The star just chosen under the pointer, kept at its size until the
23
+ // pointer moves to another.
24
+ private settled: number | null = null;
25
+
26
+ preview(event: MouseEvent) {
27
+ const star = event.currentTarget as HTMLLabelElement;
28
+ if ((star.control as HTMLInputElement | null)?.disabled) return;
29
+
30
+ const value = Number(star.dataset.value);
31
+ this.starTargets.forEach((each) => {
32
+ each.dataset.lit = String(Number(each.dataset.value) <= value);
33
+ });
34
+
35
+ const whole = Math.ceil(value);
36
+ if (whole !== this.settled) this.settled = null;
37
+ this.hover(this.settled === null ? this.halvesOf(whole) : []);
38
+ }
39
+
40
+ reset() {
41
+ for (const star of this.starTargets) delete star.dataset.lit;
42
+ this.hover([]);
43
+ this.settled = null;
44
+ }
45
+
46
+ choose(event: Event) {
47
+ const input = event.target as HTMLInputElement;
48
+ const whole = Math.ceil(Number(input.value));
49
+ const halves = this.halvesOf(whole);
50
+
51
+ for (const star of this.starTargets) delete star.dataset.lit;
52
+
53
+ if (halves.some((half) => half.dataset.hovered)) {
54
+ this.hover([]);
55
+ this.settled = whole;
56
+ } else {
57
+ this.pop(halves);
58
+ }
59
+
60
+ this.showAnswered(true);
61
+
62
+ // The chosen star carries its score, "4.5/5". Its value, not its text,
63
+ // which is what the form's reset goes back to.
64
+ const score = this.scoreValue && (document.getElementById(this.scoreValue) as HTMLOutputElement | null);
65
+ if (score) score.value = input.labels?.[0]?.dataset.score ?? '';
66
+ }
67
+
68
+ // The form's reset puts the radios back; this puts back the rest.
69
+ formReset(event: Event) {
70
+ if (!(event.target as Node).contains(this.element)) return;
71
+
72
+ this.reset();
73
+ this.showAnswered(false);
74
+ }
75
+
76
+ // Answered, the error's hidden and gone from what the group says about
77
+ // itself, and the thanks, which are a status, are read out as they show.
78
+ private showAnswered(answered: boolean) {
79
+ const error = this.errorValue && document.getElementById(this.errorValue);
80
+ if (error) {
81
+ error.hidden = answered;
82
+ const group = this.element.closest('[role="radiogroup"]');
83
+ const others = (group?.getAttribute('aria-describedby') ?? '').split(' ').filter((id) => id && id !== this.errorValue);
84
+ const describedby = answered ? others : [...others, this.errorValue];
85
+ if (answered) group?.removeAttribute('aria-invalid');
86
+ else group?.setAttribute('aria-invalid', 'true');
87
+ if (describedby.length) group?.setAttribute('aria-describedby', describedby.join(' '));
88
+ else group?.removeAttribute('aria-describedby');
89
+ }
90
+
91
+ const thanks = this.thanksValue && document.getElementById(this.thanksValue);
92
+ if (thanks) thanks.hidden = !answered;
93
+ }
94
+
95
+ // Both half-star labels of a whole star.
96
+ private halvesOf(whole: number) {
97
+ return this.starTargets.filter((each) => Math.ceil(Number(each.dataset.value)) === whole);
98
+ }
99
+
100
+ private hover(halves: HTMLLabelElement[]) {
101
+ for (const star of this.starTargets) {
102
+ if (halves.includes(star)) star.dataset.hovered = 'true';
103
+ else delete star.dataset.hovered;
104
+ }
105
+ }
106
+
107
+ private pop(halves: HTMLLabelElement[]) {
108
+ if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
109
+
110
+ for (const half of halves) {
111
+ half.animate([1, 1.25, 1].map((scale) => ({ transform: `scale(${scale})` })), {
112
+ duration: 250,
113
+ easing: 'ease-out',
114
+ });
115
+ }
116
+ }
117
+ }
@@ -68,6 +68,8 @@ components:
68
68
  description: A group of controls under one legend, with a hint and an error message for the group.
69
69
  file_field:
70
70
  description: A drag-and-drop file picker with previews, and direct upload to storage, standalone or with a form builder.
71
+ file_tree:
72
+ description: Folders and files in a tree that opens and closes, with arrow keys to move through it.
71
73
  form_field:
72
74
  description: A label, hint and error message wired to any form control.
73
75
  gallery:
@@ -105,6 +107,8 @@ components:
105
107
  description: A bar showing how far along a task is, or that it's still going.
106
108
  radio_group:
107
109
  description: A set of radio buttons.
110
+ rating:
111
+ description: A score in stars, shown to the half star with its count, or chosen with a radio for each star.
108
112
  native_select:
109
113
  description: The browser's own select, styled closed; best for phones' system pickers.
110
114
  scan_input:
@@ -33,6 +33,8 @@ en:
33
33
  roledescription: 'carousel'
34
34
  previous: 'Previous'
35
35
  next: 'Next'
36
+ indicators: 'Choose a slide'
37
+ indicator: 'Go to slide %{number}'
36
38
  chart:
37
39
  label: 'Chart'
38
40
  keyboard: 'Use the arrow keys to read each value.'
@@ -80,6 +82,15 @@ en:
80
82
  progress:
81
83
  label: 'Progress'
82
84
  value_text: '%{percent}%'
85
+ rating:
86
+ name: 'Rating'
87
+ label: 'Rated %{value} out of %{max}'
88
+ option: '%{count} out of %{max}'
89
+ thanks: 'Thank you for your rating'
90
+ score: '%{value}/%{max}'
91
+ count:
92
+ one: '%{count} rating'
93
+ other: '%{count} ratings'
83
94
  slider:
84
95
  from: 'Minimum'
85
96
  to: 'Maximum'
@@ -170,6 +181,8 @@ en:
170
181
  position: 'Image %{current} of %{total}'
171
182
  open: 'Open %{alt}'
172
183
  info: 'Info'
184
+ file_tree:
185
+ label: 'Files'
173
186
  file_field:
174
187
  browse: 'Click to upload'
175
188
  drop: 'or drag and drop'
@@ -0,0 +1,10 @@
1
+ <%# One photo at a time, with an indicator for each. The indicators are the way
2
+ through on a phone, where the buttons don't show; turn them on with
3
+ `indicators: true`. %>
4
+ <%= render(UI::Carousel.new(label: "Featured", item_class: "basis-full", indicators: true, class: "max-w-2xl")) do |carousel| %>
5
+ <% UI::GalleryPreview.photos.each do |title, src| %>
6
+ <% carousel.with_item do %>
7
+ <%= image_tag src, alt: title, class: "aspect-[16/9] w-full rounded-xl object-cover" %>
8
+ <% end %>
9
+ <% end %>
10
+ <% end %>
@@ -3,9 +3,10 @@
3
3
  class UI::CarouselPreview < ViewComponent::Preview
4
4
  # @label Playground
5
5
  # @param count number { min: 1, max: 12 }
6
- # @param item_class select { choices: [w-48, w-64, basis-1/2, basis-1/3] }
7
- def playground(count: 8, item_class: "w-48")
8
- render(UI::Carousel.new(label: "Albums", item_class: item_class, class: "max-w-2xl")) do |carousel|
6
+ # @param item_class select { choices: [w-48, w-64, basis-1/2, basis-1/3, basis-full] }
7
+ # @param indicators toggle
8
+ def playground(count: 8, item_class: "w-48", indicators: false)
9
+ render(UI::Carousel.new(label: "Albums", item_class: item_class, indicators: indicators, class: "max-w-2xl")) do |carousel|
9
10
  UI::GalleryPreview.photos.cycle.first(count.to_i).each_with_index do |(title, src), index|
10
11
  carousel.with_item do
11
12
  tag.a(href: "#", class: "group block space-y-2 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary") do
@@ -19,4 +20,7 @@ class UI::CarouselPreview < ViewComponent::Preview
19
20
 
20
21
  # @label Highlights
21
22
  def highlights; render_with_template; end
23
+
24
+ # @label With indicators
25
+ def with_indicators; render_with_template; end
22
26
  end
@@ -0,0 +1,13 @@
1
+ <%# The block shows at the end of a file's row. %>
2
+ <%= render(UI::FileTree.new(label: "Changed files", class: "max-w-xs")) do |tree| %>
3
+ <% tree.with_folder(name: "app", open: true) do |app| %>
4
+ <% app.with_folder(name: "controllers", open: true) do |controllers| %>
5
+ <% controllers.with_file(name: "orders_controller.rb", value: "app/controllers/orders_controller.rb") do %><span class="text-amber-600 dark:text-amber-400">M</span><% end %>
6
+ <% end %>
7
+ <% app.with_folder(name: "models", open: true) do |models| %>
8
+ <% models.with_file(name: "order.rb", value: "app/models/order.rb") do %><span class="text-amber-600 dark:text-amber-400">M</span><% end %>
9
+ <% models.with_file(name: "refund.rb", value: "app/models/refund.rb", active: true) do %><span class="text-emerald-600 dark:text-emerald-400">A</span><% end %>
10
+ <% end %>
11
+ <% end %>
12
+ <% tree.with_file(name: "legacy_export.rb", value: "legacy_export.rb") do %><span class="text-destructive">D</span><% end %>
13
+ <% end %>
@@ -0,0 +1,14 @@
1
+ <%# A hash with `children:` is a folder; any other is a file. %>
2
+ <%= render(UI::FileTree.new(label: "Documents", class: "max-w-xs", items: [
3
+ { name: "Contracts", children: [
4
+ { name: "2025", children: [
5
+ { name: "Acme MSA.pdf", value: "contracts/2025/acme-msa.pdf" },
6
+ { name: "Globex NDA.pdf", value: "contracts/2025/globex-nda.pdf" }
7
+ ] },
8
+ { name: "2026", children: [
9
+ { name: "Initech SOW.pdf", value: "contracts/2026/initech-sow.pdf", active: true }
10
+ ] }
11
+ ] },
12
+ { name: "Invoices", children: [] },
13
+ { name: "Brand guide.pdf", value: "brand-guide.pdf", icon: "file-text" }
14
+ ])) %>
@@ -0,0 +1,25 @@
1
+ <div id="file-tree-picking-demo" class="grid max-w-2xl gap-4 sm:grid-cols-[14rem_1fr]">
2
+ <%= render(UI::FileTree.new(label: "Source")) do |tree| %>
3
+ <% tree.with_folder(name: "src") do |src| %>
4
+ <% src.with_folder(name: "lib") do |lib| %>
5
+ <% lib.with_file(name: "format.ts", value: "src/lib/format.ts") %>
6
+ <% lib.with_file(name: "money.ts", value: "src/lib/money.ts") %>
7
+ <% end %>
8
+ <% src.with_file(name: "index.ts", value: "src/index.ts", active: true) %>
9
+ <% end %>
10
+ <% tree.with_file(name: "package.json", value: "package.json") %>
11
+ <% tree.with_file(name: "tsconfig.json", value: "tsconfig.json") %>
12
+ <% end %>
13
+ <div class="rounded-lg border bg-muted/40 p-4 font-mono text-sm">
14
+ <p class="text-muted-foreground">Selected</p>
15
+ <p data-demo="path" class="mt-1 text-foreground">src/index.ts</p>
16
+ </div>
17
+ </div>
18
+ <script>
19
+ (() => {
20
+ const root = document.getElementById("file-tree-picking-demo");
21
+ root.addEventListener("ui--file-tree:select", (event) => {
22
+ root.querySelector('[data-demo="path"]').textContent = event.detail.value;
23
+ });
24
+ })();
25
+ </script>
@@ -0,0 +1,10 @@
1
+ <%= render(UI::FileTree.new(label: "Project files", guides: false, class: "max-w-xs")) do |tree| %>
2
+ <% tree.with_folder(name: "app", open: true) do |app| %>
3
+ <% app.with_folder(name: "views", open: true) do |views| %>
4
+ <% views.with_file(name: "index.html.erb", value: "app/views/index.html.erb") %>
5
+ <% views.with_file(name: "show.html.erb", value: "app/views/show.html.erb", active: true) %>
6
+ <% end %>
7
+ <% app.with_file(name: "application.rb", value: "app/application.rb") %>
8
+ <% end %>
9
+ <% tree.with_file(name: "Gemfile", value: "Gemfile") %>
10
+ <% end %>
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UI::FileTreePreview < ViewComponent::Preview
4
+ # @label Playground
5
+ # @param guides toggle
6
+ # @param open toggle "Open every folder, whatever the active file"
7
+ # @param links toggle "Files are links, not rows to pick"
8
+ def playground(guides: true, open: false, links: true)
9
+ href = ->(path) { "#/blob/#{path}" if links }
10
+ open = open || nil
11
+ render(UI::FileTree.new(label: "Project files", guides: guides, class: "max-w-xs")) do |tree|
12
+ tree.with_folder(name: "app", open: open) do |app|
13
+ app.with_folder(name: "components", open: open) do |components|
14
+ components.with_file(name: "button.rb", href: href.("app/components/button.rb"), active: true)
15
+ components.with_file(name: "button.html.erb", href: href.("app/components/button.html.erb"))
16
+ components.with_file(name: "card.rb", href: href.("app/components/card.rb"))
17
+ end
18
+ app.with_folder(name: "models", open: open) do |models|
19
+ models.with_file(name: "user.rb", href: href.("app/models/user.rb"))
20
+ end
21
+ end
22
+ tree.with_folder(name: "config", open: open) do |config|
23
+ config.with_file(name: "routes.rb", href: href.("config/routes.rb"))
24
+ end
25
+ tree.with_file(name: "Gemfile", href: href.("Gemfile"))
26
+ tree.with_file(name: "README.md", href: href.("README.md"), icon: "file-text")
27
+ end
28
+ end
29
+
30
+ # @label From Data
31
+ def from_data; render_with_template; end
32
+
33
+ # @label Picking a File
34
+ def picking_a_file; render_with_template; end
35
+
36
+ # @label Changes, with Badges
37
+ def changes; render_with_template; end
38
+
39
+ # @label Without Guides
40
+ def without_guides; render_with_template; end
41
+ end
@@ -1,7 +1,7 @@
1
- <div class="flex flex-wrap items-end gap-6">
2
- <% %i[none sm md lg xl full].each do |r| %>
1
+ <div class="flex flex-wrap gap-6">
2
+ <% %i[none xs sm md lg xl full].each do |r| %>
3
3
  <div class="flex flex-col items-center gap-2">
4
- <%= render(UI::Image.new(src: "/icon.png", rounded: r, width: "48px", height: "48px")) %>
4
+ <%= render(UI::Image.new(src: UI::ImagePreview.photo, alt: "Mountains at sunset", rounded: r, width: "96px", height: "96px")) %>
5
5
  <span class="text-xs text-muted-foreground"><%= r %></span>
6
6
  </div>
7
7
  <% end %>
@@ -1,9 +1,14 @@
1
- <%# Dimensions land on the <img> itself, not on a wrapper. %>
2
- <div class="flex flex-wrap items-end gap-6">
1
+ <%# Dimensions land on the <img> itself, not on a wrapper; the height follows the image's own ratio. %>
2
+ <div class="flex flex-wrap items-end gap-8">
3
3
  <% ["48px", "96px", "160px"].each do |w| %>
4
4
  <div class="flex flex-col items-center gap-2">
5
- <%= render(UI::Image.new(src: "/icon.png", rounded: :md, width: w)) %>
6
- <span class="text-xs text-muted-foreground">width: <%= w %></span>
5
+ <%= render(UI::Image.new(src: UI::ImagePreview.photo, alt: "Mountains at sunset", rounded: :md, width: w)) %>
6
+ <div class="flex items-center text-muted-foreground" style="width: <%= w %>" aria-hidden="true">
7
+ <span class="h-2 border-l border-current"></span>
8
+ <span class="flex-1 border-t border-current"></span>
9
+ <span class="h-2 border-r border-current"></span>
10
+ </div>
11
+ <span class="text-xs text-muted-foreground"><%= w %></span>
7
12
  </div>
8
13
  <% end %>
9
14
  </div>
@@ -1,11 +1,24 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class UI::ImagePreview < ViewComponent::Preview
4
+ # Drawn here so the previews need no image files. It fills its frame edge to
5
+ # edge (`slice`), so the corners show the radius and the size reads at a glance.
6
+ def self.photo
7
+ svg = "<svg xmlns='http://www.w3.org/2000/svg' width='400' height='300' viewBox='0 0 400 300' " \
8
+ "preserveAspectRatio='xMidYMid slice'>" \
9
+ "<defs><linearGradient id='sky' x2='0' y2='1'><stop stop-color='#c4b5fd'/><stop offset='1' stop-color='#fde68a'/>" \
10
+ "</linearGradient></defs><rect width='400' height='300' fill='url(#sky)'/>" \
11
+ "<circle cx='290' cy='110' r='42' fill='#f59e0b'/>" \
12
+ "<path d='M0 300V190l90-80 70 60 80-90 90 100 70-50v170z' fill='#7c3aed'/>" \
13
+ "<path d='M0 300V240l110-60 90 50 100-40 100 60v50z' fill='#4c1d95'/></svg>"
14
+ "data:image/svg+xml,#{ERB::Util.url_encode(svg)}"
15
+ end
16
+
4
17
  # @label Playground
5
18
  # @param rounded select { choices: [none, xs, sm, md, lg, xl, full] }
6
19
  # @param width text
7
20
  def playground(rounded: :sm, width: "160px")
8
- render(UI::Image.new(src: "/icon.png", rounded: rounded.to_sym, width: width))
21
+ render(UI::Image.new(src: self.class.photo, alt: "Mountains at sunset", rounded: rounded.to_sym, width: width))
9
22
  end
10
23
 
11
24
  # @label Radii
@@ -0,0 +1,6 @@
1
+ <%# A radio for each star: it posts with the form and needs no JavaScript. Arrow keys move between the stars. %>
2
+ <form class="flex max-w-sm flex-col gap-6" action="#" onsubmit="event.preventDefault()">
3
+ <%= render(UI::Rating.new(name: "review[rating]", legend: "Your rating", hint: "How did the kettle work for you?", required: true, size: :lg)) %>
4
+ <%= render(UI::Textarea.new(name: "review[body]", label: "Review", rows: 3)) %>
5
+ <%= render(UI::Button.new(type: :submit, class: "self-start")) { "Post review" } %>
6
+ </form>