asta-ui 0.8.0 → 0.9.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.
@@ -0,0 +1,1459 @@
1
+ /* Forms group: the behaviour behind the form controls. Event delegation on document, so markup swapped in by
2
+ * htmx works without re-init. Every control keeps a real form field (native input or hidden input) up to date.
3
+ * CopyButton [data-asta-copy]
4
+ * SegmentedControl [data-asta-segmented] ToggleGroup [data-asta-toggle]
5
+ * NumberInput [data-asta-number] OtpInput [data-asta-otp]
6
+ * PasswordInput [data-asta-password] TagInput [data-asta-tags]
7
+ * RangeSlider [data-asta-range] Rating [data-asta-rating]
8
+ * ColorPicker [data-asta-color] Combobox [data-asta-combo]
9
+ * DatePicker [data-asta-date] FileUpload [data-asta-upload]
10
+ * InlineEdit [data-asta-inline]
11
+ */
12
+ (() => {
13
+ if (window.__astaForms) return;
14
+ window.__astaForms = true;
15
+ const EASE = "cubic-bezier(.16,1,.3,1)";
16
+ const reduce = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
17
+ const el = (e) => (e.target instanceof Element ? e.target : null);
18
+ const near = (e, sel) => el(e)?.closest(sel) || null;
19
+ const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
20
+ const emit = (node, type, detail) =>
21
+ node.dispatchEvent(detail === undefined ? new Event(type, { bubbles: true }) : new CustomEvent(type, { bubbles: true, detail }));
22
+ // Restart a CSS animation on a class without remounting the element.
23
+ const replay = (node, cls) => {
24
+ node.classList.remove(cls);
25
+ void node.offsetWidth;
26
+ node.classList.add(cls);
27
+ };
28
+ const on = (type, fn, capture) => document.addEventListener(type, fn, capture);
29
+
30
+ /* ---------- Slider ---------- */
31
+
32
+ // Chrome and Safari can't fill a range track up to the thumb, so the wrapper carries --asta-fill.
33
+ const sliderFill = (i) => {
34
+ const lo = +i.min || 0, hi = i.max === "" ? 100 : +i.max;
35
+ const f = hi > lo ? ((+i.value - lo) / (hi - lo)) * 100 : 0;
36
+ i.parentElement?.style.setProperty("--asta-fill", `${Math.min(100, Math.max(0, f))}%`);
37
+ };
38
+ on("input", (e) => e.target instanceof HTMLInputElement && e.target.matches("[data-asta-slider]") && sliderFill(e.target));
39
+ on("reset", (e) => {
40
+ if (!(e.target instanceof HTMLFormElement)) return;
41
+ const f = e.target;
42
+ requestAnimationFrame(() => f.querySelectorAll("input[data-asta-slider]").forEach(sliderFill));
43
+ });
44
+
45
+ /* ---------- CopyButton ---------- */
46
+
47
+ async function writeText(text) {
48
+ try {
49
+ await navigator.clipboard.writeText(text);
50
+ return true;
51
+ } catch {
52
+ // Older browsers and non-secure pages: fall back to a hidden textarea.
53
+ const ta = document.createElement("textarea");
54
+ ta.value = text;
55
+ ta.setAttribute("readonly", "");
56
+ ta.style.cssText = "position:fixed;opacity:0;pointer-events:none";
57
+ document.body.append(ta);
58
+ ta.select();
59
+ let ok = false;
60
+ try {
61
+ ok = document.execCommand("copy");
62
+ } catch {}
63
+ ta.remove();
64
+ return ok;
65
+ }
66
+ }
67
+
68
+ on("click", async (e) => {
69
+ const b = near(e, "[data-asta-copy]");
70
+ if (!b || b.disabled) return;
71
+ let text = b.getAttribute("data-asta-copy") || "";
72
+ const from = b.getAttribute("data-asta-copy-from");
73
+ const src = from ? document.querySelector(from) : null;
74
+ if (src) text = src instanceof HTMLInputElement || src instanceof HTMLTextAreaElement ? src.value : src.textContent.trim();
75
+ const ok = await writeText(text);
76
+ b.dataset.state = ok ? "copied" : "failed";
77
+ const status = b.nextElementSibling?.matches("[data-asta-copy-status]") ? b.nextElementSibling : null;
78
+ if (status) status.textContent = ok ? b.dataset.copied || "Copied" : "Couldn't copy";
79
+ if (ok) emit(b, "asta:copy", { text });
80
+ clearTimeout(b._astaTimer);
81
+ b._astaTimer = setTimeout(() => {
82
+ b.dataset.state = "idle";
83
+ if (status) status.textContent = "";
84
+ }, Number(b.dataset.timeout) || 1600);
85
+ });
86
+
87
+ /* ---------- Radio-like groups: SegmentedControl, ToggleGroup (single), Rating ---------- */
88
+
89
+ // What was checked just before a pointer or key press, so a change can slide from it (or a click can clear it).
90
+ const before = new WeakMap();
91
+ const GROUPS = "[data-asta-segmented],[data-asta-toggle='single'],[data-asta-rating]";
92
+ const remember = (e) => {
93
+ const root = near(e, GROUPS);
94
+ if (root) before.set(root, { input: root.querySelector("input:checked"), pointer: e.type === "pointerdown" });
95
+ };
96
+ on("pointerdown", remember, true);
97
+ on("keydown", remember, true);
98
+
99
+ // FLIP the new background from the old one's box, so it slides with transform only.
100
+ function slidePill(root, from, to) {
101
+ const ind = to.parentElement.querySelector("[data-asta-ind]");
102
+ if (!ind || reduce() || from === to) return;
103
+ const next = to.parentElement;
104
+ const prev = from?.parentElement;
105
+ const squash = root.hasAttribute("data-asta-segmented");
106
+ ind.style.transition = "none";
107
+ ind.style.transformOrigin = "left";
108
+ if (prev && prev.offsetWidth) {
109
+ const dx = prev.offsetLeft - next.offsetLeft;
110
+ ind.style.transform = `translateX(${dx}px) scaleX(${prev.offsetWidth / next.offsetWidth})${squash ? " scaleY(.86)" : ""}`;
111
+ } else {
112
+ ind.style.opacity = "0";
113
+ ind.style.transform = "scale(.94)";
114
+ }
115
+ void ind.offsetWidth;
116
+ ind.style.transition = `transform ${squash ? 0.5 : 0.44}s ${EASE}, opacity .25s ${EASE}`;
117
+ ind.style.transform = "";
118
+ ind.style.opacity = "";
119
+ }
120
+
121
+ on("change", (e) => {
122
+ const input = e.target;
123
+ if (!(input instanceof HTMLInputElement)) return;
124
+ const pill = input.closest("[data-asta-segmented],[data-asta-toggle='single']");
125
+ if (pill && input.checked) {
126
+ slidePill(pill, before.get(pill)?.input, input);
127
+ before.delete(pill);
128
+ }
129
+ const rating = input.closest("[data-asta-rating]");
130
+ if (rating && input.checked) rate(rating, Number(input.value), true);
131
+ });
132
+
133
+ // A click on the pressed option of a ToggleGroup with AllowEmpty, or on the current star, clears it.
134
+ on("click", (e) => {
135
+ const input = e.target;
136
+ if (!(input instanceof HTMLInputElement) || input.type !== "radio") return;
137
+ const root = input.closest("[data-asta-toggle][data-allow-empty],[data-asta-rating][data-clear]");
138
+ if (!root) return;
139
+ const was = before.get(root);
140
+ before.delete(root);
141
+ if (!was || was.input !== input) return;
142
+ if (root.hasAttribute("data-asta-rating")) {
143
+ if (!was.pointer || Number(input.value) <= 0) return;
144
+ const zero = root.querySelector('input[value="0"]');
145
+ if (zero) {
146
+ zero.checked = true;
147
+ emit(zero, "change");
148
+ }
149
+ } else {
150
+ input.checked = false;
151
+ emit(input, "change");
152
+ }
153
+ });
154
+
155
+ /* ---------- Rating ---------- */
156
+
157
+ function paintStars(root, v, preview) {
158
+ root.querySelectorAll("[data-asta-star]").forEach((s, i) => {
159
+ s.dataset.fill = v >= i + 1 ? "full" : v >= i + 0.5 ? "half" : "none";
160
+ s.toggleAttribute("data-preview", preview);
161
+ });
162
+ }
163
+ function rate(root, v, pop) {
164
+ root.dataset.value = String(v);
165
+ paintStars(root, v, false);
166
+ if (!pop || reduce()) return;
167
+ root.querySelectorAll("[data-asta-star-pop]").forEach((p, i) => {
168
+ if (i < Math.ceil(v)) replay(p, "asta-rating-pop");
169
+ else p.classList.remove("asta-rating-pop");
170
+ });
171
+ }
172
+ on("pointermove", (e) => {
173
+ const label = near(e, "[data-asta-rating] label");
174
+ if (!label) return;
175
+ const root = label.closest("[data-asta-rating]");
176
+ const v = Number(label.querySelector("input")?.value);
177
+ const cur = Number(root.dataset.value) || 0;
178
+ paintStars(root, v, v !== cur);
179
+ });
180
+ on(
181
+ "pointerleave",
182
+ (e) => {
183
+ if (e.target instanceof Element && e.target.matches("[data-asta-rating]")) paintStars(e.target, Number(e.target.dataset.value) || 0, false);
184
+ },
185
+ true,
186
+ );
187
+
188
+ /* ---------- NumberInput ---------- */
189
+
190
+ const DIGIT =
191
+ '<span class="relative inline-block h-[1.25em] w-[0.62em] overflow-hidden" data-asta-digit><span class="absolute inset-x-0 top-0 flex flex-col transition-transform duration-500 ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none">' +
192
+ Array.from({ length: 10 }, (_, i) => `<span class="flex h-[1.25em] items-center justify-center">${i}</span>`).join("") +
193
+ "</span></span>";
194
+
195
+ function numberSet(root, v) {
196
+ const min = Number(root.dataset.min);
197
+ const max = Number(root.dataset.max);
198
+ const input = root.querySelector("[data-asta-number-input]");
199
+ const view = root.querySelector("[data-asta-number-view]");
200
+ const cur = Number(input.value);
201
+ const next = Math.min(max, Math.max(min, v));
202
+ if (next === cur) {
203
+ // Already at a limit: nudge to say so.
204
+ if (v !== cur) {
205
+ view.dataset.bump = v < min ? "min" : "max";
206
+ clearTimeout(view._astaBump);
207
+ view._astaBump = setTimeout(() => delete view.dataset.bump, 260);
208
+ }
209
+ return false;
210
+ }
211
+ input.value = String(next);
212
+ view.setAttribute("aria-valuenow", String(next));
213
+ // Reuse strips from the right, so 9 → 10 rolls the last digit and adds one on the left.
214
+ const wrap = root.querySelector("[data-asta-number-digits]");
215
+ const digits = String(Math.abs(next)).split("").map(Number);
216
+ let strips = [...wrap.querySelectorAll("[data-asta-digit]")];
217
+ while (strips.length < digits.length) {
218
+ const t = document.createElement("template");
219
+ t.innerHTML = DIGIT;
220
+ const s = t.content.firstElementChild;
221
+ s.firstElementChild.style.transform = `translateY(${-digits[digits.length - strips.length - 1] * 1.25}em)`;
222
+ wrap.insertBefore(s, strips[0] || null);
223
+ strips = [s, ...strips];
224
+ }
225
+ while (strips.length > digits.length) strips.shift().remove();
226
+ let minus = wrap.querySelector("[data-minus]");
227
+ if (next < 0 && !minus) {
228
+ minus = document.createElement("span");
229
+ minus.dataset.minus = "";
230
+ minus.textContent = "−";
231
+ wrap.prepend(minus);
232
+ } else if (next >= 0) minus?.remove();
233
+ strips.forEach((s, i) => (s.firstElementChild.style.transform = `translateY(${-digits[i] * 1.25}em)`));
234
+ root.querySelector('[data-asta-number-step="-1"]').disabled = next <= min;
235
+ root.querySelector('[data-asta-number-step="1"]').disabled = next >= max;
236
+ emit(input, "input");
237
+ emit(input, "change");
238
+ return true;
239
+ }
240
+ const numberValue = (root) => Number(root.querySelector("[data-asta-number-input]").value);
241
+
242
+ let holdTimer = null;
243
+ const holdStop = () => {
244
+ clearTimeout(holdTimer);
245
+ holdTimer = null;
246
+ };
247
+ on("pointerdown", (e) => {
248
+ const b = near(e, "[data-asta-number-step]");
249
+ if (!b || e.button !== 0 || b.disabled) return;
250
+ const root = b.closest("[data-asta-number]");
251
+ const dir = Number(b.dataset.astaNumberStep) * Number(root.dataset.step || 1);
252
+ try {
253
+ b.setPointerCapture(e.pointerId);
254
+ } catch {}
255
+ holdStop();
256
+ numberSet(root, numberValue(root) + dir);
257
+ // Repeat while held, faster the longer it's held.
258
+ let delay = 380;
259
+ const tick = () => {
260
+ if (!numberSet(root, numberValue(root) + dir)) return holdStop();
261
+ delay = Math.max(40, delay * 0.82);
262
+ holdTimer = setTimeout(tick, delay);
263
+ };
264
+ holdTimer = setTimeout(tick, delay);
265
+ });
266
+ // Screen readers click without a pointer press.
267
+ on("click", (e) => {
268
+ const b = near(e, "[data-asta-number-step]");
269
+ if (!b || e.detail !== 0 || b.disabled) return;
270
+ const root = b.closest("[data-asta-number]");
271
+ numberSet(root, numberValue(root) + Number(b.dataset.astaNumberStep) * Number(root.dataset.step || 1));
272
+ });
273
+ ["pointerup", "pointercancel", "lostpointercapture"].forEach((t) => on(t, (e) => near(e, "[data-asta-number-step]") && holdStop()));
274
+ on("contextmenu", (e) => near(e, "[data-asta-number-step]") && e.preventDefault());
275
+ on("keydown", (e) => {
276
+ const view = near(e, "[data-asta-number-view]");
277
+ if (!view) return;
278
+ const root = view.closest("[data-asta-number]");
279
+ const step = Number(root.dataset.step || 1);
280
+ const cur = numberValue(root);
281
+ const k = e.key;
282
+ if (k === "ArrowUp" || k === "ArrowRight") numberSet(root, cur + step);
283
+ else if (k === "ArrowDown" || k === "ArrowLeft") numberSet(root, cur - step);
284
+ else if (k === "PageUp") numberSet(root, cur + step * 10);
285
+ else if (k === "PageDown") numberSet(root, cur - step * 10);
286
+ else if (k === "Home") numberSet(root, Number(root.dataset.min));
287
+ else if (k === "End") numberSet(root, Number(root.dataset.max));
288
+ else if (/^[0-9]$/.test(k)) {
289
+ const typed = e.timeStamp - (view._astaAt || 0) > 900 ? k : (view._astaTyped || "") + k;
290
+ view._astaTyped = typed;
291
+ view._astaAt = e.timeStamp;
292
+ numberSet(root, Number(typed));
293
+ } else return;
294
+ e.preventDefault();
295
+ });
296
+
297
+ /* ---------- OtpInput ---------- */
298
+
299
+ function otpPaint(root) {
300
+ const input = root.querySelector("input");
301
+ const boxes = [...root.querySelectorAll("[data-asta-otp-box]")];
302
+ const code = input.value;
303
+ const n = boxes.length;
304
+ const err = input.getAttribute("aria-invalid") === "true";
305
+ const active = document.activeElement === input && !input.disabled ? Math.min(code.length, n - 1) : -1;
306
+ boxes.forEach((b, i) => {
307
+ const ch = code[i] || "";
308
+ b.dataset.state = err ? "error" : i === active ? "active" : code.length === n ? "full" : ch ? "filled" : "";
309
+ const had = b.dataset.ch ?? b.textContent.trim();
310
+ if (had !== ch || (!ch && b.querySelector(".asta-otp-caret"))) {
311
+ b.innerHTML = ch ? `<span class="asta-otp-ch">${esc(ch)}</span>` : "";
312
+ }
313
+ b.dataset.ch = ch;
314
+ if (!ch && i === active && !err && !b.firstChild) b.innerHTML = '<span class="asta-otp-caret"></span>';
315
+ });
316
+ }
317
+ function otpSet(input, raw) {
318
+ const root = input.closest("[data-asta-otp]");
319
+ const n = root.querySelectorAll("[data-asta-otp-box]").length;
320
+ const prev = input._astaPrev ?? input.defaultValue;
321
+ const next = (input.hasAttribute("data-letters") ? raw.replace(/[^a-z0-9]/gi, "").toUpperCase() : raw.replace(/\D/g, "")).slice(0, n);
322
+ input.value = next;
323
+ input._astaPrev = next;
324
+ if (next !== prev) {
325
+ // Typing again clears an error the server rendered.
326
+ input.removeAttribute("aria-invalid");
327
+ root.querySelector("[data-asta-otp-boxes]").classList.remove("asta-otp-shake");
328
+ }
329
+ otpPaint(root);
330
+ if (next.length === n && prev.length < n) {
331
+ const boxes = root.querySelector("[data-asta-otp-boxes]");
332
+ boxes.removeAttribute("data-wave");
333
+ void boxes.offsetWidth;
334
+ boxes.setAttribute("data-wave", "");
335
+ emit(input, "asta:complete", { code: next });
336
+ }
337
+ }
338
+ const otpEnd = (input) => {
339
+ const n = input.value.length;
340
+ if (input.selectionStart !== n || input.selectionEnd !== n) input.setSelectionRange(n, n);
341
+ };
342
+ const otpInput = (e) => (e.target instanceof HTMLInputElement && e.target.parentElement?.matches("[data-asta-otp]") ? e.target : null);
343
+ on("input", (e) => {
344
+ const i = otpInput(e);
345
+ if (i) otpSet(i, i.value);
346
+ });
347
+ on("paste", (e) => {
348
+ const i = otpInput(e);
349
+ if (!i) return;
350
+ // Paste replaces the whole code, wherever the caret was.
351
+ e.preventDefault();
352
+ otpSet(i, e.clipboardData?.getData("text") || "");
353
+ });
354
+ ["focusin", "focusout"].forEach((t) =>
355
+ on(t, (e) => {
356
+ const i = otpInput(e);
357
+ if (!i) return;
358
+ if (t === "focusin") otpEnd(i);
359
+ otpPaint(i.parentElement);
360
+ }),
361
+ );
362
+ ["select", "click", "keyup"].forEach((t) =>
363
+ on(
364
+ t,
365
+ (e) => {
366
+ const i = otpInput(e);
367
+ if (i) otpEnd(i);
368
+ },
369
+ true,
370
+ ),
371
+ );
372
+
373
+ /* ---------- PasswordInput ---------- */
374
+
375
+ const WORDS = ["Weak", "Weak", "Fair", "Good", "Strong"];
376
+ function passwordCheck(root) {
377
+ const input = root.querySelector("[data-asta-password-input]");
378
+ const v = input.value;
379
+ const rules = [...root.querySelectorAll("[data-asta-password-rule]")];
380
+ let score = 0;
381
+ rules.forEach((r) => {
382
+ let ok = false;
383
+ try {
384
+ ok = new RegExp(r.getAttribute("data-asta-password-rule")).test(v);
385
+ } catch {}
386
+ if (ok) score++;
387
+ r.toggleAttribute("data-on", ok);
388
+ const said = r.querySelector("[data-asta-password-said]");
389
+ if (said) said.textContent = ok ? ", done" : ", not yet";
390
+ });
391
+ root.querySelectorAll("[data-asta-password-seg]").forEach((s, i) => s.toggleAttribute("data-on", i < score));
392
+ root.toggleAttribute("data-strong", rules.length > 0 && score === rules.length);
393
+ const word = root.querySelector("[data-asta-password-word]");
394
+ if (word) {
395
+ const w = !v || !rules.length ? "" : WORDS[Math.round((score / rules.length) * 4)];
396
+ word.innerHTML = w ? `<span class="sr-only">Strength: </span>${w}` : "";
397
+ }
398
+ }
399
+ on("input", (e) => {
400
+ const root = near(e, "[data-asta-password]");
401
+ if (root && e.target.matches("[data-asta-password-input]")) passwordCheck(root);
402
+ });
403
+ on("pointerdown", (e) => near(e, "[data-asta-password-toggle]") && e.preventDefault());
404
+ on("click", (e) => {
405
+ const b = near(e, "[data-asta-password-toggle]");
406
+ if (!b) return;
407
+ const input = b.closest("[data-asta-password]").querySelector("[data-asta-password-input]");
408
+ const show = input.type === "password";
409
+ input.type = show ? "text" : "password";
410
+ b.setAttribute("aria-pressed", String(show));
411
+ b.setAttribute("aria-label", show ? "Hide password" : "Show password");
412
+ });
413
+
414
+ /* ---------- TagInput ---------- */
415
+
416
+ const tagsOf = (root) => [...root.querySelectorAll("[data-asta-tag]")];
417
+ function tagsSync(root) {
418
+ const input = root.querySelector("[data-asta-tags-input]");
419
+ const max = Number(root.dataset.max) || 8;
420
+ const n = tagsOf(root).length;
421
+ const full = n >= max;
422
+ const count = root.querySelector("[data-asta-tags-count]");
423
+ count.textContent = `${n}/${max}`;
424
+ count.classList.toggle("text-[#e5484d]", full);
425
+ count.classList.toggle("text-mute", !full);
426
+ input.disabled = full && !input.value;
427
+ input.placeholder = full ? "Limit reached" : n ? "" : root.dataset.placeholder || "";
428
+ }
429
+ function tagsAdd(root, raws) {
430
+ const input = root.querySelector("[data-asta-tags-input]");
431
+ const list = root.querySelector("[data-asta-tags-list]");
432
+ const tpl = root.querySelector("template[data-asta-tags-tpl]");
433
+ const max = Number(root.dataset.max) || 8;
434
+ let added = false;
435
+ for (const r of raws) {
436
+ const t = r.trim().replace(/\s+/g, " ");
437
+ if (!t) continue;
438
+ const tags = tagsOf(root);
439
+ const dup = tags.find((li) => li.dataset.astaTag.toLowerCase() === t.toLowerCase());
440
+ if (dup) {
441
+ if (!reduce()) replay(dup, "asta-tag-shake");
442
+ continue;
443
+ }
444
+ if (tags.length >= max) break;
445
+ const li = tpl.content.firstElementChild.cloneNode(true);
446
+ li.dataset.astaTag = t;
447
+ li.querySelector("[data-asta-tag-text]").textContent = t;
448
+ li.querySelector("[data-asta-tag-remove]").setAttribute("aria-label", `Remove ${t}`);
449
+ const hidden = li.querySelector("input[type=hidden]");
450
+ if (hidden) hidden.value = t;
451
+ list.append(li);
452
+ added = true;
453
+ }
454
+ input.value = "";
455
+ tagsSync(root);
456
+ if (added) emit(root, "change");
457
+ }
458
+ function tagsRemove(root, li) {
459
+ li.remove();
460
+ tagsSync(root);
461
+ root.querySelector("[data-asta-tags-input]").focus();
462
+ emit(root, "change");
463
+ }
464
+ const tagsDisarm = (root) => tagsOf(root).forEach((li) => li.removeAttribute("data-armed"));
465
+ const tagsInput = (e) => (e.target instanceof HTMLInputElement && e.target.matches("[data-asta-tags-input]") ? e.target : null);
466
+ on("keydown", (e) => {
467
+ const input = tagsInput(e);
468
+ if (!input) return;
469
+ const root = input.closest("[data-asta-tags]");
470
+ const tags = tagsOf(root);
471
+ const last = tags[tags.length - 1];
472
+ if (e.key === "Enter") {
473
+ e.preventDefault();
474
+ tagsAdd(root, [input.value]);
475
+ } else if (e.key === "Backspace" && !input.value && last) {
476
+ // The first Backspace marks the last tag, the second removes it.
477
+ if (last.hasAttribute("data-armed")) tagsRemove(root, last);
478
+ else last.setAttribute("data-armed", "");
479
+ } else if (e.key === "Escape") tagsDisarm(root);
480
+ });
481
+ on("input", (e) => {
482
+ const input = tagsInput(e);
483
+ if (!input) return;
484
+ const root = input.closest("[data-asta-tags]");
485
+ tagsDisarm(root);
486
+ if (input.value.includes(",")) tagsAdd(root, input.value.split(","));
487
+ });
488
+ on("paste", (e) => {
489
+ const input = tagsInput(e);
490
+ const v = e.clipboardData?.getData("text") || "";
491
+ if (!input || !/[,\n]/.test(v)) return;
492
+ e.preventDefault();
493
+ tagsAdd(input.closest("[data-asta-tags]"), v.split(/[,\n]/));
494
+ });
495
+ on("focusout", (e) => {
496
+ const input = tagsInput(e);
497
+ if (!input) return;
498
+ const root = input.closest("[data-asta-tags]");
499
+ tagsDisarm(root);
500
+ if (input.value.trim()) tagsAdd(root, [input.value]);
501
+ });
502
+ on("click", (e) => {
503
+ const rm = near(e, "[data-asta-tag-remove]");
504
+ if (rm) {
505
+ e.stopPropagation();
506
+ tagsRemove(rm.closest("[data-asta-tags]"), rm.closest("[data-asta-tag]"));
507
+ return;
508
+ }
509
+ const box = near(e, "[data-asta-tags-box]");
510
+ if (box) box.querySelector("[data-asta-tags-input]")?.focus();
511
+ });
512
+
513
+ /* ---------- RangeSlider ---------- */
514
+
515
+ function rangeSync(root, moved) {
516
+ const [a, b] = root.querySelectorAll("[data-asta-range-input]");
517
+ const gap = Number(root.dataset.gap) || 0;
518
+ const min = Number(a.min);
519
+ const max = Number(a.max);
520
+ // The thumbs never cross and keep the gap.
521
+ if (moved === a && Number(a.value) > Number(b.value) - gap) a.value = String(Math.max(min, Number(b.value) - gap));
522
+ if (moved === b && Number(b.value) < Number(a.value) + gap) b.value = String(Math.min(max, Number(a.value) + gap));
523
+ const lo = Number(a.value);
524
+ const hi = Number(b.value);
525
+ const pct = (v) => (max > min ? ((v - min) / (max - min)) * 100 : 0);
526
+ root.querySelector("[data-asta-range-fill]").style.transform = `translateX(${pct(lo)}%) scaleX(${(pct(hi) - pct(lo)) / 100})`;
527
+ const fmt = (v) => `${root.dataset.prefix || ""}${v}${root.dataset.suffix || ""}`;
528
+ [lo, hi].forEach((v, i) => {
529
+ const at = root.querySelector(`[data-asta-range-at="${i}"]`);
530
+ // cqw = % of the track, so the zero-width marker never widens the page.
531
+ at.style.transform = `translateX(${pct(v)}cqw)`;
532
+ at.querySelector("[data-asta-range-bubble]").textContent = fmt(v);
533
+ [a, b][i].setAttribute("aria-valuetext", fmt(v));
534
+ });
535
+ // The thumb you moved stays on top, and a low thumb parked at the max must stay grabbable.
536
+ if (moved) {
537
+ a.style.zIndex = moved === a || lo >= max ? "2" : "1";
538
+ b.style.zIndex = moved === a || lo >= max ? "1" : "2";
539
+ }
540
+ }
541
+ on("input", (e) => {
542
+ const input = e.target instanceof Element && e.target.closest("[data-asta-range-input]");
543
+ if (!input) return;
544
+ const root = input.closest("[data-asta-range]");
545
+ if (!e.isTrusted) return rangeSync(root, input);
546
+ root.removeAttribute("data-glide");
547
+ rangeSync(root, input);
548
+ });
549
+ on("pointerdown", (e) => {
550
+ const track = near(e, "[data-asta-range-track]");
551
+ if (!track || e.button !== 0) return;
552
+ const root = track.closest("[data-asta-range]");
553
+ const [a, b] = root.querySelectorAll("[data-asta-range-input]");
554
+ if (a.disabled) return;
555
+ const r = track.getBoundingClientRect();
556
+ const min = Number(a.min);
557
+ const max = Number(a.max);
558
+ const v = min + Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)) * (max - min);
559
+ const lo = Number(a.value);
560
+ const hi = Number(b.value);
561
+ const input = lo === hi ? (v < lo ? a : b) : Math.abs(v - lo) < Math.abs(v - hi) ? a : b;
562
+ e.preventDefault();
563
+ root.setAttribute("data-glide", "");
564
+ input.value = String(v);
565
+ input.focus({ preventScroll: true });
566
+ emit(input, "input");
567
+ emit(input, "change");
568
+ });
569
+
570
+ /* ---------- ColorPicker ---------- */
571
+
572
+ const parseHex = (s) => {
573
+ const h = String(s).trim().replace(/^#/, "").toLowerCase();
574
+ if (/^[0-9a-f]{3}$/.test(h)) return `#${[...h].map((c) => c + c).join("")}`;
575
+ if (/^[0-9a-f]{6}$/.test(h)) return `#${h}`;
576
+ return null;
577
+ };
578
+ const colorParts = (root) => ({
579
+ radios: [...root.querySelectorAll("input[type=radio]:not([data-asta-color-custom])")],
580
+ custom: root.querySelector("[data-asta-color-custom]"),
581
+ hex: root.querySelector("[data-asta-color-hex]"),
582
+ preview: root.querySelector("[data-asta-color-preview]"),
583
+ hint: root.querySelector("[data-asta-color-hint]"),
584
+ });
585
+ const colorCurrent = (root) => root.querySelector("input[type=radio]:checked")?.value || "";
586
+ function colorPreview(root, hex) {
587
+ const { preview } = colorParts(root);
588
+ if (!preview) return;
589
+ preview.style.background = hex || "transparent";
590
+ preview.toggleAttribute("data-empty", !hex);
591
+ }
592
+ function colorShow(root) {
593
+ const { hex, hint } = colorParts(root);
594
+ const cur = colorCurrent(root);
595
+ if (hex) hex.value = cur.replace(/^#/, "");
596
+ if (hint) {
597
+ hint.textContent = "";
598
+ hint.removeAttribute("data-on");
599
+ }
600
+ hex?.removeAttribute("aria-invalid");
601
+ colorPreview(root, cur);
602
+ }
603
+ function colorCommit(root) {
604
+ const { radios, custom, hex } = colorParts(root);
605
+ const v = parseHex(hex.value);
606
+ if (v && v !== colorCurrent(root)) {
607
+ const match = radios.find((r) => r.value === v);
608
+ const target = match || custom;
609
+ target.value = v;
610
+ target.checked = true;
611
+ emit(target, "change");
612
+ }
613
+ colorShow(root);
614
+ }
615
+ on("change", (e) => {
616
+ const root = e.target instanceof HTMLInputElement && e.target.type === "radio" && e.target.closest("[data-asta-color]");
617
+ if (root) colorShow(root);
618
+ });
619
+ on("keydown", (e) => {
620
+ const t = e.target;
621
+ const root = t instanceof HTMLInputElement && t.closest("[data-asta-color]");
622
+ if (!root) return;
623
+ if (t.type === "radio" && (e.key === "ArrowDown" || e.key === "ArrowUp")) {
624
+ // Up and down move a whole row, like the grid looks.
625
+ const { radios } = colorParts(root);
626
+ const cols = Number(root.dataset.columns) || 5;
627
+ const i = radios.indexOf(t);
628
+ const j = e.key === "ArrowDown" ? Math.min(radios.length - 1, i + cols) : Math.max(0, i - cols);
629
+ e.preventDefault();
630
+ if (i < 0 || j === i) return;
631
+ radios[j].checked = true;
632
+ radios[j].focus();
633
+ emit(radios[j], "change");
634
+ } else if (t.matches("[data-asta-color-hex]")) {
635
+ if (e.key === "Enter") {
636
+ e.preventDefault();
637
+ colorCommit(root);
638
+ } else if (e.key === "Escape") {
639
+ e.preventDefault();
640
+ colorShow(root);
641
+ }
642
+ }
643
+ });
644
+ on("input", (e) => {
645
+ const t = e.target;
646
+ if (!(t instanceof HTMLInputElement) || !t.matches("[data-asta-color-hex]")) return;
647
+ const root = t.closest("[data-asta-color]");
648
+ const { hint } = colorParts(root);
649
+ const v = parseHex(t.value);
650
+ const bad = t.value.trim() !== "" && !v;
651
+ colorPreview(root, v);
652
+ t.toggleAttribute("aria-invalid", bad);
653
+ if (hint) {
654
+ hint.textContent = bad ? "Not a hex" : "";
655
+ hint.toggleAttribute("data-on", bad);
656
+ }
657
+ });
658
+ on("focusout", (e) => {
659
+ const t = e.target;
660
+ if (t instanceof HTMLInputElement && t.matches("[data-asta-color-hex]")) colorCommit(t.closest("[data-asta-color]"));
661
+ });
662
+
663
+ /* ---------- Combobox ---------- */
664
+
665
+ const combo = (root) => ({
666
+ input: root.querySelector("[data-asta-combo-input]"),
667
+ list: root.querySelector('[role="listbox"]'),
668
+ opts: [...root.querySelectorAll('[role="option"]')],
669
+ multi: root.dataset.astaCombo === "multiple",
670
+ value: root.querySelector("[data-asta-combo-value]"),
671
+ });
672
+ const comboShown = (root) => combo(root).opts.filter((o) => !o.hidden);
673
+ const comboEnabled = (root) => comboShown(root).filter((o) => o.getAttribute("aria-disabled") !== "true");
674
+ function comboActive(root, opt) {
675
+ const { input, opts } = combo(root);
676
+ opts.forEach((o) => o.toggleAttribute("data-active", o === opt));
677
+ if (opt) {
678
+ input.setAttribute("aria-activedescendant", opt.id);
679
+ opt.scrollIntoView({ block: "nearest" });
680
+ } else input.removeAttribute("aria-activedescendant");
681
+ }
682
+ function comboFilter(root, q) {
683
+ const { opts } = combo(root);
684
+ const query = q.trim().toLowerCase();
685
+ let n = 0;
686
+ for (const o of opts) {
687
+ const label = o.dataset.label || "";
688
+ const i = query ? label.toLowerCase().indexOf(query) : -1;
689
+ o.hidden = Boolean(query) && i < 0;
690
+ if (!o.hidden) n++;
691
+ const text = o.querySelector("[data-asta-combo-text]");
692
+ // The typed part in bold.
693
+ text.innerHTML =
694
+ i < 0
695
+ ? esc(label)
696
+ : `${esc(label.slice(0, i))}<span class="font-semibold text-ink">${esc(label.slice(i, i + query.length))}</span>${esc(label.slice(i + query.length))}`;
697
+ }
698
+ const empty = root.querySelector("[data-asta-combo-empty]");
699
+ empty.hidden = n > 0;
700
+ const said = root.querySelector("[data-asta-combo-query]");
701
+ said.textContent = query ? `Nothing matches “${q.trim()}”` : "";
702
+ }
703
+ function comboOpen(root) {
704
+ const { input, list, multi } = combo(root);
705
+ if (input.disabled || root.hasAttribute("data-open")) return;
706
+ root.setAttribute("data-open", "");
707
+ list.hidden = false;
708
+ input.setAttribute("aria-expanded", "true");
709
+ root.querySelector("[data-asta-combo-toggle]")?.setAttribute("aria-label", "Close list");
710
+ comboFilter(root, root._astaQuery ?? "");
711
+ const picked = !multi && comboEnabled(root).find((o) => o.getAttribute("aria-selected") === "true");
712
+ comboActive(root, picked || comboEnabled(root)[0]);
713
+ }
714
+ function comboClose(root, dismiss) {
715
+ const { input, list, multi, value, opts } = combo(root);
716
+ if (!root.hasAttribute("data-open") && root._astaQuery == null) return;
717
+ // Leaving a single combobox with its text cleared clears the value.
718
+ if (dismiss && !multi && root._astaQuery != null && !root._astaQuery.trim() && opts.some((o) => o.getAttribute("aria-selected") === "true")) {
719
+ opts.forEach((o) => o.setAttribute("aria-selected", "false"));
720
+ if (value) {
721
+ value.value = "";
722
+ emit(value, "change");
723
+ } else emit(root, "change");
724
+ }
725
+ root._astaQuery = null;
726
+ root.removeAttribute("data-open");
727
+ list.hidden = true;
728
+ input.setAttribute("aria-expanded", "false");
729
+ input.removeAttribute("aria-activedescendant");
730
+ root.querySelector("[data-asta-combo-toggle]")?.setAttribute("aria-label", "Open list");
731
+ if (!multi) input.value = opts.find((o) => o.getAttribute("aria-selected") === "true")?.dataset.label || "";
732
+ }
733
+ function comboChipSync(root) {
734
+ const { input, multi } = combo(root);
735
+ if (!multi) return;
736
+ input.placeholder = root.querySelector("[data-asta-combo-chip]") ? "" : input.dataset.placeholder || "";
737
+ }
738
+ function comboPick(root, opt) {
739
+ if (!opt || opt.getAttribute("aria-disabled") === "true") return;
740
+ const { input, multi, value, opts } = combo(root);
741
+ if (multi) {
742
+ const v = opt.dataset.value;
743
+ const chip = [...root.querySelectorAll("[data-asta-combo-chip]")].find((c) => c.dataset.astaComboChip === v);
744
+ if (chip) {
745
+ chip.remove();
746
+ opt.setAttribute("aria-selected", "false");
747
+ } else {
748
+ const c = root.querySelector("template[data-asta-combo-tpl]").content.firstElementChild.cloneNode(true);
749
+ c.dataset.astaComboChip = v;
750
+ c.querySelector("[data-asta-combo-chip-text]").textContent = opt.dataset.label;
751
+ c.querySelector("[data-asta-combo-remove]").setAttribute("aria-label", `Remove ${opt.dataset.label}`);
752
+ const icon = opt.querySelector("[data-asta-combo-icon]");
753
+ if (icon) {
754
+ const s = document.createElement("span");
755
+ s.className = "inline-flex shrink-0 [&_svg]:h-3.5 [&_svg]:w-3.5";
756
+ s.innerHTML = icon.innerHTML;
757
+ c.prepend(s);
758
+ }
759
+ const hidden = c.querySelector("input[type=hidden]");
760
+ if (hidden) hidden.value = v;
761
+ input.before(c);
762
+ opt.setAttribute("aria-selected", "true");
763
+ }
764
+ root._astaQuery = null;
765
+ input.value = "";
766
+ comboFilter(root, "");
767
+ comboChipSync(root);
768
+ input.focus();
769
+ emit(root, "change");
770
+ return;
771
+ }
772
+ opts.forEach((o) => o.setAttribute("aria-selected", String(o === opt)));
773
+ root._astaQuery = null;
774
+ comboClose(root, false);
775
+ if (value) {
776
+ value.value = opt.dataset.value;
777
+ emit(value, "change");
778
+ } else emit(root, "change");
779
+ }
780
+ function comboMove(root, step) {
781
+ const list = comboEnabled(root);
782
+ if (!list.length) return;
783
+ const i = list.findIndex((o) => o.hasAttribute("data-active"));
784
+ comboActive(root, list[(i + step + list.length) % list.length] || list[0]);
785
+ }
786
+ const comboInput = (e) => (e.target instanceof HTMLInputElement && e.target.matches("[data-asta-combo-input]") ? e.target : null);
787
+ on("focusin", (e) => {
788
+ const input = comboInput(e);
789
+ if (!input) return;
790
+ const root = input.closest("[data-asta-combo]");
791
+ if (root.dataset.astaCombo !== "multiple") input.select();
792
+ comboOpen(root);
793
+ });
794
+ on("focusout", (e) => {
795
+ const root = near(e, "[data-asta-combo]");
796
+ if (root && !root.contains(e.relatedTarget)) comboClose(root, true);
797
+ });
798
+ on("input", (e) => {
799
+ const input = comboInput(e);
800
+ if (!input) return;
801
+ const root = input.closest("[data-asta-combo]");
802
+ root._astaQuery = input.value;
803
+ comboOpen(root);
804
+ comboFilter(root, input.value);
805
+ comboActive(root, comboEnabled(root)[0]);
806
+ });
807
+ on("keydown", (e) => {
808
+ const input = comboInput(e);
809
+ if (!input) return;
810
+ const root = input.closest("[data-asta-combo]");
811
+ const open = root.hasAttribute("data-open");
812
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
813
+ if (!open) comboOpen(root);
814
+ else comboMove(root, e.key === "ArrowDown" ? 1 : -1);
815
+ } else if (e.key === "Enter") {
816
+ if (!open) return;
817
+ comboPick(root, root.querySelector('[role="option"][data-active]:not([hidden])'));
818
+ } else if (e.key === "Escape") {
819
+ if (!open && root._astaQuery == null) return;
820
+ comboClose(root, false);
821
+ } else if (e.key === "Backspace" && root.dataset.astaCombo === "multiple" && !input.value) {
822
+ const chips = root.querySelectorAll("[data-asta-combo-chip]");
823
+ const last = chips[chips.length - 1];
824
+ if (!last) return;
825
+ const opt = combo(root).opts.find((o) => o.dataset.value === last.dataset.astaComboChip);
826
+ if (opt) comboPick(root, opt);
827
+ else last.remove();
828
+ } else return;
829
+ e.preventDefault();
830
+ });
831
+ on("pointerdown", (e) => {
832
+ const t = el(e);
833
+ if (!t) return;
834
+ if (t.closest('[data-asta-combo] [role="listbox"]') || t.closest("[data-asta-combo-toggle]") || t.closest("[data-asta-combo-remove]")) {
835
+ // Keep focus in the field.
836
+ e.preventDefault();
837
+ return;
838
+ }
839
+ const box = t.matches("[data-asta-combo-box]") ? t : null;
840
+ if (box) {
841
+ e.preventDefault();
842
+ const root = box.closest("[data-asta-combo]");
843
+ combo(root).input.focus();
844
+ comboOpen(root);
845
+ }
846
+ });
847
+ on("pointermove", (e) => {
848
+ const opt = near(e, '[data-asta-combo] [role="option"]');
849
+ if (opt && !opt.hasAttribute("data-active") && opt.getAttribute("aria-disabled") !== "true") comboActive(opt.closest("[data-asta-combo]"), opt);
850
+ });
851
+ on("click", (e) => {
852
+ const opt = near(e, '[data-asta-combo] [role="option"]');
853
+ if (opt) return comboPick(opt.closest("[data-asta-combo]"), opt);
854
+ const toggle = near(e, "[data-asta-combo-toggle]");
855
+ if (toggle) {
856
+ const root = toggle.closest("[data-asta-combo]");
857
+ if (root.hasAttribute("data-open")) comboClose(root, false);
858
+ else {
859
+ combo(root).input.focus();
860
+ comboOpen(root);
861
+ }
862
+ return;
863
+ }
864
+ const rm = near(e, "[data-asta-combo-remove]");
865
+ if (rm) {
866
+ const root = rm.closest("[data-asta-combo]");
867
+ const chip = rm.closest("[data-asta-combo-chip]");
868
+ const opt = combo(root).opts.find((o) => o.dataset.value === chip.dataset.astaComboChip);
869
+ if (opt) comboPick(root, opt);
870
+ else {
871
+ chip.remove();
872
+ comboChipSync(root);
873
+ emit(root, "change");
874
+ }
875
+ }
876
+ });
877
+
878
+ /* ---------- DatePicker ---------- */
879
+
880
+ const day0 = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate());
881
+ const addDays = (d, n) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
882
+ const month0 = (d) => new Date(d.getFullYear(), d.getMonth(), 1);
883
+ const addMonths = (d, n) => {
884
+ const t = new Date(d.getFullYear(), d.getMonth() + n, 1);
885
+ const last = new Date(t.getFullYear(), t.getMonth() + 1, 0).getDate();
886
+ return new Date(t.getFullYear(), t.getMonth(), Math.min(d.getDate(), last));
887
+ };
888
+ const same = (a, b) => !!a && !!b && a.getTime() === b.getTime();
889
+ const pad = (n) => String(n).padStart(2, "0");
890
+ const key = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
891
+ const parseDay = (s) => {
892
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(s || "").trim());
893
+ return m ? new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])) : null;
894
+ };
895
+
896
+ function dp(root) {
897
+ if (root._astaDp) return root._astaDp;
898
+ const locale = root.dataset.locale || "en-US";
899
+ let fmt, title, full, wd, wdl;
900
+ try {
901
+ fmt = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", year: "numeric" });
902
+ title = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" });
903
+ full = new Intl.DateTimeFormat(locale, { weekday: "long", month: "long", day: "numeric", year: "numeric" });
904
+ wd = new Intl.DateTimeFormat(locale, { weekday: "short" });
905
+ wdl = new Intl.DateTimeFormat(locale, { weekday: "long" });
906
+ } catch {
907
+ return dp(Object.assign(root, { dataset: Object.assign(root.dataset, { locale: "en-US" }) }));
908
+ }
909
+ const s = {
910
+ range: root.dataset.astaDate === "range",
911
+ week: Number(root.dataset.week) || 0,
912
+ min: parseDay(root.dataset.min),
913
+ max: parseDay(root.dataset.max),
914
+ fmt,
915
+ title,
916
+ full,
917
+ wd,
918
+ wdl,
919
+ start: null,
920
+ end: null,
921
+ single: null,
922
+ view: null,
923
+ focus: null,
924
+ hover: null,
925
+ today: null,
926
+ };
927
+ const v = root.querySelector("[data-asta-date-value]").value;
928
+ if (s.range) {
929
+ const [a, b] = v.split("/");
930
+ s.start = parseDay(a);
931
+ s.end = s.start ? parseDay(b) : null;
932
+ } else s.single = parseDay(v);
933
+ root._astaDp = s;
934
+ return s;
935
+ }
936
+ const dpOff = (s, d) => (s.min && d < s.min) || (s.max && d > s.max) || false;
937
+ const dpClamp = (s, d) => (s.min && d < s.min ? s.min : s.max && d > s.max ? s.max : d);
938
+ function dpText(root) {
939
+ const s = dp(root);
940
+ const t = root.querySelector("[data-asta-date-text]");
941
+ let shown = null;
942
+ if (s.range) {
943
+ if (s.start && s.end) shown = s.fmt.formatRange ? s.fmt.formatRange(s.start, s.end) : `${s.fmt.format(s.start)} – ${s.fmt.format(s.end)}`;
944
+ else if (s.start) shown = `${s.fmt.format(s.start)} – …`;
945
+ } else if (s.single) shown = s.fmt.format(s.single);
946
+ t.textContent = shown ?? root.dataset.placeholder ?? "";
947
+ t.classList.toggle("text-ink", !!shown);
948
+ t.classList.toggle("text-mute", !shown);
949
+ }
950
+ const DP_NAV =
951
+ "flex h-8 w-8 items-center justify-center rounded-md text-ink-2 outline-none transition-[background-color,transform] duration-150 hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 active:scale-90 disabled:pointer-events-none disabled:opacity-35";
952
+ const DP_DAY =
953
+ "relative mx-auto flex h-9 w-9 items-center justify-center rounded-lg text-[13px] tabular-nums outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-brand/50 disabled:cursor-not-allowed disabled:opacity-30";
954
+ const dpCanFlip = (s, n) => {
955
+ const to = addMonths(s.view, n);
956
+ return !(s.min && to < month0(s.min)) && !(s.max && to > month0(s.max));
957
+ };
958
+ // Build the month. dir slides the grid in from the side the user paged to.
959
+ function dpRender(root, dir) {
960
+ const s = dp(root);
961
+ const cal = root.querySelector("[data-asta-date-cal]");
962
+ const lead = (s.view.getDay() - s.week + 7) % 7;
963
+ const first = addDays(s.view, -lead);
964
+ const arrow = (d) =>
965
+ `<button type="button" data-dp-flip="${d}" aria-label="${d === 1 ? "Next month" : "Previous month"}" class="${DP_NAV}"${dpCanFlip(s, d) ? "" : " disabled"}><svg viewBox="0 0 16 16" class="h-4 w-4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${d === 1 ? "m6 3.5 4.5 4.5L6 12.5" : "m10 3.5L5.5 8l4.5 4.5"}"/></svg></button>`;
966
+ const weekdays = Array.from({ length: 7 }, (_, i) => {
967
+ const d = new Date(2026, 10, 1 + ((i + s.week) % 7));
968
+ return `<span class="py-1 text-center text-[11px] font-medium text-mute" title="${esc(s.wdl.format(d))}">${esc(s.wd.format(d))}</span>`;
969
+ }).join("");
970
+ // 6 weeks, always, so the popover never changes height between months.
971
+ const cells = Array.from({ length: 42 }, (_, i) => {
972
+ const d = addDays(first, i);
973
+ const k = key(d);
974
+ return `<div role="gridcell" class="relative" data-dp-cell="${k}"><span aria-hidden="true" data-dp-band class="absolute inset-y-0 hidden bg-[color-mix(in_srgb,var(--brand)_11%,transparent)]"></span><button type="button" data-dp-day="${k}" tabindex="-1" aria-label="${esc(s.full.format(d))}" class="${DP_DAY} ${d.getMonth() === s.view.getMonth() ? "text-ink" : "text-mute"}"${dpOff(s, d) ? " disabled" : ""}><span class="relative">${d.getDate()}</span></button></div>`;
975
+ }).join("");
976
+ const today = s.today && !dpOff(s, s.today);
977
+ cal.innerHTML =
978
+ `<div class="mb-2 flex items-center justify-between gap-2 pl-2"><p aria-live="polite" class="text-[14px] font-medium tracking-[-0.01em] text-ink">${esc(s.title.format(s.view))}</p><div class="flex gap-0.5">${arrow(-1)}${arrow(1)}</div></div>` +
979
+ `<div class="grid grid-cols-7 pb-1" aria-hidden="true">${weekdays}</div>` +
980
+ `<div class="overflow-hidden"><div role="grid" aria-label="${esc(s.title.format(s.view))}" data-dp-grid class="grid grid-cols-7 gap-y-0.5 ${dir === 1 ? "asta-dp-next" : dir === -1 ? "asta-dp-prev" : ""}">${cells}</div></div>` +
981
+ `<div class="mt-2 flex items-center justify-between gap-2 pl-2"><p class="text-[12px] tabular-nums text-mute" data-dp-status></p><div class="flex gap-1"><button type="button" data-dp-clear class="h-7 rounded-md px-2.5 text-[12px] font-medium text-ink-2 outline-none transition-colors hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50">Clear</button>${
982
+ today
983
+ ? '<button type="button" data-dp-today class="h-7 rounded-md bg-paper-2 px-2.5 text-[12px] font-medium text-ink outline-none transition-colors hover:bg-[color-mix(in_srgb,var(--ink)_8%,var(--paper-2))] focus-visible:ring-2 focus-visible:ring-brand/50">Today</button>'
984
+ : ""
985
+ }</div></div>`;
986
+ dpPaint(root, true);
987
+ }
988
+ // Apply picked, band, today and focus to the cells already built, so hovering never rebuilds the month.
989
+ function dpPaint(root, fresh) {
990
+ const s = dp(root);
991
+ const preview = s.range && s.start && !s.end ? s.hover || s.focus : null;
992
+ const from = s.start;
993
+ const to = s.end || (preview && s.start && preview > s.start ? preview : null);
994
+ root.querySelectorAll("[data-dp-cell]").forEach((cell) => {
995
+ const d = parseDay(cell.dataset.dpCell);
996
+ const b = cell.lastElementChild;
997
+ const picked = s.range ? same(d, s.start) || same(d, s.end) : same(d, s.single);
998
+ const inBand = !!(from && to && d >= from && d <= to && !same(from, to));
999
+ const band = cell.firstElementChild;
1000
+ band.classList.toggle("hidden", !inBand);
1001
+ band.classList.toggle("left-1/2", inBand && same(d, from));
1002
+ band.classList.toggle("right-1/2", inBand && same(d, to));
1003
+ band.classList.toggle("left-0", inBand && !same(d, from));
1004
+ band.classList.toggle("right-0", inBand && !same(d, to));
1005
+ band.classList.toggle("opacity-70", !s.end);
1006
+ cell.setAttribute("aria-selected", String(picked || inBand));
1007
+ const inMonth = d.getMonth() === s.view.getMonth();
1008
+ b.classList.toggle("font-medium", picked);
1009
+ b.classList.toggle("text-white", picked);
1010
+ b.classList.toggle("text-ink", !picked && inMonth);
1011
+ b.classList.toggle("text-mute", !picked && !inMonth);
1012
+ b.classList.toggle("hover:bg-paper-2", !picked);
1013
+ let fill = b.querySelector("[data-dp-fill]");
1014
+ if (picked && !fill) {
1015
+ fill = document.createElement("span");
1016
+ fill.dataset.dpFill = "";
1017
+ fill.setAttribute("aria-hidden", "true");
1018
+ fill.className = `absolute inset-0 rounded-lg bg-brand shadow-[0_4px_10px_-4px_color-mix(in_srgb,var(--brand)_70%,transparent)]${fresh ? "" : " asta-dp-pop"}`;
1019
+ b.prepend(fill);
1020
+ } else if (!picked) fill?.remove();
1021
+ const isToday = same(d, s.today);
1022
+ let dot = b.querySelector("[data-dp-dot]");
1023
+ if (isToday && !dot) {
1024
+ dot = document.createElement("span");
1025
+ dot.dataset.dpDot = "";
1026
+ dot.setAttribute("aria-hidden", "true");
1027
+ b.append(dot);
1028
+ }
1029
+ if (dot) dot.className = `absolute bottom-1 left-1/2 h-1 w-1 -translate-x-1/2 rounded-full ${picked ? "bg-white" : "bg-brand"}`;
1030
+ if (isToday) b.setAttribute("aria-current", "date");
1031
+ b.tabIndex = same(d, s.focus) ? 0 : -1;
1032
+ });
1033
+ const status = root.querySelector("[data-dp-status]");
1034
+ if (status)
1035
+ status.textContent =
1036
+ s.range && s.start && !s.end ? "Pick an end date" : s.range && s.start && s.end ? `${Math.round((s.end - s.start) / 864e5) + 1} days` : "";
1037
+ }
1038
+ function dpFocusDay(root) {
1039
+ const s = dp(root);
1040
+ root.querySelector(`[data-dp-day="${key(s.focus)}"]`)?.focus({ preventScroll: true });
1041
+ }
1042
+ function dpOpen(root) {
1043
+ const s = dp(root);
1044
+ const trigger = root.querySelector("[data-asta-date-trigger]");
1045
+ if (trigger.disabled) return;
1046
+ s.today = day0(new Date());
1047
+ const anchor = dpClamp(s, (s.range ? s.start : s.single) || s.today);
1048
+ s.view = month0(anchor);
1049
+ s.focus = anchor;
1050
+ s.hover = null;
1051
+ root.querySelector("[data-asta-date-cal]").hidden = false;
1052
+ root.setAttribute("data-open", "");
1053
+ trigger.setAttribute("aria-expanded", "true");
1054
+ dpRender(root, 0);
1055
+ dpFocusDay(root);
1056
+ }
1057
+ function dpClose(root, refocus) {
1058
+ if (!root.hasAttribute("data-open")) return;
1059
+ root.querySelector("[data-asta-date-cal]").hidden = true;
1060
+ root.removeAttribute("data-open");
1061
+ const trigger = root.querySelector("[data-asta-date-trigger]");
1062
+ trigger.setAttribute("aria-expanded", "false");
1063
+ if (refocus) trigger.focus();
1064
+ }
1065
+ function dpMove(root, d, steer) {
1066
+ const s = dp(root);
1067
+ const next = dpClamp(s, d);
1068
+ if (next.getFullYear() !== s.view.getFullYear() || next.getMonth() !== s.view.getMonth()) {
1069
+ const dir = next > s.view ? 1 : -1;
1070
+ s.view = month0(next);
1071
+ s.focus = next;
1072
+ dpRender(root, dir);
1073
+ } else {
1074
+ s.focus = next;
1075
+ dpPaint(root, false);
1076
+ }
1077
+ if (steer) dpFocusDay(root);
1078
+ }
1079
+ function dpFlip(root, n, steer) {
1080
+ const s = dp(root);
1081
+ if (!dpCanFlip(s, n)) return;
1082
+ s.view = addMonths(s.view, n);
1083
+ s.view = month0(s.view);
1084
+ s.focus = dpClamp(s, addMonths(s.focus, n));
1085
+ dpRender(root, n > 0 ? 1 : -1);
1086
+ if (steer) dpFocusDay(root);
1087
+ }
1088
+ function dpSave(root) {
1089
+ const s = dp(root);
1090
+ const input = root.querySelector("[data-asta-date-value]");
1091
+ const v = s.range ? (s.start && s.end ? `${key(s.start)}/${key(s.end)}` : "") : s.single ? key(s.single) : "";
1092
+ dpText(root);
1093
+ if (input.value === v) return;
1094
+ input.value = v;
1095
+ emit(input, "change");
1096
+ }
1097
+ function dpPick(root, d) {
1098
+ const s = dp(root);
1099
+ if (dpOff(s, d)) return;
1100
+ if (!s.range) {
1101
+ s.single = d;
1102
+ dpSave(root);
1103
+ dpClose(root, true);
1104
+ return;
1105
+ }
1106
+ if (!s.start || s.end || d < s.start) {
1107
+ s.start = d;
1108
+ s.end = null;
1109
+ } else s.end = d;
1110
+ dpSave(root);
1111
+ if (s.end) dpClose(root, true);
1112
+ else {
1113
+ s.focus = d;
1114
+ dpPaint(root, false);
1115
+ dpFocusDay(root);
1116
+ }
1117
+ }
1118
+ on("click", (e) => {
1119
+ const t = el(e);
1120
+ const root = t?.closest("[data-asta-date]");
1121
+ // A click outside closes any open calendar.
1122
+ for (const r of document.querySelectorAll("[data-asta-date][data-open]")) if (r !== root) dpClose(r, false);
1123
+ if (!root) return;
1124
+ if (t.closest("[data-asta-date-trigger]")) return root.hasAttribute("data-open") ? dpClose(root, false) : dpOpen(root);
1125
+ const day = t.closest("[data-dp-day]");
1126
+ if (day) return dpPick(root, parseDay(day.dataset.dpDay));
1127
+ const flip = t.closest("[data-dp-flip]");
1128
+ if (flip) return dpFlip(root, Number(flip.dataset.dpFlip), false);
1129
+ if (t.closest("[data-dp-clear]")) {
1130
+ const s = dp(root);
1131
+ s.single = s.start = s.end = null;
1132
+ dpSave(root);
1133
+ return dpClose(root, true);
1134
+ }
1135
+ if (t.closest("[data-dp-today]")) dpMove(root, dp(root).today, true);
1136
+ });
1137
+ on("pointerover", (e) => {
1138
+ const day = near(e, "[data-asta-date] [data-dp-day]");
1139
+ if (!day) return;
1140
+ const root = day.closest("[data-asta-date]");
1141
+ const s = dp(root);
1142
+ if (!s.range || !s.start || s.end) return;
1143
+ s.hover = parseDay(day.dataset.dpDay);
1144
+ dpPaint(root, false);
1145
+ });
1146
+ on("keydown", (e) => {
1147
+ const t = el(e);
1148
+ const root = t?.closest("[data-asta-date]");
1149
+ if (!root) return;
1150
+ if (t.matches("[data-asta-date-trigger]") && e.key === "ArrowDown" && !root.hasAttribute("data-open")) {
1151
+ e.preventDefault();
1152
+ return dpOpen(root);
1153
+ }
1154
+ if (!t.closest("[data-asta-date-cal]")) return;
1155
+ if (e.key === "Escape") {
1156
+ e.preventDefault();
1157
+ return dpClose(root, true);
1158
+ }
1159
+ if (!t.matches("[data-dp-day]")) return;
1160
+ const s = dp(root);
1161
+ const f = s.focus;
1162
+ const dow = (f.getDay() - s.week + 7) % 7;
1163
+ if (e.key === "ArrowRight") dpMove(root, addDays(f, 1), true);
1164
+ else if (e.key === "ArrowLeft") dpMove(root, addDays(f, -1), true);
1165
+ else if (e.key === "ArrowDown") dpMove(root, addDays(f, 7), true);
1166
+ else if (e.key === "ArrowUp") dpMove(root, addDays(f, -7), true);
1167
+ else if (e.key === "Home") dpMove(root, addDays(f, -dow), true);
1168
+ else if (e.key === "End") dpMove(root, addDays(f, 6 - dow), true);
1169
+ else if (e.key === "PageDown") dpFlip(root, e.shiftKey ? 12 : 1, true);
1170
+ else if (e.key === "PageUp") dpFlip(root, e.shiftKey ? -12 : -1, true);
1171
+ else if (e.key === "Enter" || e.key === " ") dpPick(root, f);
1172
+ else return;
1173
+ e.preventDefault();
1174
+ });
1175
+ on("focusin", (e) => {
1176
+ const day = near(e, "[data-asta-date] [data-dp-day]");
1177
+ if (!day) return;
1178
+ const root = day.closest("[data-asta-date]");
1179
+ const s = dp(root);
1180
+ const d = parseDay(day.dataset.dpDay);
1181
+ if (!same(d, s.focus)) {
1182
+ s.focus = d;
1183
+ dpPaint(root, false);
1184
+ }
1185
+ });
1186
+
1187
+ /* ---------- FileUpload ---------- */
1188
+
1189
+ const fmtBytes = (n) => (n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB` : `${(n / 1024 ** 2).toFixed(1)} MB`);
1190
+ const accepts = (file, accept) => {
1191
+ if (!accept) return true;
1192
+ const name = file.name.toLowerCase();
1193
+ const type = file.type.toLowerCase();
1194
+ return accept
1195
+ .split(",")
1196
+ .map((a) => a.trim().toLowerCase())
1197
+ .filter(Boolean)
1198
+ .some((a) => (a.startsWith(".") ? name.endsWith(a) : a.endsWith("/*") ? type.startsWith(a.slice(0, -1)) : type === a));
1199
+ };
1200
+ const extOf = (name) => {
1201
+ const i = name.lastIndexOf(".");
1202
+ return i > 0 ? name.slice(i + 1, i + 5).toUpperCase() : "FILE";
1203
+ };
1204
+ function uploadSync(root) {
1205
+ const input = root.querySelector("[data-asta-upload-input]");
1206
+ const list = root.querySelector("[data-asta-upload-list]");
1207
+ const files = root._astaFiles || [];
1208
+ try {
1209
+ const dt = new DataTransfer();
1210
+ files.forEach((f) => dt.items.add(f));
1211
+ input.files = dt.files;
1212
+ } catch {}
1213
+ const rows = [...list.children];
1214
+ rows.forEach((li) => !files.includes(li._astaFile) && li.remove());
1215
+ const have = new Set(rows.map((li) => li._astaFile));
1216
+ const tpl = root.querySelector("template[data-asta-upload-tpl]");
1217
+ for (const f of files) {
1218
+ if (have.has(f)) continue;
1219
+ const li = tpl.content.firstElementChild.cloneNode(true);
1220
+ li._astaFile = f;
1221
+ li.querySelector("[data-ext]").textContent = extOf(f.name);
1222
+ li.querySelector("[data-file-name]").textContent = f.name;
1223
+ li.querySelector("[data-file-meta]").textContent = fmtBytes(f.size);
1224
+ li.querySelector("[role=progressbar]").setAttribute("aria-label", `${f.name} upload`);
1225
+ li.querySelector("[data-asta-upload-remove]").setAttribute("aria-label", `Remove ${f.name}`);
1226
+ list.append(li);
1227
+ }
1228
+ }
1229
+ function uploadError(root, msg) {
1230
+ const p = root.querySelector("[data-asta-upload-error]");
1231
+ p.querySelector("[data-asta-upload-error-text]").textContent = msg || "";
1232
+ if (msg) {
1233
+ p.hidden = true;
1234
+ void p.offsetWidth;
1235
+ }
1236
+ p.hidden = !msg;
1237
+ }
1238
+ function uploadAdd(root, list) {
1239
+ const input = root.querySelector("[data-asta-upload-input]");
1240
+ if (input.disabled) return;
1241
+ const incoming = [...list];
1242
+ if (!incoming.length) return;
1243
+ const multiple = input.multiple;
1244
+ const current = root._astaFiles || [];
1245
+ const maxFiles = Number(root.dataset.maxFiles) || 0;
1246
+ const maxSize = Number(root.dataset.maxSize) || 0;
1247
+ // A single-file input replaces what is there, so only a multiple list counts existing files.
1248
+ const room = maxFiles ? Math.max(0, maxFiles - (multiple ? current.length : 0)) : Infinity;
1249
+ const rejected = [];
1250
+ const ok = [];
1251
+ for (const f of multiple ? incoming : incoming.slice(0, 1)) {
1252
+ if (!accepts(f, root.dataset.accept)) rejected.push(`${f.name} isn't an accepted file type.`);
1253
+ else if (maxSize && f.size > maxSize) rejected.push(`${f.name} is over ${fmtBytes(maxSize)}.`);
1254
+ else if (ok.length >= room) rejected.push(`Only ${maxFiles} file${maxFiles === 1 ? "" : "s"} allowed.`);
1255
+ else ok.push(f);
1256
+ }
1257
+ uploadError(root, rejected.length ? (rejected.length === 1 ? rejected[0] : `${rejected[0]} ${rejected.length - 1} more skipped.`) : "");
1258
+ if (ok.length) root._astaFiles = multiple ? [...current, ...ok] : ok;
1259
+ uploadSync(root);
1260
+ }
1261
+ on("change", (e) => {
1262
+ const input = e.target instanceof HTMLInputElement && e.target.matches("[data-asta-upload-input]") ? e.target : null;
1263
+ if (!input || input._astaSyncing) return;
1264
+ // The picker replaces the input's files. Merge them into the list instead.
1265
+ uploadAdd(input.closest("[data-asta-upload]"), input.files);
1266
+ });
1267
+ on("click", (e) => {
1268
+ const rm = near(e, "[data-asta-upload-remove]");
1269
+ if (!rm) return;
1270
+ const root = rm.closest("[data-asta-upload]");
1271
+ const f = rm.closest("li")._astaFile;
1272
+ root._astaFiles = (root._astaFiles || []).filter((x) => x !== f);
1273
+ uploadError(root, "");
1274
+ uploadSync(root);
1275
+ });
1276
+ ["dragenter", "dragleave", "dragover", "drop"].forEach((type) =>
1277
+ on(type, (e) => {
1278
+ const zone = near(e, "[data-asta-upload-zone]");
1279
+ if (!zone) return;
1280
+ e.preventDefault();
1281
+ const root = zone.closest("[data-asta-upload]");
1282
+ if (root.querySelector("[data-asta-upload-input]").disabled) return;
1283
+ if (type === "dragenter") {
1284
+ zone._astaDepth = (zone._astaDepth || 0) + 1;
1285
+ zone.setAttribute("data-over", "");
1286
+ } else if (type === "dragleave") {
1287
+ zone._astaDepth = Math.max(0, (zone._astaDepth || 0) - 1);
1288
+ if (!zone._astaDepth) zone.removeAttribute("data-over");
1289
+ } else if (type === "dragover") {
1290
+ if (e.dataTransfer) e.dataTransfer.dropEffect = "copy";
1291
+ } else {
1292
+ zone._astaDepth = 0;
1293
+ zone.removeAttribute("data-over");
1294
+ if (e.dataTransfer) uploadAdd(root, e.dataTransfer.files);
1295
+ }
1296
+ }),
1297
+ );
1298
+ // htmx reports upload progress on the element that sent the request. Show it on the rows of the uploads inside.
1299
+ const uploadsFor = (e) => {
1300
+ const t = el(e);
1301
+ if (!t) return [];
1302
+ const scope = t.closest("form") || t;
1303
+ return [...scope.querySelectorAll("[data-asta-upload]"), ...(t.closest("[data-asta-upload]") ? [t.closest("[data-asta-upload]")] : [])];
1304
+ };
1305
+ on("htmx:xhr:progress", (e) => {
1306
+ const { loaded, total } = e.detail || {};
1307
+ if (!total) return;
1308
+ const p = Math.min(1, loaded / total);
1309
+ for (const root of uploadsFor(e))
1310
+ for (const li of root.querySelectorAll("[data-asta-upload-list] > li")) {
1311
+ li.dataset.status = "uploading";
1312
+ li.querySelector("[data-file-bar]").style.transform = `scaleX(${p})`;
1313
+ li.querySelector("[data-file-meta]").textContent = `${Math.round(p * 100)}%`;
1314
+ li.querySelector("[role=progressbar]").setAttribute("aria-valuenow", String(Math.round(p * 100)));
1315
+ }
1316
+ });
1317
+ on("htmx:afterRequest", (e) => {
1318
+ for (const root of uploadsFor(e))
1319
+ for (const li of root.querySelectorAll('[data-asta-upload-list] > li[data-status="uploading"]')) {
1320
+ const ok = e.detail?.successful;
1321
+ li.dataset.status = ok ? "done" : "error";
1322
+ li.querySelector("[data-file-meta]").textContent = ok ? fmtBytes(li._astaFile.size) : "Failed";
1323
+ }
1324
+ });
1325
+
1326
+ /* ---------- InlineEdit ---------- */
1327
+
1328
+ const inline = (root) => ({
1329
+ view: root.querySelector("[data-asta-inline-view]"),
1330
+ input: root.querySelector("[data-asta-inline-input]"),
1331
+ sizer: root.querySelector("[data-asta-inline-sizer]"),
1332
+ text: root.querySelector("[data-asta-inline-text]"),
1333
+ tick: root.querySelector("[data-asta-inline-tick]"),
1334
+ status: root.querySelector("[data-asta-inline-status]"),
1335
+ });
1336
+ function inlineOpen(root) {
1337
+ const { view, input, sizer, tick } = inline(root);
1338
+ if (view.disabled || root.hasAttribute("data-editing")) return;
1339
+ input.value = input.dataset.saved || "";
1340
+ sizer.textContent = `${input.value || input.placeholder} `;
1341
+ root.removeAttribute("data-failed");
1342
+ clearTimeout(root._astaTick);
1343
+ tick.classList.add("hidden");
1344
+ tick.classList.remove("asta-inline-tick");
1345
+ root.setAttribute("data-editing", "");
1346
+ input.focus();
1347
+ input.select();
1348
+ }
1349
+ function inlineClose(root, keepFocus) {
1350
+ const { view, input } = inline(root);
1351
+ root._astaSaving = null;
1352
+ input.readOnly = false;
1353
+ root.removeAttribute("data-editing");
1354
+ root.removeAttribute("data-failed");
1355
+ if (keepFocus) view.focus();
1356
+ }
1357
+ function inlineCancel(root, keepFocus) {
1358
+ if (root._astaSaving) return;
1359
+ const { input } = inline(root);
1360
+ input.value = input.dataset.saved || "";
1361
+ inlineClose(root, keepFocus);
1362
+ emit(input, "asta:cancel");
1363
+ }
1364
+ function inlineDone(root, next, keepFocus) {
1365
+ const { view, input, text, tick, status } = inline(root);
1366
+ const label = input.getAttribute("aria-label") || "";
1367
+ input.dataset.saved = next;
1368
+ input.value = next;
1369
+ text.textContent = next || input.placeholder;
1370
+ view.classList.toggle("text-ink", !!next);
1371
+ view.classList.toggle("text-mute", !next);
1372
+ view.setAttribute("aria-label", `${label}: ${next || input.placeholder}. Edit`);
1373
+ inlineClose(root, keepFocus);
1374
+ tick.classList.remove("hidden");
1375
+ replay(tick, "asta-inline-tick");
1376
+ status.textContent = "Saved";
1377
+ clearTimeout(root._astaTick);
1378
+ root._astaTick = setTimeout(() => {
1379
+ tick.classList.add("hidden");
1380
+ tick.classList.remove("asta-inline-tick");
1381
+ status.textContent = "";
1382
+ }, 1700);
1383
+ }
1384
+ function inlineSave(root, keepFocus) {
1385
+ if (root._astaSaving || !root.hasAttribute("data-editing")) return;
1386
+ const { input, status } = inline(root);
1387
+ const next = input.value.trim();
1388
+ const cur = (input.dataset.saved || "").trim();
1389
+ // Nothing changed: just close. Empty but required: drop the edit and keep the old text.
1390
+ if (next === cur) return inlineClose(root, keepFocus);
1391
+ if (root.hasAttribute("data-required") && !next) return inlineCancel(root, keepFocus);
1392
+ input.value = next;
1393
+ // With hx-trigger="asta:save" the server saves it: keep the field open until the request lands.
1394
+ const server = window.htmx && /asta:save/.test(input.getAttribute("hx-trigger") || input.getAttribute("data-hx-trigger") || "");
1395
+ if (!server) {
1396
+ emit(input, "asta:save", { value: next });
1397
+ return inlineDone(root, next, keepFocus);
1398
+ }
1399
+ root._astaSaving = { next, keepFocus };
1400
+ input.readOnly = true;
1401
+ const done = (e) => {
1402
+ if (e.target !== input) return;
1403
+ input.removeEventListener("htmx:afterRequest", done);
1404
+ if (!root.isConnected || !root._astaSaving) return;
1405
+ if (e.detail?.successful) return inlineDone(root, next, root._astaSaving.keepFocus);
1406
+ root._astaSaving = null;
1407
+ input.readOnly = false;
1408
+ root.setAttribute("data-failed", "");
1409
+ status.textContent = "Couldn't save. Try again or press Escape.";
1410
+ requestAnimationFrame(() => input.focus());
1411
+ };
1412
+ input.addEventListener("htmx:afterRequest", done);
1413
+ emit(input, "asta:save", { value: next });
1414
+ }
1415
+ on("click", (e) => {
1416
+ const view = near(e, "[data-asta-inline-view]");
1417
+ if (view) inlineOpen(view.closest("[data-asta-inline]"));
1418
+ });
1419
+ on("keydown", (e) => {
1420
+ const input = e.target instanceof HTMLInputElement && e.target.matches("[data-asta-inline-input]") ? e.target : null;
1421
+ if (!input) return;
1422
+ const root = input.closest("[data-asta-inline]");
1423
+ if (e.key === "Enter") {
1424
+ e.preventDefault();
1425
+ inlineSave(root, true);
1426
+ } else if (e.key === "Escape") {
1427
+ e.preventDefault();
1428
+ e.stopPropagation();
1429
+ inlineCancel(root, true);
1430
+ }
1431
+ });
1432
+ on("input", (e) => {
1433
+ const input = e.target instanceof HTMLInputElement && e.target.matches("[data-asta-inline-input]") ? e.target : null;
1434
+ if (!input) return;
1435
+ const root = input.closest("[data-asta-inline]");
1436
+ inline(root).sizer.textContent = `${input.value || input.placeholder} `;
1437
+ root.removeAttribute("data-failed");
1438
+ });
1439
+ on("focusout", (e) => {
1440
+ const input = e.target instanceof HTMLInputElement && e.target.matches("[data-asta-inline-input]") ? e.target : null;
1441
+ if (!input) return;
1442
+ const root = input.closest("[data-asta-inline]");
1443
+ if (!root.hasAttribute("data-editing") || root._astaSaving) return;
1444
+ if (root.hasAttribute("data-cancel-on-blur")) inlineCancel(root, false);
1445
+ else inlineSave(root, false);
1446
+ });
1447
+
1448
+ /* ---------- Boot and htmx ---------- */
1449
+
1450
+ function scan(scope) {
1451
+ for (const r of scope.querySelectorAll("[data-asta-password]")) if (r.querySelector("[data-asta-password-input]")?.value) passwordCheck(r);
1452
+ for (const r of scope.querySelectorAll("[data-asta-date]")) if (!r._astaDp && r.dataset.locale && r.dataset.locale !== "en-US") dpText(r);
1453
+ for (const r of scope.querySelectorAll("[data-asta-otp]")) otpPaint(r);
1454
+ }
1455
+ const boot = () => scan(document);
1456
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot);
1457
+ else boot();
1458
+ document.addEventListener("htmx:afterSettle", (e) => scan(e.detail?.elt?.parentElement || document));
1459
+ })();