velvetkit 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) 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/navigation_menu/item.html.erb +16 -0
  7. data/registry/app/components/ui/navigation_menu/item.rb +102 -0
  8. data/registry/app/components/ui/navigation_menu/link.html.erb +9 -0
  9. data/registry/app/components/ui/navigation_menu/link.rb +41 -0
  10. data/registry/app/components/ui/navigation_menu.html.erb +3 -0
  11. data/registry/app/components/ui/navigation_menu.rb +64 -0
  12. data/registry/app/components/ui/session_tabs/add.html.erb +1 -0
  13. data/registry/app/components/ui/session_tabs/add.rb +52 -0
  14. data/registry/app/components/ui/session_tabs/tab.html.erb +37 -0
  15. data/registry/app/components/ui/session_tabs/tab.rb +243 -0
  16. data/registry/app/components/ui/session_tabs.html.erb +15 -0
  17. data/registry/app/components/ui/session_tabs.rb +101 -0
  18. data/registry/app/components/ui/skeleton.html.erb +1 -0
  19. data/registry/app/components/ui/skeleton.rb +30 -0
  20. data/registry/app/components/ui/toast/viewport.html.erb +4 -0
  21. data/registry/app/components/ui/toast/viewport.rb +41 -0
  22. data/registry/app/components/ui/toast.html.erb +11 -0
  23. data/registry/app/components/ui/toast.rb +89 -0
  24. data/registry/app/javascript/controllers/ui/file_field_controller.ts +49 -0
  25. data/registry/app/javascript/controllers/ui/menu_controller.ts +3 -0
  26. data/registry/app/javascript/controllers/ui/navigation_menu_controller.ts +265 -0
  27. data/registry/app/javascript/controllers/ui/session_tabs_controller.ts +732 -0
  28. data/registry/app/javascript/controllers/ui/toast_controller.ts +62 -0
  29. data/registry/app/javascript/controllers/ui/toast_viewport_controller.ts +82 -0
  30. data/registry/app/javascript/velvetkit_icons.ts +21 -9
  31. data/registry/components.yml +10 -0
  32. data/registry/config/locales/velvetkit.en.yml +21 -0
  33. data/registry/test/components/previews/ui/file_field_preview/multiple_files.html.erb +3 -0
  34. data/registry/test/components/previews/ui/file_field_preview/with_error.html.erb +3 -0
  35. data/registry/test/components/previews/ui/file_field_preview.rb +18 -0
  36. data/registry/test/components/previews/ui/navigation_menu_preview/custom_panel.html.erb +20 -0
  37. data/registry/test/components/previews/ui/navigation_menu_preview/playground.html.erb +73 -0
  38. data/registry/test/components/previews/ui/navigation_menu_preview/simple.html.erb +23 -0
  39. data/registry/test/components/previews/ui/navigation_menu_preview.rb +23 -0
  40. data/registry/test/components/previews/ui/session_tabs_preview/handling_events.html.erb +46 -0
  41. data/registry/test/components/previews/ui/session_tabs_preview/saved_views.html.erb +16 -0
  42. data/registry/test/components/previews/ui/session_tabs_preview/touch_with_confirmation.html.erb +20 -0
  43. data/registry/test/components/previews/ui/session_tabs_preview.rb +35 -0
  44. data/registry/test/components/previews/ui/skeleton_preview/card_placeholder.html.erb +10 -0
  45. data/registry/test/components/previews/ui/skeleton_preview/shapes.html.erb +9 -0
  46. data/registry/test/components/previews/ui/skeleton_preview.rb +15 -0
  47. data/registry/test/components/previews/ui/toast_preview/live_viewport.html.erb +21 -0
  48. data/registry/test/components/previews/ui/toast_preview/variants.html.erb +7 -0
  49. data/registry/test/components/previews/ui/toast_preview/with_action.html.erb +7 -0
  50. data/registry/test/components/previews/ui/toast_preview.rb +29 -0
  51. data/registry/test/components/ui/file_field_test.rb +101 -0
  52. data/registry/test/components/ui/navigation_menu_test.rb +130 -0
  53. data/registry/test/components/ui/session_tabs/add_test.rb +52 -0
  54. data/registry/test/components/ui/session_tabs_test.rb +281 -0
  55. data/registry/test/components/ui/skeleton_test.rb +65 -0
  56. data/registry/test/components/ui/toast/viewport_test.rb +72 -0
  57. data/registry/test/components/ui/toast_test.rb +183 -0
  58. metadata +51 -1
@@ -0,0 +1,732 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ /**
4
+ * UI::SessionTabs controller — tabs the user opens, renames, duplicates,
5
+ * reorders and closes.
6
+ *
7
+ * Every action first dispatches a cancelable `ui--session-tabs:<action>`
8
+ * event (select, add, rename, duplicate, move, close) on the tab — or on the
9
+ * root, for `add` — with `{ value, url, ... }` in `detail`.
10
+ * `preventDefault()` stops it. Then:
11
+ * - if the tab carries a URL for that action, a Turbo-compatible form is
12
+ * submitted (rename PATCH, duplicate POST, move PATCH, close DELETE) and
13
+ * the server re-renders;
14
+ * - otherwise the event *is* the action, and the controller applies what it
15
+ * can locally: select, rename, move and close update the DOM; duplicate
16
+ * and add need markup only the app has, so they only dispatch.
17
+ *
18
+ * Reordering: tabs with `move:` can be dragged — anywhere on the tab with a
19
+ * mouse, by the grip handle on touch — or moved from the menu. Tabs without it are
20
+ * fixed points that movable tabs never pass. The drop fires the same `move`
21
+ * event with the new 1-based `position`.
22
+ */
23
+
24
+ type MenuController = Controller & { open(): void; close(): void };
25
+ type DialogController = Controller & { open(): void; close(): void };
26
+
27
+ const TAB = '[data-ui--session-tabs-target="tab"]';
28
+ const TRIGGER = '[data-ui--session-tabs-target="trigger"]';
29
+ const LABEL = '[data-ui--session-tabs-target="label"]';
30
+ const MENU_TRIGGER = '[data-ui--session-tabs-target="menuTrigger"]';
31
+ const LONG_PRESS_MS = 450;
32
+ const DRAG_THRESHOLD = 6; // px before a press becomes a drag
33
+ const EDGE = 32; // px from the list edge where dragging scrolls it
34
+
35
+ type Press = {
36
+ tab: HTMLElement;
37
+ kind: 'drag' | 'longPress'; // drag: handle, or tab body with a mouse; longPress: tab body on touch
38
+ touch: boolean;
39
+ pointerId: number;
40
+ startX: number;
41
+ startY: number;
42
+ armed: boolean; // drag: at once; longPress: after LONG_PRESS_MS
43
+ timer: number | null;
44
+ cancelled: boolean; // drag cancelled with Escape; ignore until release
45
+ };
46
+
47
+ type Drag = {
48
+ tab: HTMLElement;
49
+ grabOffset: number;
50
+ originNext: Element | null;
51
+ originIndex: number;
52
+ offset: number;
53
+ };
54
+
55
+ export default class extends Controller<HTMLElement> {
56
+ static targets = ['list', 'tab', 'dialog', 'confirmMessage'];
57
+ static values = {
58
+ minTabs: { type: Number, default: 1 },
59
+ returnFocus: String,
60
+ renameParam: { type: String, default: 'name' },
61
+ renameLabel: { type: String, default: 'Tab name' },
62
+ };
63
+
64
+ declare readonly listTarget: HTMLElement;
65
+ declare readonly tabTargets: HTMLElement[];
66
+ declare readonly dialogTarget: HTMLElement;
67
+ declare readonly confirmMessageTarget: HTMLElement;
68
+ declare minTabsValue: number;
69
+ declare returnFocusValue: string;
70
+ declare renameParamValue: string;
71
+ declare renameLabelValue: string;
72
+
73
+ private press: Press | null = null;
74
+ private drag: Drag | null = null;
75
+ private suppressClick = false;
76
+ private suppressTimer: number | null = null;
77
+ private pendingMenu: { tab: HTMLElement; timer: number } | null = null;
78
+ private pendingClose: HTMLElement | null = null;
79
+
80
+ connect() {
81
+ this.sync();
82
+ this.activeTab()?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
83
+ }
84
+
85
+ disconnect() {
86
+ if (this.drag) this.finishDrag(false);
87
+ this.endPress();
88
+ if (this.pendingMenu) window.clearTimeout(this.pendingMenu.timer);
89
+ if (this.suppressTimer != null) window.clearTimeout(this.suppressTimer);
90
+ }
91
+
92
+ // Tabs added or removed from outside (a Turbo Stream, the app's own JS)
93
+ // still need Close/Move and the tabindex re-derived.
94
+ tabTargetConnected() {
95
+ this.sync();
96
+ }
97
+
98
+ tabTargetDisconnected() {
99
+ this.sync();
100
+ }
101
+
102
+ // ── Selecting ──────────────────────────────────────────────────────────
103
+
104
+ select(event: MouseEvent) {
105
+ if (this.pendingMenu) {
106
+ // The click after a touch long-press: open the menu now, from inside
107
+ // this click, so UI::Menu's outside-click check doesn't see it.
108
+ const { tab, timer } = this.pendingMenu;
109
+ window.clearTimeout(timer);
110
+ this.pendingMenu = null;
111
+ event.preventDefault();
112
+ this.menuOf(tab)?.open();
113
+ return;
114
+ }
115
+ if (this.suppressClick) {
116
+ // The click that ends a drag; don't also select.
117
+ event.preventDefault();
118
+ return;
119
+ }
120
+ const tab = this.tabFor(event.currentTarget);
121
+ if (!tab) return;
122
+ if (!this.emit('select', tab, { url: this.triggerOf(tab)?.getAttribute('href') ?? null })) {
123
+ event.preventDefault();
124
+ return;
125
+ }
126
+ // A link navigates and the server marks the new tab active; a button
127
+ // tab is switched here.
128
+ if (!this.isLink(tab)) this.activate(tab);
129
+ this.restoreFocus();
130
+ }
131
+
132
+ // Arrow keys move focus only (manual activation): selecting a tab may load
133
+ // a whole pane, so Enter/Space — or a click — commits.
134
+ keydown(event: KeyboardEvent) {
135
+ const tab = this.tabFor(event.currentTarget);
136
+ if (!tab) return;
137
+ const triggers = this.tabTargets.map((t) => this.triggerOf(t)!).filter(Boolean);
138
+ const index = triggers.indexOf(event.currentTarget as HTMLElement);
139
+ let next = -1;
140
+
141
+ switch (event.key) {
142
+ case 'ArrowRight':
143
+ next = (index + 1) % triggers.length;
144
+ break;
145
+ case 'ArrowLeft':
146
+ next = (index - 1 + triggers.length) % triggers.length;
147
+ break;
148
+ case 'Home':
149
+ next = 0;
150
+ break;
151
+ case 'End':
152
+ next = triggers.length - 1;
153
+ break;
154
+ case 'F2':
155
+ if (tab.dataset.renameEnabled) {
156
+ event.preventDefault();
157
+ this.startRename(tab);
158
+ }
159
+ return;
160
+ case 'ContextMenu':
161
+ event.preventDefault();
162
+ this.menuOf(tab)?.open();
163
+ return;
164
+ case 'F10':
165
+ if (event.shiftKey) {
166
+ event.preventDefault();
167
+ this.menuOf(tab)?.open();
168
+ }
169
+ return;
170
+ default:
171
+ return;
172
+ }
173
+
174
+ event.preventDefault();
175
+ const target = triggers[next];
176
+ if (!target) return;
177
+ triggers.forEach((t) => t.setAttribute('tabindex', t === target ? '0' : '-1'));
178
+ target.focus();
179
+ target.scrollIntoView({ block: 'nearest', inline: 'nearest' });
180
+ }
181
+
182
+ // ── Pointer: drag handle, long-press menu ───────────────────────────
183
+ //
184
+ // Mouse/pen: press anywhere on a movable tab and move to drag; a plain
185
+ // click still selects. Touch: drag by the grip handle (it is
186
+ // `touch-action: none`, so a finger drags it at once) — the rest of the
187
+ // tab scrolls the list on swipe and opens the menu on a long-press.
188
+
189
+ contextMenu(event: MouseEvent) {
190
+ const tab = this.tabFor(event.currentTarget);
191
+ const menu = tab && this.menuOf(tab);
192
+ if (!menu) return;
193
+ event.preventDefault();
194
+ // On touch the long-press logic below opens it (Android also fires
195
+ // contextmenu for the same press).
196
+ if (this.press?.touch) return;
197
+ menu.open();
198
+ }
199
+
200
+ // Tab body: mouse/pen → drag (after DRAG_THRESHOLD, so clicks still
201
+ // select); touch → long-press menu.
202
+ pressStart(event: PointerEvent) {
203
+ if (event.button !== 0 || this.press) return;
204
+ const tab = this.tabFor(event.currentTarget);
205
+ if (!tab) return;
206
+ if (event.pointerType !== 'touch') {
207
+ if (tab.dataset.moveEnabled) this.beginPress(event, tab, 'drag');
208
+ return;
209
+ }
210
+ if (!this.menuOf(tab)) return;
211
+ this.beginPress(event, tab, 'longPress');
212
+ this.press!.timer = window.setTimeout(() => {
213
+ if (this.press) this.press.armed = true;
214
+ }, LONG_PRESS_MS);
215
+ }
216
+
217
+ // Grip handle → drag.
218
+ dragStart(event: PointerEvent) {
219
+ if (event.button !== 0 || this.press) return;
220
+ const tab = this.tabFor(event.currentTarget);
221
+ if (!tab || !tab.dataset.moveEnabled) return;
222
+ event.preventDefault(); // no text selection, no focus change
223
+ this.beginPress(event, tab, 'drag');
224
+ }
225
+
226
+ private beginPress(event: PointerEvent, tab: HTMLElement, kind: Press['kind']) {
227
+ this.press = {
228
+ tab,
229
+ kind,
230
+ touch: event.pointerType === 'touch',
231
+ pointerId: event.pointerId,
232
+ startX: event.clientX,
233
+ startY: event.clientY,
234
+ armed: kind === 'drag',
235
+ timer: null,
236
+ cancelled: false,
237
+ };
238
+ window.addEventListener('pointermove', this.onPointerMove);
239
+ window.addEventListener('pointerup', this.onPointerUp);
240
+ window.addEventListener('pointercancel', this.onPointerCancel);
241
+ window.addEventListener('keydown', this.onDragKeydown, true);
242
+ // Stops the list scrolling while a long-press is armed or a drag runs.
243
+ this.element.addEventListener('touchmove', this.onTouchMove, { passive: false });
244
+ }
245
+
246
+ private onPointerMove = (event: PointerEvent) => {
247
+ const press = this.press;
248
+ if (!press || event.pointerId !== press.pointerId || press.cancelled) return;
249
+
250
+ if (this.drag) {
251
+ this.updateDrag(event.clientX);
252
+ return;
253
+ }
254
+ const moved = Math.hypot(event.clientX - press.startX, event.clientY - press.startY);
255
+ if (moved < DRAG_THRESHOLD) return;
256
+
257
+ if (press.kind === 'drag') {
258
+ this.beginDrag(event.clientX);
259
+ this.updateDrag(event.clientX);
260
+ } else {
261
+ // The finger moved: a scroll (before the long-press fired) or a
262
+ // change of mind (after). Either way, no menu.
263
+ this.endPress();
264
+ }
265
+ };
266
+
267
+ private onPointerUp = (event: PointerEvent) => {
268
+ const press = this.press;
269
+ if (!press || event.pointerId !== press.pointerId) return;
270
+ if (this.drag) {
271
+ this.finishDrag(true);
272
+ this.suppressNextClick();
273
+ } else if (press.cancelled) {
274
+ this.suppressNextClick();
275
+ } else if (press.kind === 'longPress' && press.armed) {
276
+ // A click may or may not follow a long-press; open from that click if
277
+ // it comes (see select), otherwise shortly after.
278
+ const tab = press.tab;
279
+ const timer = window.setTimeout(() => {
280
+ this.pendingMenu = null;
281
+ this.menuOf(tab)?.open();
282
+ }, 350);
283
+ this.pendingMenu = { tab, timer };
284
+ }
285
+ this.endPress();
286
+ };
287
+
288
+ private onPointerCancel = () => {
289
+ if (this.drag) this.finishDrag(false);
290
+ this.endPress();
291
+ };
292
+
293
+ private onDragKeydown = (event: KeyboardEvent) => {
294
+ if (event.key !== 'Escape' || !this.drag) return;
295
+ event.preventDefault();
296
+ event.stopPropagation();
297
+ this.finishDrag(false);
298
+ if (this.press) this.press.cancelled = true;
299
+ };
300
+
301
+ // The click that follows pointerup arrives in the same task, if at all, so
302
+ // the flag is cleared on the next one — a click that lands elsewhere
303
+ // can't leave it set and swallow the user's next real click.
304
+ private suppressNextClick() {
305
+ this.suppressClick = true;
306
+ if (this.suppressTimer != null) window.clearTimeout(this.suppressTimer);
307
+ this.suppressTimer = window.setTimeout(() => {
308
+ this.suppressClick = false;
309
+ this.suppressTimer = null;
310
+ }, 0);
311
+ }
312
+
313
+ private onTouchMove = (event: TouchEvent) => {
314
+ if (this.press?.armed || this.drag) event.preventDefault();
315
+ };
316
+
317
+ private endPress() {
318
+ if (this.press?.timer != null) window.clearTimeout(this.press.timer);
319
+ this.press = null;
320
+ window.removeEventListener('pointermove', this.onPointerMove);
321
+ window.removeEventListener('pointerup', this.onPointerUp);
322
+ window.removeEventListener('pointercancel', this.onPointerCancel);
323
+ window.removeEventListener('keydown', this.onDragKeydown, true);
324
+ this.element.removeEventListener('touchmove', this.onTouchMove);
325
+ }
326
+
327
+ private beginDrag(clientX: number) {
328
+ const tab = this.press!.tab;
329
+ const rect = tab.getBoundingClientRect();
330
+ this.drag = {
331
+ tab,
332
+ grabOffset: clientX - rect.left,
333
+ originNext: tab.nextElementSibling,
334
+ originIndex: this.tabTargets.indexOf(tab),
335
+ offset: 0,
336
+ };
337
+ tab.dataset.dragging = '';
338
+ this.menuOf(tab)?.close();
339
+ }
340
+
341
+ private updateDrag(clientX: number) {
342
+ const drag = this.drag!;
343
+ const { tab } = drag;
344
+
345
+ // Where the dragged tab is drawn right now, in client coordinates.
346
+ const left = clientX - drag.grabOffset;
347
+ const right = left + tab.offsetWidth;
348
+
349
+ // Neighbours are compared by their *layout* slot (offsetLeft), never
350
+ // their on-screen rect: a neighbour still sliding from the last swap
351
+ // would otherwise be measured mid-animation and swap straight back.
352
+ // `toClient` converts offset coordinates to client ones.
353
+ const toClient = tab.getBoundingClientRect().left - drag.offset - tab.offsetLeft;
354
+ const centre = (t: HTMLElement) => toClient + t.offsetLeft + t.offsetWidth / 2;
355
+
356
+ // Swap as soon as the dragged tab covers half of the next movable tab —
357
+ // its leading edge, not the pointer, decides — and keep going on a fast
358
+ // drag that passes several tabs at once.
359
+ for (let guard = this.tabTargets.length; guard > 0; guard--) {
360
+ const next = this.movableNeighbour(tab, 1);
361
+ const prev = this.movableNeighbour(tab, -1);
362
+ if (next && right > centre(next)) {
363
+ this.animateSiblings(() => next.after(tab));
364
+ } else if (prev && left < centre(prev)) {
365
+ this.animateSiblings(() => prev.before(tab));
366
+ } else {
367
+ break;
368
+ }
369
+ }
370
+
371
+ // Keep the dragged tab under the pointer wherever its slot now is.
372
+ const naturalLeft = tab.getBoundingClientRect().left - drag.offset;
373
+ drag.offset = left - naturalLeft;
374
+ tab.style.transform = `translateX(${drag.offset}px)`;
375
+
376
+ this.autoScroll(clientX);
377
+ }
378
+
379
+ private finishDrag(commit: boolean) {
380
+ const drag = this.drag!;
381
+ const { tab } = drag;
382
+ this.drag = null;
383
+ delete tab.dataset.dragging;
384
+ tab.style.transform = '';
385
+
386
+ const to = this.tabTargets.indexOf(tab);
387
+ const moved = to !== drag.originIndex;
388
+ const allowed =
389
+ commit &&
390
+ moved &&
391
+ this.emit('move', tab, {
392
+ position: to + 1,
393
+ direction: to < drag.originIndex ? 'left' : 'right',
394
+ });
395
+
396
+ if (moved && !allowed) {
397
+ // Cancelled (Escape, pointercancel, or preventDefault): put it back.
398
+ this.animateSiblings(() => {
399
+ if (drag.originNext) drag.originNext.before(tab);
400
+ else this.listTarget.append(tab);
401
+ });
402
+ }
403
+ this.sync();
404
+ if (allowed && tab.dataset.moveUrl) {
405
+ this.submit(tab.dataset.moveUrl, 'patch', { position: String(to + 1) });
406
+ }
407
+ }
408
+
409
+ // FLIP: neighbours slide into their new slots instead of jumping.
410
+ private animateSiblings(mutate: () => void) {
411
+ const others = this.tabTargets.filter((t) => t !== this.drag?.tab);
412
+ // "Before" is where each tab is *drawn* (mid-slide included), so a new
413
+ // slide continues from there instead of jumping.
414
+ const before = new Map(others.map((t) => [t, t.getBoundingClientRect().left]));
415
+ mutate();
416
+ for (const t of others) {
417
+ // Measure the new slot without the old slide still applied.
418
+ t.getAnimations().forEach((a) => a.cancel());
419
+ const dx = (before.get(t) ?? 0) - t.getBoundingClientRect().left;
420
+ if (!dx) continue;
421
+ t.animate([{ transform: `translateX(${dx}px)` }, { transform: 'translateX(0)' }], {
422
+ duration: 150,
423
+ easing: 'ease-out',
424
+ });
425
+ }
426
+ }
427
+
428
+ private autoScroll(clientX: number) {
429
+ const list = this.listTarget.getBoundingClientRect();
430
+ if (clientX < list.left + EDGE) this.listTarget.scrollLeft -= 8;
431
+ else if (clientX > list.right - EDGE) this.listTarget.scrollLeft += 8;
432
+ }
433
+
434
+ // ── Menu actions ───────────────────────────────────────────────────────
435
+
436
+ rename(event: Event) {
437
+ const tab = this.fromMenu(event);
438
+ if (tab) this.startRename(tab);
439
+ }
440
+
441
+ duplicate(event: Event) {
442
+ const tab = this.fromMenu(event);
443
+ if (!tab || !this.emit('duplicate', tab)) return;
444
+ if (tab.dataset.duplicateUrl) this.submit(tab.dataset.duplicateUrl, 'post');
445
+ }
446
+
447
+ moveLeft(event: Event) {
448
+ const tab = this.fromMenu(event);
449
+ if (tab) this.move(tab, -1);
450
+ }
451
+
452
+ moveRight(event: Event) {
453
+ const tab = this.fromMenu(event);
454
+ if (tab) this.move(tab, 1);
455
+ }
456
+
457
+ close(event: Event) {
458
+ const tab = this.fromMenu(event);
459
+ if (!tab || !this.canClose()) return;
460
+ const message = tab.dataset.closeConfirm;
461
+ if (message) {
462
+ this.pendingClose = tab;
463
+ this.confirmMessageTarget.textContent = message;
464
+ this.dialog()?.open();
465
+ } else {
466
+ this.performClose(tab);
467
+ }
468
+ }
469
+
470
+ confirmClose(event: Event) {
471
+ event.preventDefault();
472
+ this.dialog()?.close();
473
+ const tab = this.pendingClose;
474
+ this.pendingClose = null;
475
+ if (tab) this.performClose(tab);
476
+ }
477
+
478
+ add(event: Event) {
479
+ // With a URL the button submits its own form; cancelling the event
480
+ // cancels the submit.
481
+ if (!this.emit('add', null)) event.preventDefault();
482
+ }
483
+
484
+ // ── Rename ─────────────────────────────────────────────────────────────
485
+
486
+ private startRename(tab: HTMLElement) {
487
+ const trigger = this.triggerOf(tab);
488
+ const label = tab.querySelector<HTMLElement>(LABEL);
489
+ if (!trigger || !label || tab.querySelector('input[data-session-tabs-rename]')) return;
490
+
491
+ const original = (label.textContent ?? '').trim();
492
+ const input = document.createElement('input');
493
+ input.type = 'text';
494
+ input.value = original;
495
+ input.dataset.sessionTabsRename = '';
496
+ input.setAttribute('aria-label', this.renameLabelValue);
497
+ input.className =
498
+ 'mx-1 h-[calc(100%-0.5rem)] min-w-0 w-[16ch] rounded-sm border border-input bg-background px-2 ' +
499
+ 'text-sm text-foreground outline-none focus:ring-2 focus:ring-primary';
500
+
501
+ let done = false;
502
+ const finish = (commit: boolean) => {
503
+ if (done) return;
504
+ done = true;
505
+ const name = input.value.trim();
506
+ input.remove();
507
+ trigger.hidden = false;
508
+ if (commit && name && name !== original) this.commitRename(tab, label, name);
509
+ trigger.focus();
510
+ if (commit) this.restoreFocus();
511
+ };
512
+
513
+ input.addEventListener('keydown', (e) => {
514
+ if (e.key === 'Enter') {
515
+ e.preventDefault();
516
+ finish(true);
517
+ } else if (e.key === 'Escape') {
518
+ e.preventDefault();
519
+ e.stopPropagation();
520
+ finish(false);
521
+ }
522
+ });
523
+ input.addEventListener('blur', () => finish(true));
524
+
525
+ trigger.hidden = true;
526
+ tab.insertBefore(input, trigger);
527
+ input.focus();
528
+ input.select();
529
+ }
530
+
531
+ private commitRename(tab: HTMLElement, label: HTMLElement, name: string) {
532
+ if (!this.emit('rename', tab, { name })) return;
533
+ label.textContent = name;
534
+ if (tab.dataset.renameUrl) {
535
+ this.submit(tab.dataset.renameUrl, 'patch', { [this.renameParamValue]: name });
536
+ }
537
+ }
538
+
539
+ // ── Move ───────────────────────────────────────────────────────────────
540
+
541
+ private move(tab: HTMLElement, step: -1 | 1) {
542
+ const neighbour = this.movableNeighbour(tab, step);
543
+ if (!neighbour) return;
544
+
545
+ const originNext = tab.nextElementSibling;
546
+ if (step < 0) neighbour.before(tab);
547
+ else neighbour.after(tab);
548
+ const position = this.tabTargets.indexOf(tab) + 1; // 1-based, like acts_as_list / positioning
549
+
550
+ if (!this.emit('move', tab, { position, direction: step < 0 ? 'left' : 'right' })) {
551
+ // Cancelled: put it back where it was.
552
+ if (originNext) originNext.before(tab);
553
+ else this.listTarget.append(tab);
554
+ return;
555
+ }
556
+ this.sync();
557
+ this.triggerOf(tab)?.focus();
558
+ tab.scrollIntoView({ block: 'nearest', inline: 'nearest' });
559
+
560
+ if (tab.dataset.moveUrl) this.submit(tab.dataset.moveUrl, 'patch', { position: String(position) });
561
+ }
562
+
563
+ // Non-movable tabs are fixed points: moves hop over them.
564
+ private movableNeighbour(tab: HTMLElement, step: -1 | 1): HTMLElement | null {
565
+ const tabs = this.tabTargets;
566
+ for (let i = tabs.indexOf(tab) + step; i >= 0 && i < tabs.length; i += step) {
567
+ if (tabs[i]!.dataset.moveEnabled) return tabs[i]!;
568
+ }
569
+ return null;
570
+ }
571
+
572
+ // ── Close ──────────────────────────────────────────────────────────────
573
+
574
+ private canClose() {
575
+ return this.tabTargets.length > this.minTabsValue;
576
+ }
577
+
578
+ private performClose(tab: HTMLElement) {
579
+ if (!this.emit('close', tab)) return;
580
+
581
+ // With a URL the server decides what follows (and where to go if this
582
+ // was the active tab).
583
+ if (tab.dataset.closeUrl) {
584
+ this.submit(tab.dataset.closeUrl, 'delete');
585
+ return;
586
+ }
587
+
588
+ const tabs = this.tabTargets;
589
+ const index = tabs.indexOf(tab);
590
+ const wasActive = tab.dataset.state === 'active';
591
+ tab.remove();
592
+ this.sync();
593
+
594
+ const remaining = this.tabTargets;
595
+ const next = remaining[Math.min(index, remaining.length - 1)];
596
+ if (wasActive && next) {
597
+ if (this.isLink(next)) {
598
+ this.triggerOf(next)?.click();
599
+ } else if (this.emit('select', next)) {
600
+ this.activate(next);
601
+ }
602
+ }
603
+ if (this.returnFocusValue) this.restoreFocus();
604
+ else this.triggerOf(this.activeTab() ?? next ?? remaining[0]!)?.focus();
605
+ }
606
+
607
+ // ── State ──────────────────────────────────────────────────────────────
608
+
609
+ private activate(tab: HTMLElement) {
610
+ for (const t of this.tabTargets) {
611
+ const active = t === tab;
612
+ t.dataset.state = active ? 'active' : 'inactive';
613
+ this.triggerOf(t)?.setAttribute('aria-selected', active ? 'true' : 'false');
614
+ }
615
+ this.sync();
616
+ tab.scrollIntoView({ block: 'nearest', inline: 'nearest' });
617
+ }
618
+
619
+ // Re-derives everything that depends on position or count: roving
620
+ // tabindex, Move left/right on the ends, Close at the minimum.
621
+ private sync() {
622
+ const tabs = this.tabTargets;
623
+ const closable = tabs.length > this.minTabsValue;
624
+ const active = this.activeTab() ?? tabs[0];
625
+
626
+ tabs.forEach((tab) => {
627
+ const focusable = tab === active ? '0' : '-1';
628
+ this.triggerOf(tab)?.setAttribute('tabindex', focusable);
629
+ tab.querySelector(MENU_TRIGGER)?.setAttribute('tabindex', focusable);
630
+
631
+ tab.querySelectorAll<HTMLElement>('[data-close-part]').forEach((el) => this.setHidden(el, !closable));
632
+ const left = !this.movableNeighbour(tab, -1);
633
+ const right = !this.movableNeighbour(tab, 1);
634
+ tab.querySelectorAll<HTMLElement>('[data-move="left"]').forEach((el) => this.setHidden(el, left));
635
+ tab.querySelectorAll<HTMLElement>('[data-move="right"]').forEach((el) => this.setHidden(el, right));
636
+ });
637
+ }
638
+
639
+ // Hidden menu items are also disabled so UI::Menu's arrow keys skip them.
640
+ private setHidden(el: HTMLElement, hidden: boolean) {
641
+ el.hidden = hidden;
642
+ if (el.getAttribute('data-ui--menu-target') !== 'item') return;
643
+ if (hidden) {
644
+ el.setAttribute('disabled', '');
645
+ el.setAttribute('data-disabled', 'true');
646
+ } else {
647
+ el.removeAttribute('disabled');
648
+ el.removeAttribute('data-disabled');
649
+ }
650
+ }
651
+
652
+ // ── Helpers ────────────────────────────────────────────────────────────
653
+
654
+ private emit(action: string, tab: HTMLElement | null, extra: Record<string, unknown> = {}) {
655
+ const key = `${action}Url`;
656
+ const detail = {
657
+ value: tab?.dataset.value ?? null,
658
+ url: tab ? (tab.dataset[key] ?? null) : null,
659
+ ...extra,
660
+ };
661
+ const event = this.dispatch(action, { target: tab ?? this.element, detail, cancelable: true });
662
+ return !event.defaultPrevented;
663
+ }
664
+
665
+ private submit(url: string, method: 'post' | 'patch' | 'delete', params: Record<string, string> = {}) {
666
+ const form = document.createElement('form');
667
+ form.method = 'post';
668
+ form.action = url;
669
+ form.hidden = true;
670
+
671
+ const fields: Record<string, string> = { ...params };
672
+ if (method !== 'post') fields._method = method;
673
+ const csrfParam = document.querySelector<HTMLMetaElement>('meta[name="csrf-param"]')?.content;
674
+ const csrfToken = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;
675
+ if (csrfParam && csrfToken) fields[csrfParam] = csrfToken;
676
+
677
+ for (const [name, value] of Object.entries(fields)) {
678
+ const input = document.createElement('input');
679
+ input.type = 'hidden';
680
+ input.name = name;
681
+ input.value = value;
682
+ form.appendChild(input);
683
+ }
684
+
685
+ form.addEventListener('turbo:submit-end', () => form.remove());
686
+ this.element.appendChild(form);
687
+ form.requestSubmit();
688
+ }
689
+
690
+ private fromMenu(event: Event): HTMLElement | null {
691
+ event.preventDefault();
692
+ const tab = this.tabFor(event.currentTarget);
693
+ if (tab) this.menuOf(tab)?.close();
694
+ return tab;
695
+ }
696
+
697
+ private tabFor(el: EventTarget | null): HTMLElement | null {
698
+ const tab = (el as Element | null)?.closest<HTMLElement>(TAB) ?? null;
699
+ return tab && this.tabTargets.includes(tab) ? tab : null;
700
+ }
701
+
702
+ private triggerOf(tab: HTMLElement) {
703
+ return tab.querySelector<HTMLElement>(TRIGGER);
704
+ }
705
+
706
+ private isLink(tab: HTMLElement) {
707
+ return this.triggerOf(tab)?.tagName === 'A';
708
+ }
709
+
710
+ private activeTab() {
711
+ return this.tabTargets.find((t) => t.dataset.state === 'active');
712
+ }
713
+
714
+ private menuOf(tab: HTMLElement): MenuController | null {
715
+ const el = tab.querySelector<HTMLElement>('[data-controller~="ui--menu"]');
716
+ if (!el) return null;
717
+ return this.application.getControllerForElementAndIdentifier(el, 'ui--menu') as MenuController | null;
718
+ }
719
+
720
+ private dialog(): DialogController | null {
721
+ return this.application.getControllerForElementAndIdentifier(
722
+ this.dialogTarget,
723
+ 'ui--dialog',
724
+ ) as DialogController | null;
725
+ }
726
+
727
+ private restoreFocus() {
728
+ const selector = this.returnFocusValue;
729
+ if (!selector) return;
730
+ requestAnimationFrame(() => document.querySelector<HTMLElement>(selector)?.focus());
731
+ }
732
+ }