velvetkit 0.3.0 → 0.4.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 (175) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +80 -0
  3. data/README.md +5 -1
  4. data/lib/generators/velvetkit/add/add_generator.rb +58 -0
  5. data/lib/velvetkit/version.rb +4 -1
  6. data/lib/velvetkit.rb +7 -0
  7. data/registry/app/assets/tailwind/velvetkit.css +90 -155
  8. data/registry/app/components/ui/chart.html.erb +47 -0
  9. data/registry/app/components/ui/chart.rb +177 -0
  10. data/registry/app/components/ui/command/group.rb +27 -0
  11. data/registry/app/components/ui/command/item.rb +64 -0
  12. data/registry/app/components/ui/command.html.erb +41 -0
  13. data/registry/app/components/ui/command.rb +122 -0
  14. data/registry/app/components/ui/date_picker.html.erb +58 -64
  15. data/registry/app/components/ui/date_picker.rb +199 -75
  16. data/registry/app/components/ui/file_field.html.erb +14 -4
  17. data/registry/app/components/ui/file_field.rb +179 -28
  18. data/registry/app/components/ui/gallery/image.rb +20 -0
  19. data/registry/app/components/ui/gallery.html.erb +52 -0
  20. data/registry/app/components/ui/gallery.rb +164 -0
  21. data/registry/app/components/ui/kbd.html.erb +27 -0
  22. data/registry/app/components/ui/kbd.rb +134 -0
  23. data/registry/app/components/ui/number_input.html.erb +11 -0
  24. data/registry/app/components/ui/number_input.rb +103 -0
  25. data/registry/app/components/ui/progress/segment.rb +25 -0
  26. data/registry/app/components/ui/progress.html.erb +25 -0
  27. data/registry/app/components/ui/progress.rb +182 -0
  28. data/registry/app/components/ui/select.html.erb +24 -5
  29. data/registry/app/components/ui/select.rb +44 -5
  30. data/registry/app/components/ui/timeline/item.html.erb +21 -0
  31. data/registry/app/components/ui/timeline/item.rb +145 -0
  32. data/registry/app/components/ui/timeline.html.erb +1 -0
  33. data/registry/app/components/ui/timeline.rb +42 -0
  34. data/registry/app/javascript/chart_js.ts +37 -0
  35. data/registry/app/javascript/controllers/ui/_internal/date_format.ts +74 -0
  36. data/registry/app/javascript/controllers/ui/_internal/shortcut.ts +80 -0
  37. data/registry/app/javascript/controllers/ui/chart_controller.ts +585 -0
  38. data/registry/app/javascript/controllers/ui/command_controller.ts +454 -0
  39. data/registry/app/javascript/controllers/ui/date_picker_controller.ts +247 -82
  40. data/registry/app/javascript/controllers/ui/file_field_controller.ts +288 -16
  41. data/registry/app/javascript/controllers/ui/gallery_controller.ts +568 -0
  42. data/registry/app/javascript/controllers/ui/kbd_controller.ts +60 -0
  43. data/registry/app/javascript/controllers/ui/number_input_controller.ts +111 -0
  44. data/registry/app/javascript/controllers/ui/progress_controller.ts +87 -0
  45. data/registry/app/javascript/controllers/ui/select_controller.ts +198 -8
  46. data/registry/app/javascript/vanilla_calendar.ts +15 -0
  47. data/registry/components.yml +19 -3
  48. data/registry/config/locales/velvetkit.en.yml +73 -0
  49. data/registry/icons/lucide/download.svg +17 -0
  50. data/registry/icons/lucide/file-plus.svg +18 -0
  51. data/registry/icons/lucide/file.svg +16 -0
  52. data/registry/icons/lucide/folder.svg +15 -0
  53. data/registry/icons/lucide/keyboard.svg +23 -0
  54. data/registry/icons/lucide/minus.svg +15 -0
  55. data/registry/icons/lucide/package.svg +18 -0
  56. data/registry/icons/lucide/pause.svg +16 -0
  57. data/registry/icons/lucide/percent.svg +17 -0
  58. data/registry/icons/lucide/printer.svg +17 -0
  59. data/registry/icons/lucide/receipt.svg +17 -0
  60. data/registry/icons/lucide/sun-moon.svg +19 -0
  61. data/registry/icons/lucide/truck.svg +19 -0
  62. data/registry/icons/lucide/user-plus.svg +18 -0
  63. data/registry/icons/lucide/zoom-in.svg +18 -0
  64. data/registry/icons/lucide/zoom-out.svg +17 -0
  65. data/registry/icons/phosphor/circle-half.svg +2 -0
  66. data/registry/icons/phosphor/download-simple.svg +2 -0
  67. data/registry/icons/phosphor/file-plus.svg +2 -0
  68. data/registry/icons/phosphor/file.svg +2 -0
  69. data/registry/icons/phosphor/folder.svg +2 -0
  70. data/registry/icons/phosphor/keyboard.svg +2 -0
  71. data/registry/icons/phosphor/magnifying-glass-minus.svg +2 -0
  72. data/registry/icons/phosphor/magnifying-glass-plus.svg +2 -0
  73. data/registry/icons/phosphor/minus.svg +2 -0
  74. data/registry/icons/phosphor/package.svg +2 -0
  75. data/registry/icons/phosphor/pause.svg +2 -0
  76. data/registry/icons/phosphor/percent.svg +2 -0
  77. data/registry/icons/phosphor/printer.svg +2 -0
  78. data/registry/icons/phosphor/receipt.svg +2 -0
  79. data/registry/icons/phosphor/truck.svg +2 -0
  80. data/registry/icons/phosphor/user-plus.svg +2 -0
  81. data/registry/icons/tabler/download.svg +18 -0
  82. data/registry/icons/tabler/file-plus.svg +19 -0
  83. data/registry/icons/tabler/file.svg +17 -0
  84. data/registry/icons/tabler/folder.svg +16 -0
  85. data/registry/icons/tabler/keyboard.svg +23 -0
  86. data/registry/icons/tabler/minus.svg +16 -0
  87. data/registry/icons/tabler/package.svg +20 -0
  88. data/registry/icons/tabler/percentage.svg +18 -0
  89. data/registry/icons/tabler/player-pause.svg +17 -0
  90. data/registry/icons/tabler/printer.svg +18 -0
  91. data/registry/icons/tabler/receipt.svg +16 -0
  92. data/registry/icons/tabler/sun-moon.svg +21 -0
  93. data/registry/icons/tabler/truck.svg +18 -0
  94. data/registry/icons/tabler/user-plus.svg +19 -0
  95. data/registry/icons/tabler/zoom-in.svg +19 -0
  96. data/registry/icons/tabler/zoom-out.svg +18 -0
  97. data/registry/icons.yml +16 -0
  98. data/registry/test/components/previews/ui/chart_preview/cash_flow.html.erb +6 -0
  99. data/registry/test/components/previews/ui/chart_preview/donut.html.erb +6 -0
  100. data/registry/test/components/previews/ui/chart_preview/margin.html.erb +6 -0
  101. data/registry/test/components/previews/ui/chart_preview/pie.html.erb +6 -0
  102. data/registry/test/components/previews/ui/chart_preview/sales.html.erb +6 -0
  103. data/registry/test/components/previews/ui/chart_preview/stock.html.erb +6 -0
  104. data/registry/test/components/previews/ui/chart_preview/takings.html.erb +8 -0
  105. data/registry/test/components/previews/ui/chart_preview.rb +46 -0
  106. data/registry/test/components/previews/ui/command_preview/_picked.html.erb +14 -0
  107. data/registry/test/components/previews/ui/command_preview/dialog.html.erb +24 -0
  108. data/registry/test/components/previews/ui/command_preview/inline.html.erb +16 -0
  109. data/registry/test/components/previews/ui/command_preview/playground.html.erb +15 -0
  110. data/registry/test/components/previews/ui/command_preview/server_search.html.erb +24 -0
  111. data/registry/test/components/previews/ui/command_preview/shortcuts.html.erb +12 -0
  112. data/registry/test/components/previews/ui/command_preview/till.html.erb +17 -0
  113. data/registry/test/components/previews/ui/command_preview.rb +25 -0
  114. data/registry/test/components/previews/ui/date_picker_preview/custom_presets.html.erb +6 -0
  115. data/registry/test/components/previews/ui/date_picker_preview/in_form.html.erb +11 -0
  116. data/registry/test/components/previews/ui/date_picker_preview/range.html.erb +5 -0
  117. data/registry/test/components/previews/ui/date_picker_preview/states.html.erb +4 -3
  118. data/registry/test/components/previews/ui/date_picker_preview.rb +26 -6
  119. data/registry/test/components/previews/ui/file_field_preview/multiple_files.html.erb +1 -1
  120. data/registry/test/components/previews/ui/file_field_preview/product_photos.html.erb +12 -0
  121. data/registry/test/components/previews/ui/file_field_preview/single_image.html.erb +4 -0
  122. data/registry/test/components/previews/ui/file_field_preview.rb +32 -5
  123. data/registry/test/components/previews/ui/gallery_preview/hover_zoom.html.erb +13 -0
  124. data/registry/test/components/previews/ui/gallery_preview/landscape.html.erb +5 -0
  125. data/registry/test/components/previews/ui/gallery_preview/product_page.html.erb +13 -0
  126. data/registry/test/components/previews/ui/gallery_preview/single.html.erb +3 -0
  127. data/registry/test/components/previews/ui/gallery_preview.rb +45 -0
  128. data/registry/test/components/previews/ui/kbd_preview/bound.html.erb +20 -0
  129. data/registry/test/components/previews/ui/kbd_preview/keys.html.erb +13 -0
  130. data/registry/test/components/previews/ui/kbd_preview/menu.html.erb +13 -0
  131. data/registry/test/components/previews/ui/kbd_preview/search_field.html.erb +8 -0
  132. data/registry/test/components/previews/ui/kbd_preview/shortcuts_list.html.erb +17 -0
  133. data/registry/test/components/previews/ui/kbd_preview/till.html.erb +23 -0
  134. data/registry/test/components/previews/ui/kbd_preview/tooltip_and_buttons.html.erb +14 -0
  135. data/registry/test/components/previews/ui/kbd_preview.rb +32 -0
  136. data/registry/test/components/previews/ui/number_input_preview/cart.html.erb +11 -0
  137. data/registry/test/components/previews/ui/number_input_preview/decimals.html.erb +4 -0
  138. data/registry/test/components/previews/ui/number_input_preview/sizes.html.erb +5 -0
  139. data/registry/test/components/previews/ui/number_input_preview/states.html.erb +7 -0
  140. data/registry/test/components/previews/ui/number_input_preview/stock_adjustment.html.erb +3 -0
  141. data/registry/test/components/previews/ui/number_input_preview.rb +36 -0
  142. data/registry/test/components/previews/ui/progress_preview/file_upload.html.erb +36 -0
  143. data/registry/test/components/previews/ui/progress_preview/free_shipping.html.erb +4 -0
  144. data/registry/test/components/previews/ui/progress_preview/indeterminate.html.erb +4 -0
  145. data/registry/test/components/previews/ui/progress_preview/sizes_and_tones.html.erb +8 -0
  146. data/registry/test/components/previews/ui/progress_preview/steps.html.erb +9 -0
  147. data/registry/test/components/previews/ui/progress_preview/storage.html.erb +8 -0
  148. data/registry/test/components/previews/ui/progress_preview/storage_by_category.html.erb +7 -0
  149. data/registry/test/components/previews/ui/progress_preview/tasks_by_status.html.erb +14 -0
  150. data/registry/test/components/previews/ui/progress_preview/traffic_by_source.html.erb +15 -0
  151. data/registry/test/components/previews/ui/progress_preview.rb +46 -0
  152. data/registry/test/components/previews/ui/select_preview/server_search.html.erb +22 -0
  153. data/registry/test/components/previews/ui/select_preview.rb +5 -0
  154. data/registry/test/components/previews/ui/timeline_preview/activity_log.html.erb +7 -0
  155. data/registry/test/components/previews/ui/timeline_preview/colored.html.erb +7 -0
  156. data/registry/test/components/previews/ui/timeline_preview/colored_by_meaning.html.erb +7 -0
  157. data/registry/test/components/previews/ui/timeline_preview/failed_delivery.html.erb +6 -0
  158. data/registry/test/components/previews/ui/timeline_preview/order_status.html.erb +9 -0
  159. data/registry/test/components/previews/ui/timeline_preview/real_dates.html.erb +5 -0
  160. data/registry/test/components/previews/ui/timeline_preview/stock_history.html.erb +6 -0
  161. data/registry/test/components/previews/ui/timeline_preview.rb +40 -0
  162. data/registry/test/components/ui/chart_test.rb +187 -0
  163. data/registry/test/components/ui/command/group_test.rb +19 -0
  164. data/registry/test/components/ui/command/item_test.rb +47 -0
  165. data/registry/test/components/ui/command_test.rb +110 -0
  166. data/registry/test/components/ui/date_picker_test.rb +129 -111
  167. data/registry/test/components/ui/file_field_test.rb +105 -9
  168. data/registry/test/components/ui/gallery_test.rb +192 -0
  169. data/registry/test/components/ui/kbd_test.rb +150 -0
  170. data/registry/test/components/ui/number_input_test.rb +155 -0
  171. data/registry/test/components/ui/progress_test.rb +188 -0
  172. data/registry/test/components/ui/select_test.rb +62 -0
  173. data/registry/test/components/ui/timeline_test.rb +175 -0
  174. metadata +147 -2
  175. data/registry/app/javascript/cally.ts +0 -8
@@ -0,0 +1,568 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // Connects to data-controller="ui--gallery"
4
+ //
5
+ // Swiping the main view is plain CSS scroll-snap; this keeps the thumbnails in
6
+ // step with it. The overlay is a native <dialog>, so the browser owns the focus
7
+ // trap, Escape and the dimmed page behind it.
8
+ //
9
+ // Zooming sizes the image inside a scrolling box instead of scaling it with a
10
+ // transform. That way panning is just scrolling, and touch, trackpad and wheel
11
+ // all work without any code here. Only dragging with a mouse needs help.
12
+ const ZOOM_STEPS = [1, 1.5, 2, 3, 4];
13
+ const MIN_ZOOM = ZOOM_STEPS[0];
14
+ const MAX_ZOOM = ZOOM_STEPS[ZOOM_STEPS.length - 1];
15
+ const CLICK_ZOOM = 2;
16
+ const DRAG_THRESHOLD = 4;
17
+ const PANE_GAP = 16;
18
+ // Room round the image at 100%, to keep it clear of the buttons.
19
+ const IMAGE_MARGIN_TOP = 64;
20
+ const IMAGE_MARGIN_SIDE = 72;
21
+ const IMAGE_MARGIN_SIDE_NARROW = 16;
22
+ const NARROW = 640;
23
+ const EASE_OUT = 'cubic-bezier(0.2, 0.8, 0.2, 1)';
24
+ const OPEN_MS = 280;
25
+ const CLOSE_MS = 220;
26
+ const SLIDE_MS = 240;
27
+ const SLIDE_DISTANCE = 48;
28
+ const ZOOM_MS = 220;
29
+ const FADE_MS = 160;
30
+
31
+ type Rect = { left: number; top: number; width: number; height: number };
32
+
33
+ type IndexEvent<E extends Event = Event> = E & { params: { index: number } };
34
+
35
+ export default class extends Controller<HTMLElement> {
36
+ static targets = ['track', 'slide', 'thumbnail', 'status', 'dialog', 'viewport', 'zoomImage', 'zoomStatus', 'zoomIn', 'zoomOut', 'lens', 'pane'];
37
+ static values = { position: String, zoomScale: Number };
38
+
39
+ declare readonly trackTarget: HTMLElement;
40
+ declare readonly slideTargets: HTMLElement[];
41
+ declare readonly thumbnailTargets: HTMLElement[];
42
+ declare readonly statusTarget: HTMLElement;
43
+ declare readonly dialogTarget: HTMLDialogElement;
44
+ declare readonly viewportTarget: HTMLElement;
45
+ declare readonly zoomImageTarget: HTMLImageElement;
46
+ declare readonly zoomStatusTarget: HTMLElement;
47
+ declare readonly zoomInTarget: HTMLButtonElement;
48
+ declare readonly zoomOutTarget: HTMLButtonElement;
49
+ declare readonly hasPaneTarget: boolean;
50
+ declare readonly lensTarget: HTMLElement;
51
+ declare readonly paneTarget: HTMLElement;
52
+ declare readonly positionValue: string;
53
+ declare readonly zoomScaleValue: number;
54
+
55
+ private index = 0;
56
+ private heading: number | null = null;
57
+ private frame?: number;
58
+ private scale = MIN_ZOOM;
59
+ private pan: { id: number; x: number; y: number; left: number; top: number } | null = null;
60
+ private dragged = false;
61
+ private closing: Animation[] | null = null;
62
+
63
+ disconnect() {
64
+ if (this.frame) cancelAnimationFrame(this.frame);
65
+ this.cancelClosing();
66
+ if (this.dialogTarget.open) this.dialogTarget.close();
67
+ }
68
+
69
+ // ── The main view ────────────────────────────────────────────────────────
70
+
71
+ select(event: IndexEvent) {
72
+ this.goTo(event.params.index);
73
+ }
74
+
75
+ previous() {
76
+ this.move(-1);
77
+ }
78
+
79
+ next() {
80
+ this.move(1);
81
+ }
82
+
83
+ private move(by: number) {
84
+ const count = this.slideTargets.length;
85
+ const index = (this.index + by + count) % count;
86
+ if (this.dialogTarget.open) this.show(index, by);
87
+ else this.goTo(index);
88
+ }
89
+
90
+ private goTo(index: number, behavior: ScrollBehavior = this.scrollBehavior) {
91
+ this.heading = index;
92
+ this.setIndex(index);
93
+ this.trackTarget.scrollTo({ left: this.scrollPosition(this.trackTarget, this.slideTargets[index]), behavior });
94
+ }
95
+
96
+ // Follows a swipe. While heading for a chosen image, the ones passed on the
97
+ // way aren't announced or highlighted.
98
+ scrolled() {
99
+ if (this.frame) return;
100
+
101
+ this.frame = requestAnimationFrame(() => {
102
+ this.frame = undefined;
103
+ const nearest = this.nearestSlide();
104
+ if (this.heading === null) this.setIndex(nearest);
105
+ else if (nearest === this.heading) this.heading = null;
106
+ });
107
+ }
108
+
109
+ // A finger or mouse on the strip takes over from wherever it was heading.
110
+ released() {
111
+ this.heading = null;
112
+ }
113
+
114
+ private nearestSlide(): number {
115
+ const track = this.trackTarget.getBoundingClientRect();
116
+ const middle = track.left + track.width / 2;
117
+ let nearest = 0;
118
+ let closest = Infinity;
119
+ this.slideTargets.forEach((slide, index) => {
120
+ const rect = slide.getBoundingClientRect();
121
+ const distance = Math.abs(rect.left + rect.width / 2 - middle);
122
+ if (distance < closest) {
123
+ closest = distance;
124
+ nearest = index;
125
+ }
126
+ });
127
+ return nearest;
128
+ }
129
+
130
+ private setIndex(index: number) {
131
+ if (index === this.index && this.statusTarget.dataset.ready) return;
132
+
133
+ this.index = index;
134
+ this.statusTarget.dataset.ready = 'true';
135
+ this.statusTarget.textContent = this.position(index);
136
+ this.slideTargets.forEach((_, i) => this.slideButton(i)?.setAttribute('tabindex', i === index ? '0' : '-1'));
137
+ this.thumbnailTargets.forEach((thumbnail, i) => {
138
+ if (i === index) thumbnail.setAttribute('aria-current', 'true');
139
+ else thumbnail.removeAttribute('aria-current');
140
+ });
141
+ const strip = this.thumbnailTargets[index]?.closest('ul');
142
+ if (strip) strip.scrollTo({ left: this.scrollPosition(strip, this.thumbnailTargets[index]), behavior: this.scrollBehavior });
143
+ }
144
+
145
+ private slideButton(index: number) {
146
+ return this.slideTargets[index].querySelector('button');
147
+ }
148
+
149
+ // Where to scroll `box` so `item` sits in its middle. Measured from what's on
150
+ // screen, so it holds in a right-to-left page, where scrollLeft runs negative.
151
+ private scrollPosition(box: HTMLElement, item: HTMLElement): number {
152
+ const boxRect = box.getBoundingClientRect();
153
+ const itemRect = item.getBoundingClientRect();
154
+ return box.scrollLeft + itemRect.left - boxRect.left - (boxRect.width - itemRect.width) / 2;
155
+ }
156
+
157
+ private position(index: number): string {
158
+ return this.positionValue.replace('%{current}', String(index + 1)).replace('%{total}', String(this.slideTargets.length));
159
+ }
160
+
161
+ private get scrollBehavior(): ScrollBehavior {
162
+ return this.reducedMotion ? 'auto' : 'smooth';
163
+ }
164
+
165
+ // ── Hover zoom ───────────────────────────────────────────────────────────
166
+
167
+ // A lens on the image, and what's under it magnified in a pane the same size
168
+ // as the image. Sized from the picture as drawn, which can be smaller than its
169
+ // frame (`fit: :contain`) or larger (`fit: :cover`).
170
+ hover(event: IndexEvent<PointerEvent>) {
171
+ if (event.pointerType !== 'mouse' || this.dialogTarget.open) return;
172
+
173
+ const slide = this.slideTargets[event.params.index];
174
+ const image = slide.querySelector('img');
175
+ if (!image?.naturalWidth) return;
176
+
177
+ const frame = slide.getBoundingClientRect();
178
+ const scale = this.zoomScaleValue;
179
+ const drawn = this.drawnImage(slide, image);
180
+ const left = drawn.left - frame.left;
181
+ const top = drawn.top - frame.top;
182
+ const { width, height } = drawn;
183
+ const lensWidth = frame.width / scale;
184
+ const lensHeight = frame.height / scale;
185
+ const lensLeft = this.clampLens(event.clientX - frame.left - lensWidth / 2, left, width, frame.width, lensWidth);
186
+ const lensTop = this.clampLens(event.clientY - frame.top - lensHeight / 2, top, height, frame.height, lensHeight);
187
+
188
+ const inside = !this.hasRoomBeside(frame);
189
+ const lens = this.lensTarget;
190
+ lens.toggleAttribute('data-shown', !inside);
191
+ lens.style.width = `${lensWidth}px`;
192
+ lens.style.height = `${lensHeight}px`;
193
+ lens.style.transform = `translate(${lensLeft}px, ${lensTop}px)`;
194
+
195
+ const pane = this.paneTarget;
196
+ const large = slide.dataset.zoomSrc ?? '';
197
+ if (pane.dataset.src !== large) {
198
+ pane.dataset.src = large;
199
+ // The picture already on screen shows through until the large one arrives.
200
+ pane.style.backgroundImage = [large, image.currentSrc].map((src) => `url("${src.replace(/"/g, '%22')}")`).join(', ');
201
+ }
202
+ pane.toggleAttribute('data-inside', inside);
203
+ pane.toggleAttribute('data-shown', true);
204
+ pane.style.width = `${frame.width}px`;
205
+ pane.style.height = `${frame.height}px`;
206
+ pane.style.backgroundSize = `${width * scale}px ${height * scale}px`;
207
+ pane.style.backgroundPosition = `${(left - lensLeft) * scale}px ${(top - lensTop) * scale}px`;
208
+ }
209
+
210
+ hoverEnd() {
211
+ if (!this.hasPaneTarget) return;
212
+
213
+ this.paneTarget.removeAttribute('data-shown');
214
+ this.lensTarget.removeAttribute('data-shown');
215
+ }
216
+
217
+ // Where the picture is really drawn in its slide, which can be smaller than the
218
+ // slide (`fit: :contain`) or larger (`fit: :cover`).
219
+ private drawnImage(slide: HTMLElement, image: HTMLImageElement): Rect {
220
+ const frame = slide.getBoundingClientRect();
221
+ const cover = getComputedStyle(image).objectFit === 'cover';
222
+ const fit = (cover ? Math.max : Math.min)(frame.width / image.naturalWidth, frame.height / image.naturalHeight);
223
+ const width = image.naturalWidth * fit;
224
+ const height = image.naturalHeight * fit;
225
+ return { left: frame.left + (frame.width - width) / 2, top: frame.top + (frame.height - height) / 2, width, height };
226
+ }
227
+
228
+ // Keeps the lens on the picture, or centres it where the picture is too short
229
+ // to hold it.
230
+ private clampLens(wanted: number, start: number, size: number, frame: number, lens: number): number {
231
+ const min = Math.max(0, start);
232
+ const max = Math.min(frame, start + size) - lens;
233
+ return max < min ? (min + max) / 2 : Math.min(max, Math.max(min, wanted));
234
+ }
235
+
236
+ private hasRoomBeside(frame: DOMRect): boolean {
237
+ const rtl = getComputedStyle(this.element).direction === 'rtl';
238
+ if (rtl) return frame.left - PANE_GAP - frame.width >= 0;
239
+ return frame.right + PANE_GAP + frame.width <= document.documentElement.clientWidth;
240
+ }
241
+
242
+ // ── The overlay ──────────────────────────────────────────────────────────
243
+
244
+ // Focus goes to the dialog, so it opens without a ring on any one button. The
245
+ // image grows out of its place on the page.
246
+ open(event: IndexEvent) {
247
+ this.hoverEnd();
248
+ this.cancelClosing();
249
+ this.dialogTarget.showModal();
250
+ this.dialogTarget.focus();
251
+ this.show(event.params.index);
252
+
253
+ const fade = { duration: OPEN_MS, easing: 'ease-out' };
254
+ this.animate(this.dialogTarget, { opacity: [0, 1] }, { ...fade, pseudoElement: '::backdrop' });
255
+ this.overlayButtons.forEach((button) => this.animate(button, { opacity: [0, 1] }, fade));
256
+
257
+ const slide = this.slideTargets[this.index];
258
+ const image = this.zoomImageTarget;
259
+ const origin = slide.querySelector('img');
260
+ if (origin?.naturalWidth && image.naturalWidth) {
261
+ this.fly(this.drawnImage(slide, origin), image.getBoundingClientRect(), OPEN_MS);
262
+ } else {
263
+ this.animate(image, { opacity: [0, 1] }, fade);
264
+ }
265
+ }
266
+
267
+ // The image goes back to its place on the page as the backdrop fades, and the
268
+ // dialog only really closes after that. Going back to the image last looked at
269
+ // comes first, so that's the place it flies to.
270
+ close() {
271
+ if (this.closing) return;
272
+
273
+ this.goTo(this.index, 'auto');
274
+ const slide = this.slideTargets[this.index];
275
+ const image = this.zoomImageTarget;
276
+ const origin = slide.querySelector('img');
277
+ const fade = { duration: CLOSE_MS, easing: 'ease-in', fill: 'forwards' as const };
278
+ const animations = [
279
+ this.animate(this.dialogTarget, { opacity: [1, 0] }, { ...fade, pseudoElement: '::backdrop' }),
280
+ ...this.overlayButtons.map((button) => this.animate(button, { opacity: [1, 0] }, fade)),
281
+ origin?.naturalWidth && image.naturalWidth
282
+ ? this.fly(image.getBoundingClientRect(), this.drawnImage(slide, origin), CLOSE_MS, true)
283
+ : this.animate(image, { opacity: [1, 0] }, fade),
284
+ ].filter((animation): animation is Animation => animation !== null);
285
+
286
+ if (animations.length === 0) {
287
+ this.dialogTarget.close();
288
+ return;
289
+ }
290
+ this.closing = animations;
291
+ Promise.all(animations.map((animation) => animation.finished))
292
+ .then(() => {
293
+ if (this.closing === animations) this.dialogTarget.close();
294
+ })
295
+ .catch(() => {});
296
+ }
297
+
298
+ // Escape runs through the same closing animation.
299
+ cancel(event: Event) {
300
+ event.preventDefault();
301
+ this.close();
302
+ }
303
+
304
+ // However the dialog closed, focus lands on the image last looked at, not the
305
+ // one the dialog was opened from.
306
+ closed() {
307
+ this.cancelClosing();
308
+ this.goTo(this.index, 'auto');
309
+ this.slideButton(this.index)?.focus({ preventScroll: true });
310
+ this.zoomImageTarget.removeAttribute('style');
311
+ this.setScale(MIN_ZOOM);
312
+ }
313
+
314
+ private cancelClosing() {
315
+ const animations = this.closing;
316
+ this.closing = null;
317
+ animations?.forEach((animation) => animation.cancel());
318
+ }
319
+
320
+ // What's on the page shows at once, since it's already loaded, and the large
321
+ // image replaces it when it arrives. It's only asked for here, so it costs
322
+ // nothing until opened. `direction` slides the old image out and the new one in.
323
+ private show(index: number, direction = 0) {
324
+ const slide = this.slideTargets[index];
325
+ const image = this.zoomImageTarget;
326
+ const large = slide.dataset.zoomSrc ?? '';
327
+ const shown = slide.querySelector('img');
328
+ const ready = shown?.complete && shown.naturalWidth > 0 ? shown.currentSrc : '';
329
+
330
+ if (direction) this.slideOut(direction);
331
+ this.setIndex(index);
332
+ this.zoomStatusTarget.textContent = this.position(index);
333
+ this.scale = MIN_ZOOM;
334
+ image.src = ready || large;
335
+ image.alt = slide.dataset.alt ?? '';
336
+ this.layout();
337
+ this.viewportTarget.scrollTo(0, 0);
338
+ this.loadLarge(index, large);
339
+ if (direction) {
340
+ this.animate(image, { opacity: [0, 1], transform: [`translateX(${direction * SLIDE_DISTANCE}px)`, 'none'] }, { duration: SLIDE_MS, easing: EASE_OUT });
341
+ }
342
+ }
343
+
344
+ private loadLarge(index: number, large: string) {
345
+ const image = this.zoomImageTarget;
346
+ if (!large || image.src === new URL(large, window.location.href).href) return;
347
+
348
+ const loader = new Image();
349
+ loader.onload = () => {
350
+ if (this.index !== index || !this.dialogTarget.open) return;
351
+
352
+ this.morph(ZOOM_MS, () => {
353
+ image.src = loader.src;
354
+ this.layout();
355
+ });
356
+ };
357
+ loader.src = large;
358
+ }
359
+
360
+ // A copy of the outgoing image, left to slide away while the real one changes.
361
+ private slideOut(direction: number) {
362
+ const image = this.zoomImageTarget;
363
+ if (!image.naturalWidth || this.reducedMotion) return;
364
+
365
+ const rect = image.getBoundingClientRect();
366
+ const ghost = image.cloneNode() as HTMLImageElement;
367
+ ghost.removeAttribute('data-ui--gallery-target');
368
+ ghost.removeAttribute('data-action');
369
+ ghost.alt = '';
370
+ ghost.setAttribute('aria-hidden', 'true');
371
+ Object.assign(ghost.style, {
372
+ position: 'fixed', left: `${rect.left}px`, top: `${rect.top}px`, width: `${rect.width}px`, height: `${rect.height}px`,
373
+ margin: '0', pointerEvents: 'none',
374
+ });
375
+ this.dialogTarget.append(ghost);
376
+ const animation = this.animate(ghost, { opacity: [1, 0], transform: ['none', `translateX(${-direction * SLIDE_DISTANCE}px)`] }, { duration: SLIDE_MS, easing: EASE_OUT });
377
+ if (animation) animation.onfinish = animation.oncancel = () => ghost.remove();
378
+ else ghost.remove();
379
+ }
380
+
381
+ // Moves the image from one place and size on screen to another, by transform,
382
+ // so nothing is laid out again on the way.
383
+ private fly(from: Rect, to: Rect, duration: number, hold = false): Animation | null {
384
+ const image = this.zoomImageTarget;
385
+ const place = image.getBoundingClientRect();
386
+ const transform = (rect: Rect) =>
387
+ `translate(${rect.left - place.left}px, ${rect.top - place.top}px) scale(${rect.width / place.width}, ${rect.height / place.height})`;
388
+ image.style.transformOrigin = '0 0';
389
+ return this.animate(image, { transform: [transform(from), transform(to)] }, { duration, easing: EASE_OUT, fill: hold ? 'forwards' : 'none' });
390
+ }
391
+
392
+ // Runs a change that moves or resizes the image, and eases it across.
393
+ private morph(duration: number, change: () => void) {
394
+ const image = this.zoomImageTarget;
395
+ const before = image.getBoundingClientRect();
396
+ change();
397
+ const after = image.getBoundingClientRect();
398
+ if (before.width > 0 && after.width > 0) this.fly(before, after, duration);
399
+ }
400
+
401
+ private animate(element: Element, keyframes: PropertyIndexedKeyframes, options: KeyframeAnimationOptions): Animation | null {
402
+ return this.reducedMotion ? null : element.animate(keyframes, options);
403
+ }
404
+
405
+ private get reducedMotion(): boolean {
406
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
407
+ }
408
+
409
+ private get overlayButtons(): HTMLElement[] {
410
+ return Array.from(this.dialogTarget.querySelectorAll('button'));
411
+ }
412
+
413
+ // Sizes the image to fit the window, times the zoom. It's never stretched past
414
+ // its own size at 100%, so a small image isn't blurred until someone asks.
415
+ layout() {
416
+ if (!this.dialogTarget.open) return;
417
+
418
+ const image = this.zoomImageTarget;
419
+ const viewport = this.viewportTarget;
420
+ if (image.naturalWidth > 0) {
421
+ const side = viewport.clientWidth < NARROW ? IMAGE_MARGIN_SIDE_NARROW : IMAGE_MARGIN_SIDE;
422
+ const room = { width: viewport.clientWidth - side * 2, height: viewport.clientHeight - IMAGE_MARGIN_TOP * 2 };
423
+ const fit = Math.min(room.width / image.naturalWidth, room.height / image.naturalHeight, 1);
424
+ image.style.width = `${image.naturalWidth * fit * this.scale}px`;
425
+ image.style.height = `${image.naturalHeight * fit * this.scale}px`;
426
+ }
427
+ this.setScale(this.scale);
428
+ }
429
+
430
+ private setScale(scale: number) {
431
+ this.scale = scale;
432
+ this.viewportTarget.toggleAttribute('data-zoomed', scale > MIN_ZOOM);
433
+ const atMin = scale <= MIN_ZOOM;
434
+ const atMax = scale >= MAX_ZOOM;
435
+ if (!atMin) this.zoomOutTarget.disabled = false;
436
+ if (!atMax) this.zoomInTarget.disabled = false;
437
+ if (atMin) this.turnOff(this.zoomOutTarget, this.zoomInTarget);
438
+ if (atMax) this.turnOff(this.zoomInTarget, this.zoomOutTarget);
439
+ }
440
+
441
+ // A button that turns off under the keyboard would drop focus out of the dialog.
442
+ private turnOff(button: HTMLButtonElement, other: HTMLButtonElement) {
443
+ if (document.activeElement === button) other.focus();
444
+ button.disabled = true;
445
+ }
446
+
447
+ zoomIn() {
448
+ const step = ZOOM_STEPS.find((zoom) => zoom > this.scale);
449
+ if (step) this.zoomTo(step);
450
+ }
451
+
452
+ zoomOut() {
453
+ const step = [...ZOOM_STEPS].reverse().find((zoom) => zoom < this.scale);
454
+ if (step) this.zoomTo(step);
455
+ }
456
+
457
+ // Keeps the spot at (x, y) where it is on screen, by default the middle. A
458
+ // trackpad pinch is already gradual, so `eased` is off for it.
459
+ private zoomTo(scale: number, x?: number, y?: number, eased = true) {
460
+ const viewport = this.viewportTarget.getBoundingClientRect();
461
+ const pointX = x ?? viewport.left + viewport.width / 2;
462
+ const pointY = y ?? viewport.top + viewport.height / 2;
463
+ const before = this.zoomImageTarget.getBoundingClientRect();
464
+ if (before.width === 0 || before.height === 0) return;
465
+
466
+ const change = () => {
467
+ const spotX = (pointX - before.left) / before.width;
468
+ const spotY = (pointY - before.top) / before.height;
469
+ this.scale = scale;
470
+ this.layout();
471
+ const after = this.zoomImageTarget.getBoundingClientRect();
472
+ this.viewportTarget.scrollBy(after.left + spotX * after.width - pointX, after.top + spotY * after.height - pointY);
473
+ };
474
+ if (eased) this.morph(ZOOM_MS, change);
475
+ else change();
476
+ }
477
+
478
+ viewportClick(event: MouseEvent) {
479
+ if (this.dragged) {
480
+ this.dragged = false;
481
+ return;
482
+ }
483
+ if (event.target === this.zoomImageTarget) {
484
+ if (this.scale > MIN_ZOOM) this.zoomTo(MIN_ZOOM);
485
+ else this.zoomTo(CLICK_ZOOM, event.clientX, event.clientY);
486
+ } else {
487
+ this.close();
488
+ }
489
+ }
490
+
491
+ // A trackpad pinch arrives as a wheel event with the control key held.
492
+ wheel(event: WheelEvent) {
493
+ if (!event.ctrlKey) return;
494
+
495
+ event.preventDefault();
496
+ const scale = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, this.scale * Math.exp(-event.deltaY * 0.01)));
497
+ this.zoomTo(scale, event.clientX, event.clientY, false);
498
+ }
499
+
500
+ panStart(event: PointerEvent) {
501
+ this.dragged = false;
502
+ if (event.pointerType !== 'mouse' || event.button !== 0) return;
503
+ if (this.scale === MIN_ZOOM || event.target !== this.zoomImageTarget) return;
504
+
505
+ const { scrollLeft: left, scrollTop: top } = this.viewportTarget;
506
+ this.pan = { id: event.pointerId, x: event.clientX, y: event.clientY, left, top };
507
+ }
508
+
509
+ // Only captures the pointer once it's really a drag, so that a plain click
510
+ // still lands on the image.
511
+ panMove(event: PointerEvent) {
512
+ if (!this.pan || event.pointerId !== this.pan.id) return;
513
+
514
+ const x = event.clientX - this.pan.x;
515
+ const y = event.clientY - this.pan.y;
516
+ if (!this.dragged && Math.hypot(x, y) < DRAG_THRESHOLD) return;
517
+
518
+ if (!this.dragged) this.viewportTarget.setPointerCapture(event.pointerId);
519
+ this.dragged = true;
520
+ this.viewportTarget.scrollTo(this.pan.left - x, this.pan.top - y);
521
+ }
522
+
523
+ panEnd() {
524
+ this.pan = null;
525
+ }
526
+
527
+ // ── Keys ─────────────────────────────────────────────────────────────────
528
+
529
+ keydown(event: KeyboardEvent) {
530
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
531
+
532
+ if (this.dialogTarget.open) this.dialogKeydown(event);
533
+ else if (this.element.contains(event.target as Node)) this.galleryKeydown(event);
534
+ }
535
+
536
+ private galleryKeydown(event: KeyboardEvent) {
537
+ const by = this.arrowDirection(event);
538
+ if (!by) return;
539
+
540
+ event.preventDefault();
541
+ this.move(by);
542
+ }
543
+
544
+ // Zoomed in, the arrow keys are left to scroll the image.
545
+ private dialogKeydown(event: KeyboardEvent) {
546
+ const by = this.arrowDirection(event);
547
+ if (by && this.scale === MIN_ZOOM) {
548
+ event.preventDefault();
549
+ this.move(by);
550
+ } else if (event.key === '+' || event.key === '=') {
551
+ event.preventDefault();
552
+ this.zoomIn();
553
+ } else if (event.key === '-') {
554
+ event.preventDefault();
555
+ this.zoomOut();
556
+ } else if (event.key === '0') {
557
+ event.preventDefault();
558
+ this.zoomTo(MIN_ZOOM);
559
+ }
560
+ }
561
+
562
+ private arrowDirection(event: KeyboardEvent): number {
563
+ const forward = getComputedStyle(this.element).direction === 'rtl' ? -1 : 1;
564
+ if (event.key === 'ArrowRight') return forward;
565
+ if (event.key === 'ArrowLeft') return -forward;
566
+ return 0;
567
+ }
568
+ }
@@ -0,0 +1,60 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+ import { ariaShortcut, isApple, isTyping, keyboardPlatform, matchesShortcut, parseShortcut, usableWhileTyping, type Shortcut } from './_internal/shortcut.js';
3
+
4
+ // Connects to data-controller="ui--kbd"
5
+ //
6
+ // The server guesses Mac or not from the user agent; this corrects the guess,
7
+ // in case the page was cached for someone else. With a keys value (bind: on
8
+ // the component) it also makes the shortcut press its button: the one the
9
+ // hint sits in, or the element the target value points at. A field the
10
+ // target points at is focused instead.
11
+ export default class extends Controller<HTMLElement> {
12
+ static values = { keys: String, target: String };
13
+
14
+ declare readonly keysValue: string;
15
+ declare readonly hasKeysValue: boolean;
16
+ declare readonly targetValue: string;
17
+
18
+ private apple = false;
19
+ private shortcut?: Shortcut;
20
+ private bound?: HTMLElement;
21
+ private addedAria = false;
22
+
23
+ connect() {
24
+ this.apple = isApple();
25
+ this.element.dataset.platform = keyboardPlatform();
26
+ if (!this.hasKeysValue || !this.keysValue) return;
27
+
28
+ this.bound = this.findTarget();
29
+ if (!this.bound) return;
30
+ this.shortcut = parseShortcut(this.keysValue);
31
+ if (!this.bound.hasAttribute('aria-keyshortcuts')) {
32
+ this.bound.setAttribute('aria-keyshortcuts', ariaShortcut(this.shortcut, this.apple));
33
+ this.addedAria = true;
34
+ }
35
+ document.addEventListener('keydown', this.onKeydown);
36
+ }
37
+
38
+ disconnect() {
39
+ document.removeEventListener('keydown', this.onKeydown);
40
+ if (this.addedAria) this.bound?.removeAttribute('aria-keyshortcuts');
41
+ this.bound = undefined;
42
+ this.addedAria = false;
43
+ }
44
+
45
+ private onKeydown = (event: KeyboardEvent) => {
46
+ if (event.defaultPrevented || event.repeat || event.isComposing || !this.bound || !this.shortcut) return;
47
+ if (!matchesShortcut(event, this.shortcut, this.apple)) return;
48
+ if (isTyping(event.target) && !usableWhileTyping(this.shortcut)) return;
49
+ if (this.bound.matches(':disabled, [aria-disabled="true"], [data-disabled]')) return;
50
+
51
+ event.preventDefault();
52
+ if (this.bound.matches('input, textarea, select, [contenteditable="true"]')) this.bound.focus();
53
+ else this.bound.click();
54
+ };
55
+
56
+ private findTarget(): HTMLElement | undefined {
57
+ if (this.targetValue) return document.querySelector<HTMLElement>(this.targetValue) ?? undefined;
58
+ return this.element.closest<HTMLElement>('button, a[href], [role="menuitem"], [role="option"], input[type="submit"]') ?? undefined;
59
+ }
60
+ }