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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +80 -0
- data/README.md +5 -1
- data/lib/generators/velvetkit/add/add_generator.rb +58 -0
- data/lib/velvetkit/version.rb +4 -1
- data/lib/velvetkit.rb +7 -0
- data/registry/app/assets/tailwind/velvetkit.css +90 -155
- data/registry/app/components/ui/chart.html.erb +47 -0
- data/registry/app/components/ui/chart.rb +177 -0
- data/registry/app/components/ui/command/group.rb +27 -0
- data/registry/app/components/ui/command/item.rb +64 -0
- data/registry/app/components/ui/command.html.erb +41 -0
- data/registry/app/components/ui/command.rb +122 -0
- data/registry/app/components/ui/date_picker.html.erb +58 -64
- data/registry/app/components/ui/date_picker.rb +199 -75
- data/registry/app/components/ui/file_field.html.erb +14 -4
- data/registry/app/components/ui/file_field.rb +179 -28
- data/registry/app/components/ui/gallery/image.rb +20 -0
- data/registry/app/components/ui/gallery.html.erb +52 -0
- data/registry/app/components/ui/gallery.rb +164 -0
- data/registry/app/components/ui/kbd.html.erb +27 -0
- data/registry/app/components/ui/kbd.rb +134 -0
- data/registry/app/components/ui/number_input.html.erb +11 -0
- data/registry/app/components/ui/number_input.rb +103 -0
- data/registry/app/components/ui/progress/segment.rb +25 -0
- data/registry/app/components/ui/progress.html.erb +25 -0
- data/registry/app/components/ui/progress.rb +182 -0
- data/registry/app/components/ui/select.html.erb +24 -5
- data/registry/app/components/ui/select.rb +44 -5
- data/registry/app/components/ui/timeline/item.html.erb +21 -0
- data/registry/app/components/ui/timeline/item.rb +145 -0
- data/registry/app/components/ui/timeline.html.erb +1 -0
- data/registry/app/components/ui/timeline.rb +42 -0
- data/registry/app/javascript/chart_js.ts +37 -0
- data/registry/app/javascript/controllers/ui/_internal/date_format.ts +74 -0
- data/registry/app/javascript/controllers/ui/_internal/shortcut.ts +80 -0
- data/registry/app/javascript/controllers/ui/chart_controller.ts +585 -0
- data/registry/app/javascript/controllers/ui/command_controller.ts +454 -0
- data/registry/app/javascript/controllers/ui/date_picker_controller.ts +247 -82
- data/registry/app/javascript/controllers/ui/file_field_controller.ts +288 -16
- data/registry/app/javascript/controllers/ui/gallery_controller.ts +568 -0
- data/registry/app/javascript/controllers/ui/kbd_controller.ts +60 -0
- data/registry/app/javascript/controllers/ui/number_input_controller.ts +111 -0
- data/registry/app/javascript/controllers/ui/progress_controller.ts +87 -0
- data/registry/app/javascript/controllers/ui/select_controller.ts +198 -8
- data/registry/app/javascript/vanilla_calendar.ts +15 -0
- data/registry/components.yml +19 -3
- data/registry/config/locales/velvetkit.en.yml +73 -0
- data/registry/icons/lucide/download.svg +17 -0
- data/registry/icons/lucide/file-plus.svg +18 -0
- data/registry/icons/lucide/file.svg +16 -0
- data/registry/icons/lucide/folder.svg +15 -0
- data/registry/icons/lucide/keyboard.svg +23 -0
- data/registry/icons/lucide/minus.svg +15 -0
- data/registry/icons/lucide/package.svg +18 -0
- data/registry/icons/lucide/pause.svg +16 -0
- data/registry/icons/lucide/percent.svg +17 -0
- data/registry/icons/lucide/printer.svg +17 -0
- data/registry/icons/lucide/receipt.svg +17 -0
- data/registry/icons/lucide/sun-moon.svg +19 -0
- data/registry/icons/lucide/truck.svg +19 -0
- data/registry/icons/lucide/user-plus.svg +18 -0
- data/registry/icons/lucide/zoom-in.svg +18 -0
- data/registry/icons/lucide/zoom-out.svg +17 -0
- data/registry/icons/phosphor/circle-half.svg +2 -0
- data/registry/icons/phosphor/download-simple.svg +2 -0
- data/registry/icons/phosphor/file-plus.svg +2 -0
- data/registry/icons/phosphor/file.svg +2 -0
- data/registry/icons/phosphor/folder.svg +2 -0
- data/registry/icons/phosphor/keyboard.svg +2 -0
- data/registry/icons/phosphor/magnifying-glass-minus.svg +2 -0
- data/registry/icons/phosphor/magnifying-glass-plus.svg +2 -0
- data/registry/icons/phosphor/minus.svg +2 -0
- data/registry/icons/phosphor/package.svg +2 -0
- data/registry/icons/phosphor/pause.svg +2 -0
- data/registry/icons/phosphor/percent.svg +2 -0
- data/registry/icons/phosphor/printer.svg +2 -0
- data/registry/icons/phosphor/receipt.svg +2 -0
- data/registry/icons/phosphor/truck.svg +2 -0
- data/registry/icons/phosphor/user-plus.svg +2 -0
- data/registry/icons/tabler/download.svg +18 -0
- data/registry/icons/tabler/file-plus.svg +19 -0
- data/registry/icons/tabler/file.svg +17 -0
- data/registry/icons/tabler/folder.svg +16 -0
- data/registry/icons/tabler/keyboard.svg +23 -0
- data/registry/icons/tabler/minus.svg +16 -0
- data/registry/icons/tabler/package.svg +20 -0
- data/registry/icons/tabler/percentage.svg +18 -0
- data/registry/icons/tabler/player-pause.svg +17 -0
- data/registry/icons/tabler/printer.svg +18 -0
- data/registry/icons/tabler/receipt.svg +16 -0
- data/registry/icons/tabler/sun-moon.svg +21 -0
- data/registry/icons/tabler/truck.svg +18 -0
- data/registry/icons/tabler/user-plus.svg +19 -0
- data/registry/icons/tabler/zoom-in.svg +19 -0
- data/registry/icons/tabler/zoom-out.svg +18 -0
- data/registry/icons.yml +16 -0
- data/registry/test/components/previews/ui/chart_preview/cash_flow.html.erb +6 -0
- data/registry/test/components/previews/ui/chart_preview/donut.html.erb +6 -0
- data/registry/test/components/previews/ui/chart_preview/margin.html.erb +6 -0
- data/registry/test/components/previews/ui/chart_preview/pie.html.erb +6 -0
- data/registry/test/components/previews/ui/chart_preview/sales.html.erb +6 -0
- data/registry/test/components/previews/ui/chart_preview/stock.html.erb +6 -0
- data/registry/test/components/previews/ui/chart_preview/takings.html.erb +8 -0
- data/registry/test/components/previews/ui/chart_preview.rb +46 -0
- data/registry/test/components/previews/ui/command_preview/_picked.html.erb +14 -0
- data/registry/test/components/previews/ui/command_preview/dialog.html.erb +24 -0
- data/registry/test/components/previews/ui/command_preview/inline.html.erb +16 -0
- data/registry/test/components/previews/ui/command_preview/playground.html.erb +15 -0
- data/registry/test/components/previews/ui/command_preview/server_search.html.erb +24 -0
- data/registry/test/components/previews/ui/command_preview/shortcuts.html.erb +12 -0
- data/registry/test/components/previews/ui/command_preview/till.html.erb +17 -0
- data/registry/test/components/previews/ui/command_preview.rb +25 -0
- data/registry/test/components/previews/ui/date_picker_preview/custom_presets.html.erb +6 -0
- data/registry/test/components/previews/ui/date_picker_preview/in_form.html.erb +11 -0
- data/registry/test/components/previews/ui/date_picker_preview/range.html.erb +5 -0
- data/registry/test/components/previews/ui/date_picker_preview/states.html.erb +4 -3
- data/registry/test/components/previews/ui/date_picker_preview.rb +26 -6
- data/registry/test/components/previews/ui/file_field_preview/multiple_files.html.erb +1 -1
- data/registry/test/components/previews/ui/file_field_preview/product_photos.html.erb +12 -0
- data/registry/test/components/previews/ui/file_field_preview/single_image.html.erb +4 -0
- data/registry/test/components/previews/ui/file_field_preview.rb +32 -5
- data/registry/test/components/previews/ui/gallery_preview/hover_zoom.html.erb +13 -0
- data/registry/test/components/previews/ui/gallery_preview/landscape.html.erb +5 -0
- data/registry/test/components/previews/ui/gallery_preview/product_page.html.erb +13 -0
- data/registry/test/components/previews/ui/gallery_preview/single.html.erb +3 -0
- data/registry/test/components/previews/ui/gallery_preview.rb +45 -0
- data/registry/test/components/previews/ui/kbd_preview/bound.html.erb +20 -0
- data/registry/test/components/previews/ui/kbd_preview/keys.html.erb +13 -0
- data/registry/test/components/previews/ui/kbd_preview/menu.html.erb +13 -0
- data/registry/test/components/previews/ui/kbd_preview/search_field.html.erb +8 -0
- data/registry/test/components/previews/ui/kbd_preview/shortcuts_list.html.erb +17 -0
- data/registry/test/components/previews/ui/kbd_preview/till.html.erb +23 -0
- data/registry/test/components/previews/ui/kbd_preview/tooltip_and_buttons.html.erb +14 -0
- data/registry/test/components/previews/ui/kbd_preview.rb +32 -0
- data/registry/test/components/previews/ui/number_input_preview/cart.html.erb +11 -0
- data/registry/test/components/previews/ui/number_input_preview/decimals.html.erb +4 -0
- data/registry/test/components/previews/ui/number_input_preview/sizes.html.erb +5 -0
- data/registry/test/components/previews/ui/number_input_preview/states.html.erb +7 -0
- data/registry/test/components/previews/ui/number_input_preview/stock_adjustment.html.erb +3 -0
- data/registry/test/components/previews/ui/number_input_preview.rb +36 -0
- data/registry/test/components/previews/ui/progress_preview/file_upload.html.erb +36 -0
- data/registry/test/components/previews/ui/progress_preview/free_shipping.html.erb +4 -0
- data/registry/test/components/previews/ui/progress_preview/indeterminate.html.erb +4 -0
- data/registry/test/components/previews/ui/progress_preview/sizes_and_tones.html.erb +8 -0
- data/registry/test/components/previews/ui/progress_preview/steps.html.erb +9 -0
- data/registry/test/components/previews/ui/progress_preview/storage.html.erb +8 -0
- data/registry/test/components/previews/ui/progress_preview/storage_by_category.html.erb +7 -0
- data/registry/test/components/previews/ui/progress_preview/tasks_by_status.html.erb +14 -0
- data/registry/test/components/previews/ui/progress_preview/traffic_by_source.html.erb +15 -0
- data/registry/test/components/previews/ui/progress_preview.rb +46 -0
- data/registry/test/components/previews/ui/select_preview/server_search.html.erb +22 -0
- data/registry/test/components/previews/ui/select_preview.rb +5 -0
- data/registry/test/components/previews/ui/timeline_preview/activity_log.html.erb +7 -0
- data/registry/test/components/previews/ui/timeline_preview/colored.html.erb +7 -0
- data/registry/test/components/previews/ui/timeline_preview/colored_by_meaning.html.erb +7 -0
- data/registry/test/components/previews/ui/timeline_preview/failed_delivery.html.erb +6 -0
- data/registry/test/components/previews/ui/timeline_preview/order_status.html.erb +9 -0
- data/registry/test/components/previews/ui/timeline_preview/real_dates.html.erb +5 -0
- data/registry/test/components/previews/ui/timeline_preview/stock_history.html.erb +6 -0
- data/registry/test/components/previews/ui/timeline_preview.rb +40 -0
- data/registry/test/components/ui/chart_test.rb +187 -0
- data/registry/test/components/ui/command/group_test.rb +19 -0
- data/registry/test/components/ui/command/item_test.rb +47 -0
- data/registry/test/components/ui/command_test.rb +110 -0
- data/registry/test/components/ui/date_picker_test.rb +129 -111
- data/registry/test/components/ui/file_field_test.rb +105 -9
- data/registry/test/components/ui/gallery_test.rb +192 -0
- data/registry/test/components/ui/kbd_test.rb +150 -0
- data/registry/test/components/ui/number_input_test.rb +155 -0
- data/registry/test/components/ui/progress_test.rb +188 -0
- data/registry/test/components/ui/select_test.rb +62 -0
- data/registry/test/components/ui/timeline_test.rb +175 -0
- metadata +147 -2
- data/registry/app/javascript/cally.ts +0 -8
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
import { Controller } from '@hotwired/stimulus';
|
|
2
|
+
import { isApple, isTyping, matchesShortcut, parseShortcut, usableWhileTyping, type Shortcut } from './_internal/shortcut.js';
|
|
3
|
+
|
|
4
|
+
// Connects to data-controller="ui--command"
|
|
5
|
+
//
|
|
6
|
+
// A combobox over a listbox, as WAI-ARIA describes it: focus stays in the
|
|
7
|
+
// search box and the highlighted item is announced with aria-activedescendant.
|
|
8
|
+
//
|
|
9
|
+
// Typing hides the items that don't match and puts the best first, within
|
|
10
|
+
// their group. With a url, it also asks the server, the way UI::Select does:
|
|
11
|
+
// spaced out, a spinner when slow, nothing cancelled, answers remembered.
|
|
12
|
+
//
|
|
13
|
+
// With dialog, the panel lives in a native <dialog>: the shortcut toggles it
|
|
14
|
+
// from anywhere, and the platform gives the focus trap, Escape and the inert
|
|
15
|
+
// page behind it.
|
|
16
|
+
const SEARCH_DELAY = 200;
|
|
17
|
+
const SLOW_SEARCH = 200;
|
|
18
|
+
const REMEMBER_FOR = 60_000;
|
|
19
|
+
|
|
20
|
+
type Result = { label: string; value: string; href?: string; description?: string; group?: string };
|
|
21
|
+
|
|
22
|
+
const remembered = new Map<string, { at: number; results: Result[] }>();
|
|
23
|
+
const pending = new Map<string, Promise<Result[]>>();
|
|
24
|
+
|
|
25
|
+
type Turbo = { visit: (url: string) => void };
|
|
26
|
+
|
|
27
|
+
export default class extends Controller<HTMLElement> {
|
|
28
|
+
static targets = ['dialog', 'panel', 'input', 'list', 'group', 'item', 'results', 'empty', 'status', 'template', 'searchIcon', 'spinner'];
|
|
29
|
+
static values = {
|
|
30
|
+
dialog: Boolean, shortcut: String, sortGroups: Boolean, url: String, param: { type: String, default: 'q' },
|
|
31
|
+
resultsHeading: String, empty: String, searching: String, failed: String,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
declare readonly hasDialogTarget: boolean;
|
|
35
|
+
declare readonly dialogTarget: HTMLDialogElement;
|
|
36
|
+
declare readonly inputTarget: HTMLInputElement;
|
|
37
|
+
declare readonly listTarget: HTMLElement;
|
|
38
|
+
declare readonly groupTargets: HTMLElement[];
|
|
39
|
+
declare readonly itemTargets: HTMLElement[];
|
|
40
|
+
declare readonly resultsTarget: HTMLElement;
|
|
41
|
+
declare readonly emptyTarget: HTMLElement;
|
|
42
|
+
declare readonly statusTarget: HTMLElement;
|
|
43
|
+
declare readonly templateTarget: HTMLTemplateElement;
|
|
44
|
+
declare readonly searchIconTarget: HTMLElement;
|
|
45
|
+
declare readonly spinnerTarget: HTMLElement;
|
|
46
|
+
declare readonly dialogValue: boolean;
|
|
47
|
+
declare readonly shortcutValue: string;
|
|
48
|
+
declare readonly sortGroupsValue: boolean;
|
|
49
|
+
declare readonly urlValue: string;
|
|
50
|
+
declare readonly paramValue: string;
|
|
51
|
+
declare readonly resultsHeadingValue: string;
|
|
52
|
+
declare readonly emptyValue: string;
|
|
53
|
+
declare readonly searchingValue: string;
|
|
54
|
+
declare readonly failedValue: string;
|
|
55
|
+
|
|
56
|
+
private shortcuts: Shortcut[] = [];
|
|
57
|
+
private apple = false;
|
|
58
|
+
private highlighted: HTMLElement | null = null;
|
|
59
|
+
private searchTimer?: number;
|
|
60
|
+
private slowTimer?: number;
|
|
61
|
+
private latestKey = '';
|
|
62
|
+
private resultCount = 0;
|
|
63
|
+
|
|
64
|
+
connect() {
|
|
65
|
+
this.apple = isApple();
|
|
66
|
+
this.itemTargets.forEach((item, index) => { item.dataset.order = String(index); });
|
|
67
|
+
this.groupTargets.forEach((group, index) => { group.dataset.order = String(index); });
|
|
68
|
+
if (this.dialogValue && this.hasDialogTarget) {
|
|
69
|
+
this.shortcuts = this.shortcutValue.split(/\s+/).filter(Boolean).map(parseShortcut);
|
|
70
|
+
if (this.shortcuts.length) document.addEventListener('keydown', this.onShortcut);
|
|
71
|
+
this.dialogTarget.addEventListener('click', this.onBackdrop);
|
|
72
|
+
this.dialogTarget.addEventListener('close', this.onClose);
|
|
73
|
+
}
|
|
74
|
+
this.filter('');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
disconnect() {
|
|
78
|
+
document.removeEventListener('keydown', this.onShortcut);
|
|
79
|
+
if (this.hasDialogTarget) {
|
|
80
|
+
this.dialogTarget.removeEventListener('click', this.onBackdrop);
|
|
81
|
+
this.dialogTarget.removeEventListener('close', this.onClose);
|
|
82
|
+
if (this.dialogTarget.open) this.dialogTarget.close();
|
|
83
|
+
}
|
|
84
|
+
this.stopSearch();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ── Opening and closing (dialog) ─────────────────────────────────────────
|
|
88
|
+
|
|
89
|
+
open(event?: Event) {
|
|
90
|
+
event?.preventDefault();
|
|
91
|
+
if (!this.hasDialogTarget || this.dialogTarget.open) return;
|
|
92
|
+
|
|
93
|
+
this.inputTarget.value = '';
|
|
94
|
+
this.filter('');
|
|
95
|
+
this.dialogTarget.showModal();
|
|
96
|
+
this.inputTarget.focus();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
close() {
|
|
100
|
+
if (this.hasDialogTarget && this.dialogTarget.open) this.dialogTarget.close();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private onShortcut = (event: KeyboardEvent) => {
|
|
104
|
+
if (event.defaultPrevented || event.repeat || event.isComposing) return;
|
|
105
|
+
const shortcut = this.shortcuts.find((s) => matchesShortcut(event, s, this.apple));
|
|
106
|
+
if (!shortcut) return;
|
|
107
|
+
// A bare-key shortcut, like "/", is typing when in a field, this search
|
|
108
|
+
// box included: there it's a "/" in the query, not a way to close.
|
|
109
|
+
if (isTyping(event.target) && !usableWhileTyping(shortcut)) return;
|
|
110
|
+
|
|
111
|
+
event.preventDefault();
|
|
112
|
+
if (this.dialogTarget.open) this.close();
|
|
113
|
+
else this.open();
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
private onBackdrop = (event: MouseEvent) => {
|
|
117
|
+
if (event.target === this.dialogTarget) this.close();
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
private onClose = () => {
|
|
121
|
+
this.stopSearch();
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
// ── Typing ───────────────────────────────────────────────────────────────
|
|
125
|
+
|
|
126
|
+
search() {
|
|
127
|
+
const query = this.inputTarget.value.trim();
|
|
128
|
+
this.filter(query);
|
|
129
|
+
this.announce();
|
|
130
|
+
if (!this.remote) return;
|
|
131
|
+
|
|
132
|
+
window.clearTimeout(this.searchTimer);
|
|
133
|
+
if (!query) {
|
|
134
|
+
this.stopSearch();
|
|
135
|
+
this.clearResults();
|
|
136
|
+
this.updateEmpty();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
this.searchTimer = window.setTimeout(() => this.fetchResults(query), SEARCH_DELAY);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Hides what doesn't match, best matches first in each group; an empty
|
|
143
|
+
// query puts everything back as written. With sortGroups, the groups follow
|
|
144
|
+
// their best match too.
|
|
145
|
+
private filter(query: string) {
|
|
146
|
+
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
|
|
147
|
+
const best = new Map<HTMLElement, number>();
|
|
148
|
+
|
|
149
|
+
this.groupTargets.forEach((group) => {
|
|
150
|
+
const items = this.itemTargets.filter((item) => item.closest('[data-ui--command-target="group"]') === group);
|
|
151
|
+
const scored = items.map((item) => ({ item, score: words.length ? this.score(item, words) : 1 }));
|
|
152
|
+
scored.forEach(({ item, score }) => { item.hidden = score <= 0; });
|
|
153
|
+
scored
|
|
154
|
+
.sort((a, b) => (words.length ? b.score - a.score : 0) || Number(a.item.dataset.order) - Number(b.item.dataset.order))
|
|
155
|
+
.forEach(({ item }) => group.append(item));
|
|
156
|
+
group.hidden = scored.every(({ score }) => score <= 0);
|
|
157
|
+
best.set(group, Math.max(0, ...scored.map(({ score }) => score)));
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
if (this.sortGroupsValue) {
|
|
161
|
+
const results = this.resultsTarget;
|
|
162
|
+
[...this.groupTargets]
|
|
163
|
+
.sort((a, b) => (words.length ? best.get(b)! - best.get(a)! : 0) || Number(a.dataset.order) - Number(b.dataset.order))
|
|
164
|
+
.forEach((group) => results.before(group));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
this.updateEmpty();
|
|
168
|
+
this.highlight(this.visible()[0] ?? null);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Every word has to be found. A label starting with it beats a word in the
|
|
172
|
+
// label starting with it, which beats it anywhere, which beats keywords,
|
|
173
|
+
// which beats an abbreviation ("nwinv" for New invoice).
|
|
174
|
+
private score(item: HTMLElement, words: string[]) {
|
|
175
|
+
const label = (item.dataset.label ?? item.textContent ?? '').toLowerCase();
|
|
176
|
+
const keywords = (item.dataset.keywords ?? '').toLowerCase();
|
|
177
|
+
let total = 0;
|
|
178
|
+
for (const word of words) {
|
|
179
|
+
let best = 0;
|
|
180
|
+
if (label.startsWith(word)) best = 1000 - label.length;
|
|
181
|
+
else if (new RegExp(`(^|[\\s\\-_/.])${word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`).test(label)) best = 800 - label.length;
|
|
182
|
+
else if (label.includes(word)) best = 600 - label.indexOf(word);
|
|
183
|
+
else if (keywords.includes(word)) best = 400;
|
|
184
|
+
else if (this.inOrder(label, word)) best = 100;
|
|
185
|
+
if (best <= 0) return 0;
|
|
186
|
+
total += best;
|
|
187
|
+
}
|
|
188
|
+
return total;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// An abbreviation: the letters in order, starting a word, each next one
|
|
192
|
+
// later in the same word or starting another. "nwproj" is New project;
|
|
193
|
+
// "dal" isn't hold this sale, since its d is in the middle of a word.
|
|
194
|
+
private inOrder(text: string, word: string, from = 0, after = -1): boolean {
|
|
195
|
+
if (word === '') return true;
|
|
196
|
+
for (let at = text.indexOf(word[0], from); at !== -1; at = text.indexOf(word[0], at + 1)) {
|
|
197
|
+
const startsWord = at === 0 || /[\s\-_/.,]/.test(text[at - 1]);
|
|
198
|
+
const sameWord = after >= 0 && !/[\s\-_/.,]/.test(text.slice(after + 1, at));
|
|
199
|
+
if ((startsWord || sameWord) && this.inOrder(text, word.slice(1), at + 1, at)) return true;
|
|
200
|
+
}
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ── Moving and picking ───────────────────────────────────────────────────
|
|
205
|
+
|
|
206
|
+
navigate(event: KeyboardEvent) {
|
|
207
|
+
const items = this.visible();
|
|
208
|
+
const at = this.highlighted ? items.indexOf(this.highlighted) : -1;
|
|
209
|
+
|
|
210
|
+
switch (event.key) {
|
|
211
|
+
case 'ArrowDown':
|
|
212
|
+
event.preventDefault();
|
|
213
|
+
this.highlight(items[(at + 1) % items.length] ?? null, true);
|
|
214
|
+
break;
|
|
215
|
+
case 'ArrowUp':
|
|
216
|
+
event.preventDefault();
|
|
217
|
+
this.highlight(items[(at - 1 + items.length) % items.length] ?? null, true);
|
|
218
|
+
break;
|
|
219
|
+
case 'PageDown':
|
|
220
|
+
event.preventDefault();
|
|
221
|
+
this.highlight(items[Math.min(at + 8, items.length - 1)] ?? null, true);
|
|
222
|
+
break;
|
|
223
|
+
case 'PageUp':
|
|
224
|
+
event.preventDefault();
|
|
225
|
+
this.highlight(items[Math.max(at - 8, 0)] ?? null, true);
|
|
226
|
+
break;
|
|
227
|
+
case 'Enter':
|
|
228
|
+
if (event.isComposing) return;
|
|
229
|
+
event.preventDefault();
|
|
230
|
+
if (this.highlighted) this.choose(this.highlighted, event.metaKey || event.ctrlKey);
|
|
231
|
+
break;
|
|
232
|
+
case 'Escape':
|
|
233
|
+
// In a dialog, Escape closes it (the platform does that). On a page,
|
|
234
|
+
// it clears the search first.
|
|
235
|
+
if (!this.dialogValue && this.inputTarget.value) {
|
|
236
|
+
event.preventDefault();
|
|
237
|
+
this.inputTarget.value = '';
|
|
238
|
+
this.search();
|
|
239
|
+
}
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
hover(event: PointerEvent) {
|
|
245
|
+
const item = (event.target as HTMLElement).closest<HTMLElement>('[role="option"]');
|
|
246
|
+
if (item && item !== this.highlighted && !item.hidden && item.getAttribute('aria-disabled') !== 'true') this.highlight(item);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
pick(event: MouseEvent) {
|
|
250
|
+
const item = (event.target as HTMLElement).closest<HTMLElement>('[role="option"]');
|
|
251
|
+
if (!item) return;
|
|
252
|
+
event.preventDefault();
|
|
253
|
+
this.choose(item, event.metaKey || event.ctrlKey);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
private choose(item: HTMLElement, newTab = false) {
|
|
257
|
+
if (item.getAttribute('aria-disabled') === 'true') return;
|
|
258
|
+
|
|
259
|
+
const detail = { value: item.dataset.value ?? '', label: item.dataset.label ?? '', href: item.dataset.href ?? null };
|
|
260
|
+
const picked = this.dispatch('select', { detail, cancelable: true, target: item });
|
|
261
|
+
if (picked.defaultPrevented) return;
|
|
262
|
+
|
|
263
|
+
this.close();
|
|
264
|
+
if (!detail.href) return;
|
|
265
|
+
if (newTab) {
|
|
266
|
+
window.open(detail.href, '_blank', 'noopener');
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
const turbo = (window as unknown as { Turbo?: Turbo }).Turbo;
|
|
270
|
+
if (turbo) turbo.visit(detail.href);
|
|
271
|
+
else window.location.assign(detail.href);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private highlight(item: HTMLElement | null, scroll = false) {
|
|
275
|
+
this.highlighted?.removeAttribute('data-highlighted');
|
|
276
|
+
this.highlighted?.setAttribute('aria-selected', 'false');
|
|
277
|
+
this.highlighted = item;
|
|
278
|
+
if (!item) {
|
|
279
|
+
this.inputTarget.removeAttribute('aria-activedescendant');
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
item.setAttribute('data-highlighted', '');
|
|
283
|
+
item.setAttribute('aria-selected', 'true');
|
|
284
|
+
this.inputTarget.setAttribute('aria-activedescendant', item.id);
|
|
285
|
+
if (scroll) item.scrollIntoView({ block: 'nearest' });
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
private visible() {
|
|
289
|
+
return [...this.listTarget.querySelectorAll<HTMLElement>('[role="option"]')]
|
|
290
|
+
.filter((item) => !item.hidden && !item.closest('[hidden]') && item.getAttribute('aria-disabled') !== 'true');
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// For analytics and the like: what was searched and how much it found,
|
|
294
|
+
// server results included once they're in.
|
|
295
|
+
private announce() {
|
|
296
|
+
const query = this.inputTarget.value.trim();
|
|
297
|
+
const matches = [...this.listTarget.querySelectorAll<HTMLElement>('[role="option"]')]
|
|
298
|
+
.filter((item) => !item.hidden && !item.closest('[hidden]')).length;
|
|
299
|
+
this.dispatch('search', { detail: { query, matches } });
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
private updateEmpty() {
|
|
303
|
+
const query = this.inputTarget.value.trim();
|
|
304
|
+
const searching = this.listTarget.getAttribute('aria-busy') === 'true';
|
|
305
|
+
// Disabled items count as found: they're shown, just not pickable.
|
|
306
|
+
const shown = [...this.listTarget.querySelectorAll<HTMLElement>('[role="option"]')].filter((item) => !item.hidden && !item.closest('[hidden]'));
|
|
307
|
+
const none = shown.length === 0 && !this.statusTarget.textContent;
|
|
308
|
+
this.emptyTarget.textContent = this.emptyValue;
|
|
309
|
+
this.emptyTarget.hidden = !(query && none && !searching);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// ── Searching the server ─────────────────────────────────────────────────
|
|
313
|
+
|
|
314
|
+
private get remote() {
|
|
315
|
+
return this.urlValue !== '';
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
private async fetchResults(query: string) {
|
|
319
|
+
const url = new URL(this.urlValue, window.location.href);
|
|
320
|
+
url.searchParams.set(this.paramValue, query);
|
|
321
|
+
const key = url.toString();
|
|
322
|
+
this.latestKey = key;
|
|
323
|
+
window.clearTimeout(this.slowTimer);
|
|
324
|
+
|
|
325
|
+
const known = remembered.get(key);
|
|
326
|
+
if (known && Date.now() - known.at < REMEMBER_FOR) {
|
|
327
|
+
this.showResults(known.results);
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
this.listTarget.setAttribute('aria-busy', 'true');
|
|
332
|
+
this.slowTimer = window.setTimeout(() => this.showStatus(this.searchingValue, true), SLOW_SEARCH);
|
|
333
|
+
try {
|
|
334
|
+
const results = await this.ask(url, key);
|
|
335
|
+
if (this.latestKey !== key) return;
|
|
336
|
+
this.listTarget.removeAttribute('aria-busy');
|
|
337
|
+
this.showResults(results);
|
|
338
|
+
this.announce();
|
|
339
|
+
} catch {
|
|
340
|
+
if (this.latestKey !== key) return;
|
|
341
|
+
this.listTarget.removeAttribute('aria-busy');
|
|
342
|
+
this.clearResults();
|
|
343
|
+
this.showStatus(this.failedValue);
|
|
344
|
+
this.highlight(this.visible()[0] ?? null);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
private ask(url: URL, key: string): Promise<Result[]> {
|
|
349
|
+
let request = pending.get(key);
|
|
350
|
+
if (!request) {
|
|
351
|
+
request = fetch(url, { headers: { Accept: 'application/json' } })
|
|
352
|
+
.then((response) => {
|
|
353
|
+
if (!response.ok) throw new Error(`${response.status}`);
|
|
354
|
+
return response.json();
|
|
355
|
+
})
|
|
356
|
+
.then((data) => {
|
|
357
|
+
const results = this.normalise(data);
|
|
358
|
+
remembered.set(key, { at: Date.now(), results });
|
|
359
|
+
return results;
|
|
360
|
+
})
|
|
361
|
+
.finally(() => pending.delete(key));
|
|
362
|
+
pending.set(key, request);
|
|
363
|
+
}
|
|
364
|
+
return request;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private normalise(data: unknown): Result[] {
|
|
368
|
+
if (!Array.isArray(data)) return [];
|
|
369
|
+
return data.flatMap((item) => {
|
|
370
|
+
if (!item || typeof item !== 'object') return [];
|
|
371
|
+
const { label, value, href, url, description, group } = item as Record<string, unknown>;
|
|
372
|
+
const link = href ?? url;
|
|
373
|
+
const text = String(label ?? value ?? '');
|
|
374
|
+
if (!text) return [];
|
|
375
|
+
return [{
|
|
376
|
+
label: text, value: String(value ?? link ?? text), href: link ? String(link) : undefined,
|
|
377
|
+
description: description ? String(description) : undefined, group: group ? String(group) : undefined,
|
|
378
|
+
}];
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Server results go after what's on the page, grouped as the server says.
|
|
383
|
+
private showResults(results: Result[]) {
|
|
384
|
+
this.clearResults();
|
|
385
|
+
this.showStatus(null);
|
|
386
|
+
const groups = new Map<string, Result[]>();
|
|
387
|
+
results.forEach((result) => {
|
|
388
|
+
const heading = result.group || this.resultsHeadingValue;
|
|
389
|
+
groups.set(heading, [...(groups.get(heading) ?? []), result]);
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
groups.forEach((list, heading) => {
|
|
393
|
+
const group = document.createElement('div');
|
|
394
|
+
group.setAttribute('role', 'group');
|
|
395
|
+
group.className = 'py-1 [&:not(:first-child)]:border-t';
|
|
396
|
+
const title = document.createElement('div');
|
|
397
|
+
title.id = `${this.listTarget.id}-results-${this.resultCount++}`;
|
|
398
|
+
title.className = 'px-2 pt-1.5 pb-1 text-xs font-medium text-muted-foreground';
|
|
399
|
+
title.textContent = heading;
|
|
400
|
+
group.setAttribute('aria-labelledby', title.id);
|
|
401
|
+
group.append(title);
|
|
402
|
+
list.forEach((result) => group.append(this.buildItem(result)));
|
|
403
|
+
this.resultsTarget.append(group);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
this.updateEmpty();
|
|
407
|
+
// Keep the highlight on what's on the page if something there matched.
|
|
408
|
+
if (!this.highlighted || this.highlighted.hidden) this.highlight(this.visible()[0] ?? null);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
private buildItem(result: Result) {
|
|
412
|
+
const item = this.templateTarget.content.firstElementChild!.cloneNode(true) as HTMLElement;
|
|
413
|
+
item.id = `${this.listTarget.id}-result-${this.resultCount++}`;
|
|
414
|
+
item.removeAttribute('data-ui--command-target');
|
|
415
|
+
item.dataset.value = result.value;
|
|
416
|
+
item.dataset.label = result.label;
|
|
417
|
+
if (result.href) item.dataset.href = result.href;
|
|
418
|
+
const body = item.querySelector<HTMLElement>('span.flex-col')!;
|
|
419
|
+
body.firstElementChild!.textContent = result.label;
|
|
420
|
+
if (result.description) {
|
|
421
|
+
const description = document.createElement('span');
|
|
422
|
+
description.className = 'truncate text-xs text-muted-foreground';
|
|
423
|
+
description.textContent = result.description;
|
|
424
|
+
body.append(description);
|
|
425
|
+
}
|
|
426
|
+
return item;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
private clearResults() {
|
|
430
|
+
if (this.highlighted && this.resultsTarget.contains(this.highlighted)) this.highlight(null);
|
|
431
|
+
this.resultsTarget.replaceChildren();
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private showStatus(text: string | null, busy = false) {
|
|
435
|
+
window.clearTimeout(this.slowTimer);
|
|
436
|
+
this.statusTarget.textContent = text ?? '';
|
|
437
|
+
this.statusTarget.hidden = !text;
|
|
438
|
+
// While searching, the spinner says it; the words are for screen readers.
|
|
439
|
+
this.statusTarget.classList.toggle('sr-only', busy);
|
|
440
|
+
this.spinnerTarget.classList.toggle('hidden', !busy);
|
|
441
|
+
this.spinnerTarget.classList.toggle('flex', busy);
|
|
442
|
+
this.searchIconTarget.classList.toggle('hidden', busy);
|
|
443
|
+
this.searchIconTarget.classList.toggle('flex', !busy);
|
|
444
|
+
this.updateEmpty();
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
private stopSearch() {
|
|
448
|
+
window.clearTimeout(this.searchTimer);
|
|
449
|
+
window.clearTimeout(this.slowTimer);
|
|
450
|
+
this.latestKey = '';
|
|
451
|
+
this.listTarget.removeAttribute('aria-busy');
|
|
452
|
+
this.showStatus(null);
|
|
453
|
+
}
|
|
454
|
+
}
|