asta-ui 0.9.4 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/css/asta.css +2 -2
  2. package/css/asta.js +1461 -1
  3. package/css/components.css +1900 -138
  4. package/css/runtime/agent.css +136 -0
  5. package/css/runtime/agent.js +173 -0
  6. package/css/runtime/assist.css +79 -0
  7. package/css/runtime/assist.js +799 -0
  8. package/css/runtime/controls.css +48 -0
  9. package/css/runtime/controls.js +482 -0
  10. package/css/src/agent.css +484 -0
  11. package/css/src/assist.css +598 -0
  12. package/css/src/controls.css +424 -0
  13. package/css/tokens.css +16 -0
  14. package/dist/agent-plan.d.ts +2 -0
  15. package/dist/agent-plan.js +11 -0
  16. package/dist/agent-team.d.ts +2 -0
  17. package/dist/agent-team.js +7 -0
  18. package/dist/api-keys.d.ts +2 -0
  19. package/dist/api-keys.js +10 -0
  20. package/dist/autonomy-dial.d.ts +2 -0
  21. package/dist/autonomy-dial.js +7 -0
  22. package/dist/base/agent-plan.d.ts +2 -0
  23. package/dist/base/agent-plan.js +11 -0
  24. package/dist/base/agent-team.d.ts +2 -0
  25. package/dist/base/agent-team.js +7 -0
  26. package/dist/base/api-keys.d.ts +2 -0
  27. package/dist/base/api-keys.js +10 -0
  28. package/dist/base/autonomy-dial.d.ts +2 -0
  29. package/dist/base/autonomy-dial.js +7 -0
  30. package/dist/base/change-ledger.d.ts +2 -0
  31. package/dist/base/change-ledger.js +7 -0
  32. package/dist/base/citations.d.ts +2 -0
  33. package/dist/base/citations.js +9 -0
  34. package/dist/base/context-meter.d.ts +2 -0
  35. package/dist/base/context-meter.js +14 -0
  36. package/dist/base/fallback-chain.d.ts +2 -0
  37. package/dist/base/fallback-chain.js +7 -0
  38. package/dist/base/model-picker.d.ts +2 -0
  39. package/dist/base/model-picker.js +9 -0
  40. package/dist/base/prompt-composer.d.ts +2 -0
  41. package/dist/base/prompt-composer.js +9 -0
  42. package/dist/base/scrub-input.d.ts +2 -0
  43. package/dist/base/scrub-input.js +13 -0
  44. package/dist/base/thinking.d.ts +2 -0
  45. package/dist/base/thinking.js +11 -0
  46. package/dist/base/tool-approval.d.ts +2 -0
  47. package/dist/base/tool-approval.js +9 -0
  48. package/dist/base/trace-waterfall.d.ts +2 -0
  49. package/dist/base/trace-waterfall.js +9 -0
  50. package/dist/base.js +202 -134
  51. package/dist/change-ledger.d.ts +2 -0
  52. package/dist/change-ledger.js +7 -0
  53. package/dist/chunk-24O5V2PQ.js +253 -0
  54. package/dist/chunk-44DNL43W.js +490 -0
  55. package/dist/chunk-45IXJ7W7.js +245 -0
  56. package/dist/chunk-ANL6VX4X.js +326 -0
  57. package/dist/chunk-DNROUJ62.js +432 -0
  58. package/dist/chunk-F4CWSZXK.js +226 -0
  59. package/dist/chunk-GBOJUMMY.js +163 -0
  60. package/dist/chunk-H4NFBYKY.js +275 -0
  61. package/dist/chunk-KFPGQ5RT.js +321 -0
  62. package/dist/chunk-OIIMYSVT.js +342 -0
  63. package/dist/chunk-TL32C2SQ.js +221 -0
  64. package/dist/chunk-UBTYMAKF.js +240 -0
  65. package/dist/chunk-W6YVDJHX.js +235 -0
  66. package/dist/chunk-XYQI4ZYV.js +314 -0
  67. package/dist/citations.d.ts +2 -0
  68. package/dist/citations.js +9 -0
  69. package/dist/context-meter.d.ts +2 -0
  70. package/dist/context-meter.js +14 -0
  71. package/dist/fallback-chain.d.ts +2 -0
  72. package/dist/fallback-chain.js +7 -0
  73. package/dist/index.js +202 -134
  74. package/dist/model-picker.d.ts +2 -0
  75. package/dist/model-picker.js +9 -0
  76. package/dist/prompt-composer.d.ts +2 -0
  77. package/dist/prompt-composer.js +9 -0
  78. package/dist/scrub-input.d.ts +2 -0
  79. package/dist/scrub-input.js +13 -0
  80. package/dist/thinking.d.ts +2 -0
  81. package/dist/thinking.js +11 -0
  82. package/dist/tool-approval.d.ts +2 -0
  83. package/dist/tool-approval.js +9 -0
  84. package/dist/trace-waterfall.d.ts +2 -0
  85. package/dist/trace-waterfall.js +9 -0
  86. package/dist/types/components/kit/agent-plan.d.ts +34 -0
  87. package/dist/types/components/kit/api-keys.d.ts +62 -0
  88. package/dist/types/components/kit/citations.d.ts +34 -0
  89. package/dist/types/components/kit/context-meter.d.ts +38 -0
  90. package/dist/types/components/kit/model-picker.d.ts +46 -0
  91. package/dist/types/components/kit/prompt-composer.d.ts +61 -0
  92. package/dist/types/components/kit/scrub-input.d.ts +44 -0
  93. package/dist/types/components/kit/thinking.d.ts +28 -0
  94. package/dist/types/components/kit/tool-approval.d.ts +43 -0
  95. package/dist/types/components/kit/trace-waterfall.d.ts +44 -0
  96. package/dist/types/components/lab/blocks/AgentTeam.d.ts +2 -0
  97. package/dist/types/components/lab/blocks/AutonomyDial.d.ts +2 -0
  98. package/dist/types/components/lab/blocks/ChangeLedger.d.ts +2 -0
  99. package/dist/types/components/lab/blocks/FallbackChain.d.ts +2 -0
  100. package/dist/types/packages/asta-ui/src/agent-plan.d.ts +2 -0
  101. package/dist/types/packages/asta-ui/src/agent-team.d.ts +2 -0
  102. package/dist/types/packages/asta-ui/src/api-keys.d.ts +2 -0
  103. package/dist/types/packages/asta-ui/src/autonomy-dial.d.ts +2 -0
  104. package/dist/types/packages/asta-ui/src/base/agent-plan.d.ts +2 -0
  105. package/dist/types/packages/asta-ui/src/base/agent-team.d.ts +2 -0
  106. package/dist/types/packages/asta-ui/src/base/api-keys.d.ts +2 -0
  107. package/dist/types/packages/asta-ui/src/base/autonomy-dial.d.ts +2 -0
  108. package/dist/types/packages/asta-ui/src/base/change-ledger.d.ts +2 -0
  109. package/dist/types/packages/asta-ui/src/base/citations.d.ts +2 -0
  110. package/dist/types/packages/asta-ui/src/base/context-meter.d.ts +2 -0
  111. package/dist/types/packages/asta-ui/src/base/fallback-chain.d.ts +2 -0
  112. package/dist/types/packages/asta-ui/src/base/model-picker.d.ts +2 -0
  113. package/dist/types/packages/asta-ui/src/base/prompt-composer.d.ts +2 -0
  114. package/dist/types/packages/asta-ui/src/base/scrub-input.d.ts +2 -0
  115. package/dist/types/packages/asta-ui/src/base/thinking.d.ts +2 -0
  116. package/dist/types/packages/asta-ui/src/base/tool-approval.d.ts +2 -0
  117. package/dist/types/packages/asta-ui/src/base/trace-waterfall.d.ts +2 -0
  118. package/dist/types/packages/asta-ui/src/base.d.ts +25 -1
  119. package/dist/types/packages/asta-ui/src/change-ledger.d.ts +2 -0
  120. package/dist/types/packages/asta-ui/src/citations.d.ts +2 -0
  121. package/dist/types/packages/asta-ui/src/context-meter.d.ts +2 -0
  122. package/dist/types/packages/asta-ui/src/fallback-chain.d.ts +2 -0
  123. package/dist/types/packages/asta-ui/src/index.d.ts +25 -1
  124. package/dist/types/packages/asta-ui/src/model-picker.d.ts +2 -0
  125. package/dist/types/packages/asta-ui/src/prompt-composer.d.ts +2 -0
  126. package/dist/types/packages/asta-ui/src/scrub-input.d.ts +2 -0
  127. package/dist/types/packages/asta-ui/src/thinking.d.ts +2 -0
  128. package/dist/types/packages/asta-ui/src/tool-approval.d.ts +2 -0
  129. package/dist/types/packages/asta-ui/src/trace-waterfall.d.ts +2 -0
  130. package/package.json +1 -1
package/css/asta.js CHANGED
@@ -439,7 +439,983 @@
439
439
  else boot();
440
440
  document.addEventListener("htmx:afterSettle", (e) => scan(e.detail?.elt?.parentElement || document));
441
441
 
442
- window.asta = { toast, open: (id) => open(byId(id)), close: (id) => close(byId(id)), version: "0.9.4" };
442
+ window.asta = { toast, open: (id) => open(byId(id)), close: (id) => close(byId(id)), version: "0.9.6" };
443
+ })();
444
+
445
+ /* ---- runtime/agent.js ---- */
446
+ /* Agent: elapsed timers and tool approval.
447
+ * Event delegation on document, so markup swapped in by htmx works without re-init.
448
+ * Elapsed [data-asta-elapsed="<epoch ms>"] counts up from that time, or from when it first shows with "now" ("12s", "1m 04s"; inside an agent plan "4.2s"
449
+ * under ten seconds). Rests off screen and in hidden tabs. Remove the attribute to stop it.
450
+ * Tool [data-asta-tool-approval]: [data-asta-decide="deny|once|always"] inside a .asta-tool-approval-card, or
451
+ * Enter (allow once) / Esc (deny) while the card has focus. The card becomes a receipt in
452
+ * .asta-tool-approval-receipts, queued calls to an always-allowed tool follow on their own ("auto"), and
453
+ * "asta:tool-decision" fires with detail { id, tool, decision }. Cancel it to handle the swap yourself.
454
+ */
455
+ (() => {
456
+ if (window.astaAgent) return;
457
+ window.astaAgent = true;
458
+ const el = (e) => (e.target instanceof Element ? e.target : null);
459
+
460
+ /* ---------- Elapsed ---------- */
461
+
462
+ const seen = new WeakSet();
463
+ const onScreen = new Set();
464
+ const io = "IntersectionObserver" in window ? new IntersectionObserver((es) => es.forEach((e) => onScreen[e.isIntersecting ? "add" : "delete"](e.target))) : null;
465
+ const fmt = (ms, tenths) => {
466
+ const s = Math.max(0, ms) / 1000;
467
+ if (tenths && s < 10) return `${s.toFixed(1)}s`;
468
+ if (s < 60) return `${Math.floor(s)}s`;
469
+ return `${Math.floor(s / 60)}m ${String(Math.floor(s % 60)).padStart(2, "0")}s`;
470
+ };
471
+ function paint(node) {
472
+ if (node.getAttribute("data-asta-elapsed") === "now") node.setAttribute("data-asta-elapsed", String(Date.now()));
473
+ const from = Number(node.getAttribute("data-asta-elapsed"));
474
+ if (!Number.isFinite(from) || from <= 0) return;
475
+ const next = fmt(Date.now() - from, !!node.closest(".asta-agent-plan"));
476
+ if (node.textContent !== next) node.textContent = next;
477
+ }
478
+ function scan() {
479
+ document.querySelectorAll("[data-asta-elapsed]").forEach((n) => {
480
+ if (seen.has(n)) return;
481
+ seen.add(n);
482
+ if (io) io.observe(n);
483
+ else onScreen.add(n);
484
+ paint(n);
485
+ });
486
+ onScreen.forEach((n) => {
487
+ if (n.isConnected && n.hasAttribute("data-asta-elapsed")) return paint(n);
488
+ onScreen.delete(n);
489
+ seen.delete(n);
490
+ io?.unobserve(n);
491
+ });
492
+ }
493
+ let timer = 0;
494
+ const run = () => {
495
+ clearInterval(timer);
496
+ if (!document.hidden) timer = setInterval(scan, 500);
497
+ scan();
498
+ };
499
+ document.addEventListener("visibilitychange", run);
500
+
501
+ /* ---------- Tool approval ---------- */
502
+
503
+ const WORD = { deny: "Denied", once: "Allowed", always: "Always allowed", auto: "Auto-allowed" };
504
+ const NS = "http://www.w3.org/2000/svg";
505
+ const PATH = { ok: "m3.5 8.5 3 3 6-7", deny: "M8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12ZM3.8 12.2l8.4-8.4" };
506
+
507
+ function icon(d) {
508
+ const svg = document.createElementNS(NS, "svg");
509
+ svg.setAttribute("viewBox", "0 0 16 16");
510
+ svg.setAttribute("fill", "none");
511
+ svg.setAttribute("stroke", "currentColor");
512
+ svg.setAttribute("stroke-width", "1.8");
513
+ svg.setAttribute("stroke-linecap", "round");
514
+ svg.setAttribute("stroke-linejoin", "round");
515
+ svg.setAttribute("aria-hidden", "true");
516
+ const p = document.createElementNS(NS, "path");
517
+ p.setAttribute("d", d);
518
+ svg.append(p);
519
+ return svg;
520
+ }
521
+
522
+ function receipt(card, decision) {
523
+ const li = document.createElement("li");
524
+ li.className = "asta-tool-approval-receipt";
525
+ li.dataset.decision = decision;
526
+ if (card.dataset.id) li.dataset.id = card.dataset.id;
527
+ const word = document.createElement("b");
528
+ word.textContent = WORD[decision];
529
+ const sep = document.createElement("span");
530
+ sep.className = "asta-tool-approval-receipt-sep";
531
+ sep.setAttribute("aria-hidden", "true");
532
+ sep.textContent = "·";
533
+ const code = document.createElement("code");
534
+ code.textContent = card.dataset.tool || card.querySelector(".asta-tool-approval-tool")?.textContent || "tool";
535
+ li.append(icon(decision === "deny" ? PATH.deny : PATH.ok), word, sep, code);
536
+ const sum = card.querySelector(".asta-tool-approval-summary")?.textContent;
537
+ if (sum) {
538
+ const s = document.createElement("span");
539
+ s.className = "asta-tool-approval-receipt-summary";
540
+ s.textContent = sum;
541
+ li.append(s);
542
+ }
543
+ return li;
544
+ }
545
+
546
+ // Queue look and "n of total" labels.
547
+ function sync(root) {
548
+ const queue = root.querySelector(".asta-tool-approval-queue");
549
+ const cards = queue ? [...queue.querySelectorAll(":scope > .asta-tool-approval-card")] : [];
550
+ const done = root.querySelectorAll(".asta-tool-approval-receipt").length;
551
+ const total = done + cards.length;
552
+ if (queue) {
553
+ if (cards.length > 1) queue.setAttribute("data-more", String(Math.min(2, cards.length - 1)));
554
+ else queue.removeAttribute("data-more");
555
+ }
556
+ cards.forEach((c, i) => {
557
+ const n = c.querySelector(".asta-tool-approval-count");
558
+ if (n) n.textContent = total > 1 ? `${done + i + 1} of ${total}` : "";
559
+ if (n) n.hidden = total < 2;
560
+ if (i === 0 && total > 1) c.setAttribute("aria-label", `Approve ${c.dataset.tool || "tool"}, ${done + 1} of ${total}`);
561
+ });
562
+ }
563
+
564
+ function decide(card, decision) {
565
+ const root = card.closest("[data-asta-tool-approval]");
566
+ if (!root || !card.isConnected) return;
567
+ const detail = { id: card.dataset.id, tool: card.dataset.tool, decision };
568
+ if (!card.dispatchEvent(new CustomEvent("asta:tool-decision", { bubbles: true, cancelable: true, detail }))) return;
569
+ const refocus = card.contains(document.activeElement);
570
+ let list = root.querySelector(".asta-tool-approval-receipts");
571
+ if (!list) {
572
+ list = document.createElement("ul");
573
+ list.className = "asta-tool-approval-receipts";
574
+ list.setAttribute("aria-label", "Tool calls");
575
+ root.prepend(list);
576
+ }
577
+ list.append(receipt(card, decision));
578
+ card.remove();
579
+ if (decision === "always" && card.dataset.tool) {
580
+ root.querySelectorAll(`.asta-tool-approval-card[data-tool="${CSS.escape(card.dataset.tool)}"]`).forEach((c) => decide(c, "auto"));
581
+ }
582
+ sync(root);
583
+ if (refocus) {
584
+ const next = root.querySelector(".asta-tool-approval-queue > .asta-tool-approval-card");
585
+ if (!next) list.tabIndex = -1;
586
+ (next || list).focus({ preventScroll: true });
587
+ }
588
+ }
589
+
590
+ document.addEventListener("click", (e) => {
591
+ const b = el(e)?.closest("[data-asta-decide]");
592
+ const card = b?.closest(".asta-tool-approval-card");
593
+ if (!card || b.disabled) return;
594
+ decide(card, b.getAttribute("data-asta-decide"));
595
+ });
596
+
597
+ document.addEventListener("keydown", (e) => {
598
+ if (e.defaultPrevented || e.isComposing) return;
599
+ const t = el(e);
600
+ const card = t?.closest(".asta-tool-approval-card");
601
+ if (!card || t.closest("[data-asta-mpanel]")) return;
602
+ if (e.key === "Escape") {
603
+ e.preventDefault();
604
+ decide(card, "deny");
605
+ } else if (e.key === "Enter" && !t.closest("button,a,input,textarea,select,summary")) {
606
+ e.preventDefault();
607
+ decide(card, "once");
608
+ }
609
+ });
610
+
611
+ const init = () => {
612
+ run();
613
+ document.querySelectorAll("[data-asta-tool-approval]").forEach(sync);
614
+ };
615
+ document.addEventListener("htmx:load", () => document.querySelectorAll("[data-asta-tool-approval]").forEach(sync));
616
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init, { once: true });
617
+ else init();
618
+ })();
619
+
620
+ /* ---- runtime/assist.js ---- */
621
+ /* Assist: model picker, citations, trace waterfall, prompt composer.
622
+ * Event delegation on document, so markup swapped in by htmx works without re-init.
623
+ * Model [data-asta-model]: the trigger opens a listbox, [data-asta-model-search] filters it, arrows/Home/End move,
624
+ * Enter picks, Esc closes, typing on the closed trigger searches. Picking updates
625
+ * [data-asta-model-value], the trigger label/tag and fires "asta:model-change" with detail.value
626
+ * Citations [data-asta-cite]: a pill shows its card on hover, focus or tap. Hovering a source lights its pills
627
+ * (data-lit) and the other way round. [data-asta-cite-toggle] expands the source list (data-expanded)
628
+ * Trace [data-asta-trace]: [data-asta-trace-toggle] or ←/→ folds a span, ↑/↓/Home/End move, a click or
629
+ * Enter selects it and copies <template data-asta-trace-for="id"> into [data-asta-trace-detail].
630
+ * Fires "asta:trace-select" with detail.id
631
+ * Prompt [data-asta-prompt]: @ and / open [data-asta-prompt-menu], a pick becomes an atomic chip that one
632
+ * Backspace removes. Enter sends, Shift+Enter adds a line. Fills [data-asta-prompt-value] and
633
+ * [data-asta-prompt-refs], lists attached files, sets data-running during an htmx request.
634
+ * Fires "asta:prompt-send" (detail { text, refs, files }) and "asta:prompt-stop"
635
+ */
636
+ (() => {
637
+ if (window.astaAssist) return;
638
+ window.astaAssist = true;
639
+ const el = (e) => (e.target instanceof Element ? e.target : null);
640
+ const fire = (node, name, detail) => node.dispatchEvent(new CustomEvent(name, { bubbles: true, detail }));
641
+ const shown = (n) => !n.hidden && !n.closest("[hidden]");
642
+ let uid = 0;
643
+ const idOf = (n, p) => n.id || (n.id = `${p}-${++uid}`);
644
+
645
+ /* Loops (composer orbit, running spans) rest off screen and while the tab is hidden. */
646
+ const io =
647
+ "IntersectionObserver" in window
648
+ ? new IntersectionObserver((es) => es.forEach((e) => e.target.toggleAttribute("data-offscreen", !e.isIntersecting)))
649
+ : null;
650
+ const watched = new Set();
651
+ function watch(root) {
652
+ if (!io || watched.has(root)) return;
653
+ watched.add(root);
654
+ io.observe(root);
655
+ }
656
+ function scan(scope = document) {
657
+ scope.querySelectorAll?.("[data-asta-prompt], [data-asta-trace]").forEach(watch);
658
+ scope.querySelectorAll?.(".asta-trace-bar:not([data-seen])").forEach((b) => {
659
+ b.setAttribute("data-seen", "");
660
+ const x = parseFloat(b.style.getPropertyValue("--x")) || 0;
661
+ if (!b.style.animationDelay) b.style.animationDelay = `${Math.round(x * 5)}ms`;
662
+ });
663
+ scope.querySelectorAll?.("[data-asta-prompt]").forEach(syncPrompt);
664
+ watched.forEach((r) => {
665
+ if (r.isConnected) return;
666
+ io?.unobserve(r);
667
+ watched.delete(r);
668
+ });
669
+ }
670
+ document.addEventListener("visibilitychange", () => watched.forEach((r) => r.toggleAttribute("data-paused", document.hidden)));
671
+ window.addEventListener("pagehide", () => io?.disconnect(), { once: true });
672
+
673
+ /* ---------- Model picker ---------- */
674
+
675
+ const mpOptions = (mp) => [...mp.querySelectorAll('[role="option"]')].filter(shown);
676
+ const mpUsable = (mp) => mpOptions(mp).filter((o) => o.getAttribute("aria-disabled") !== "true");
677
+ function mpPlace(mp, animate) {
678
+ const list = mp.querySelector('[role="listbox"]');
679
+ const act = mp.querySelector('[role="option"][data-active]');
680
+ const sel = mp.querySelector('[role="option"][aria-selected="true"]');
681
+ const ease = animate ? "transform .32s cubic-bezier(.16,1,.3,1), opacity .2s" : "none";
682
+ const mark = mp.querySelector(".asta-model-picker-mark");
683
+ const bar = mp.querySelector(".asta-model-picker-bar");
684
+ if (mark) {
685
+ mark.style.transition = ease;
686
+ mark.style.opacity = act && shown(act) ? "1" : "0";
687
+ if (act) mark.style.transform = `translateY(${act.offsetTop}px)`;
688
+ }
689
+ if (bar) {
690
+ bar.style.transition = ease;
691
+ bar.style.opacity = sel && shown(sel) ? "1" : "0";
692
+ if (sel) bar.style.transform = `translateY(${sel.offsetTop + (sel.offsetHeight - bar.offsetHeight) / 2}px)`;
693
+ }
694
+ if (act && list && animate !== null) {
695
+ const top = act.offsetTop;
696
+ if (top < list.scrollTop) list.scrollTop = top - 32;
697
+ else if (top + act.offsetHeight > list.scrollTop + list.clientHeight) list.scrollTop = top + act.offsetHeight - list.clientHeight + 6;
698
+ }
699
+ }
700
+ function mpActivate(mp, opt, animate = true) {
701
+ mp.querySelectorAll('[role="option"][data-active]').forEach((o) => o.removeAttribute("data-active"));
702
+ const owner = mp.querySelector("[data-asta-model-search]") || mp.querySelector('[role="listbox"]');
703
+ if (opt) {
704
+ opt.setAttribute("data-active", "");
705
+ owner?.setAttribute("aria-activedescendant", idOf(opt, "asta-mp"));
706
+ } else owner?.removeAttribute("aria-activedescendant");
707
+ mpPlace(mp, animate);
708
+ }
709
+ function mpFilter(mp, q) {
710
+ q = q.trim().toLowerCase();
711
+ mp.querySelectorAll('[role="option"]').forEach((o) => {
712
+ const hay = `${o.dataset.label || o.textContent} ${o.closest('[role="group"]')?.querySelector(".asta-model-picker-group")?.textContent || ""}`.toLowerCase();
713
+ o.hidden = !!q && !hay.includes(q);
714
+ });
715
+ mp.querySelectorAll('[role="listbox"] [role="group"]').forEach((g) => (g.hidden = !g.querySelector('[role="option"]:not([hidden])')));
716
+ const empty = mp.querySelector("[data-asta-model-empty]");
717
+ if (empty) {
718
+ empty.hidden = mpOptions(mp).length > 0;
719
+ const echo = empty.querySelector("[data-asta-model-query]");
720
+ if (echo) echo.textContent = q;
721
+ }
722
+ mpActivate(mp, mpUsable(mp)[0] || null, false);
723
+ }
724
+ function mpOpen(mp, seed) {
725
+ const trigger = mp.querySelector("[data-asta-model-trigger]");
726
+ const panel = mp.querySelector(".asta-model-picker-panel");
727
+ if (!panel || trigger?.disabled) return;
728
+ document.querySelectorAll('[data-asta-model] [aria-expanded="true"][data-asta-model-trigger]').forEach((t) => t !== trigger && mpClose(t.closest("[data-asta-model]")));
729
+ panel.hidden = false;
730
+ trigger?.setAttribute("aria-expanded", "true");
731
+ // Keep the popup inside the viewport with a 16px gutter.
732
+ panel.style.translate = "";
733
+ const r = panel.getBoundingClientRect();
734
+ const dx = r.left < 16 ? 16 - r.left : r.right > innerWidth - 16 ? innerWidth - 16 - r.right : 0;
735
+ if (dx) panel.style.translate = `${Math.round(dx)}px 0`;
736
+ const search = mp.querySelector("[data-asta-model-search]");
737
+ if (search) {
738
+ search.value = seed || "";
739
+ mpFilter(mp, search.value);
740
+ search.focus();
741
+ } else mp.querySelector('[role="listbox"]')?.focus();
742
+ if (!seed) mpActivate(mp, mp.querySelector('[role="option"][aria-selected="true"]:not([aria-disabled="true"])') || mpUsable(mp)[0] || null, false);
743
+ }
744
+ function mpClose(mp, refocus) {
745
+ if (!mp) return;
746
+ const panel = mp.querySelector(".asta-model-picker-panel");
747
+ const trigger = mp.querySelector("[data-asta-model-trigger]");
748
+ if (panel) panel.hidden = true;
749
+ trigger?.setAttribute("aria-expanded", "false");
750
+ if (refocus) trigger?.focus();
751
+ }
752
+ function mpPick(mp, opt) {
753
+ if (!opt || opt.getAttribute("aria-disabled") === "true") return;
754
+ mp.querySelectorAll('[role="option"]').forEach((o) => o.setAttribute("aria-selected", String(o === opt)));
755
+ const value = opt.dataset.value || "";
756
+ const input = mp.querySelector("[data-asta-model-value]");
757
+ if (input) input.value = value;
758
+ const label = mp.querySelector("[data-asta-model-label]");
759
+ if (label) label.textContent = opt.dataset.label || value;
760
+ const tag = mp.querySelector("[data-asta-model-tag]");
761
+ if (tag) {
762
+ tag.textContent = opt.dataset.tag || "";
763
+ tag.hidden = !opt.dataset.tag;
764
+ }
765
+ mpPlace(mp, true);
766
+ setTimeout(() => mpClose(mp, true), 120);
767
+ fire(mp, "asta:model-change", { value });
768
+ }
769
+ document.addEventListener("click", (e) => {
770
+ const t = el(e);
771
+ const mp = t?.closest("[data-asta-model]");
772
+ if (!mp) return;
773
+ if (t.closest("[data-asta-model-trigger]")) {
774
+ const open = mp.querySelector("[data-asta-model-trigger]").getAttribute("aria-expanded") === "true";
775
+ if (open) mpClose(mp);
776
+ else mpOpen(mp);
777
+ return;
778
+ }
779
+ const opt = t.closest('[role="option"]');
780
+ if (opt && mp.contains(opt)) mpPick(mp, opt);
781
+ });
782
+ document.addEventListener("pointermove", (e) => {
783
+ const opt = el(e)?.closest('[data-asta-model] [role="option"]');
784
+ if (!opt || opt.hasAttribute("data-active") || opt.getAttribute("aria-disabled") === "true") return;
785
+ mpActivate(opt.closest("[data-asta-model]"), opt, null);
786
+ });
787
+ document.addEventListener("input", (e) => {
788
+ const s = el(e)?.closest("[data-asta-model-search]");
789
+ if (s) mpFilter(s.closest("[data-asta-model]"), s.value);
790
+ });
791
+ let mpBuf = "";
792
+ let mpBufT = 0;
793
+ document.addEventListener("keydown", (e) => {
794
+ const t = el(e);
795
+ const mp = t?.closest("[data-asta-model]");
796
+ if (!mp) return;
797
+ const trigger = t.closest("[data-asta-model-trigger]");
798
+ const open = mp.querySelector("[data-asta-model-trigger]")?.getAttribute("aria-expanded") === "true";
799
+ if (trigger && !open) {
800
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
801
+ e.preventDefault();
802
+ mpOpen(mp);
803
+ } else if (e.key.length === 1 && /\S/.test(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) {
804
+ e.preventDefault();
805
+ if (mp.querySelector("[data-asta-model-search]")) mpOpen(mp, e.key);
806
+ else {
807
+ clearTimeout(mpBufT);
808
+ mpBuf += e.key.toLowerCase();
809
+ mpBufT = setTimeout(() => (mpBuf = ""), 700);
810
+ mpOpen(mp);
811
+ mpActivate(mp, mpUsable(mp).find((o) => (o.dataset.label || "").toLowerCase().startsWith(mpBuf)) || null);
812
+ }
813
+ }
814
+ return;
815
+ }
816
+ if (!open) return;
817
+ const items = mpUsable(mp);
818
+ const cur = items.indexOf(mp.querySelector('[role="option"][data-active]'));
819
+ const inSearch = !!t.closest("[data-asta-model-search]");
820
+ const go = (i) => {
821
+ e.preventDefault();
822
+ if (items.length) mpActivate(mp, items[(i + items.length) % items.length]);
823
+ };
824
+ if (e.key === "ArrowDown") go(cur + 1);
825
+ else if (e.key === "ArrowUp") go(cur < 0 ? items.length - 1 : cur - 1);
826
+ else if (e.key === "Home" && !inSearch) go(0);
827
+ else if (e.key === "End" && !inSearch) go(items.length - 1);
828
+ else if (e.key === "Enter") {
829
+ e.preventDefault();
830
+ mpPick(mp, items[cur]);
831
+ } else if (e.key === "Escape") {
832
+ e.preventDefault();
833
+ mpClose(mp, true);
834
+ } else if (e.key === "Tab") mpClose(mp);
835
+ });
836
+ document.addEventListener("pointerdown", (e) => {
837
+ const t = el(e);
838
+ document.querySelectorAll('[data-asta-model-trigger][aria-expanded="true"]').forEach((tr) => {
839
+ const mp = tr.closest("[data-asta-model]");
840
+ if (!mp.contains(t)) mpClose(mp);
841
+ });
842
+ hideCards(t);
843
+ });
844
+
845
+ /* ---------- Citations ---------- */
846
+
847
+ let cardT = 0;
848
+ const cardOf = (pill) => pill.parentElement?.querySelector(".asta-citations-card");
849
+ function showCard(pill) {
850
+ const card = cardOf(pill);
851
+ if (!card) return;
852
+ pill.closest("[data-asta-cite]")?.querySelectorAll(".asta-citations-pill[aria-expanded='true']").forEach((p) => p !== pill && hideCard(p));
853
+ const r = pill.getBoundingClientRect();
854
+ card.toggleAttribute("data-below", r.top < 220);
855
+ card.style.left = "";
856
+ card.hidden = false;
857
+ pill.setAttribute("aria-expanded", "true");
858
+ pill.setAttribute("aria-describedby", idOf(card, "asta-cite"));
859
+ // Keep the card inside the viewport with a 16px gutter.
860
+ const c = card.getBoundingClientRect();
861
+ const shift = c.left < 16 ? 16 - c.left : c.right > innerWidth - 16 ? innerWidth - 16 - c.right : 0;
862
+ if (shift) card.style.left = `calc(50% + ${Math.round(shift)}px)`;
863
+ }
864
+ function hideCard(pill) {
865
+ const card = cardOf(pill);
866
+ if (card) card.hidden = true;
867
+ pill.setAttribute("aria-expanded", "false");
868
+ pill.removeAttribute("data-pinned");
869
+ }
870
+ function hideCards(except) {
871
+ document.querySelectorAll(".asta-citations-pill[aria-expanded='true']").forEach((p) => !p.parentElement.contains(except) && hideCard(p));
872
+ }
873
+ function light(root, src, on) {
874
+ root.querySelectorAll(`[data-src]`).forEach((n) => {
875
+ const ids = (n.dataset.src || "").split(/\s*,\s*/);
876
+ n.toggleAttribute("data-lit", on && ids.includes(src));
877
+ });
878
+ }
879
+ document.addEventListener("pointerover", (e) => {
880
+ const t = el(e);
881
+ const root = t?.closest("[data-asta-cite]");
882
+ if (!root) return;
883
+ const pill = t.closest(".asta-citations-pill");
884
+ const cite = t.closest(".asta-citations-cite");
885
+ const source = t.closest(".asta-citations-source[data-src]");
886
+ if (cite) clearTimeout(cardT);
887
+ if (pill && e.pointerType === "mouse" && pill.getAttribute("aria-expanded") !== "true") {
888
+ cardT = setTimeout(() => showCard(pill), 90);
889
+ }
890
+ if (pill) light(root, pill.dataset.src, true);
891
+ else if (source) light(root, source.dataset.src, true);
892
+ });
893
+ document.addEventListener("pointerout", (e) => {
894
+ const t = el(e);
895
+ const root = t?.closest("[data-asta-cite]");
896
+ if (!root) return;
897
+ const to = e.relatedTarget instanceof Element ? e.relatedTarget : null;
898
+ const cite = t.closest(".asta-citations-cite");
899
+ if (cite && !cite.contains(to)) {
900
+ clearTimeout(cardT);
901
+ const pill = cite.querySelector(".asta-citations-pill");
902
+ if (pill && !pill.hasAttribute("data-pinned") && e.pointerType === "mouse") cardT = setTimeout(() => hideCard(pill), 140);
903
+ }
904
+ if ((t.closest(".asta-citations-pill") || t.closest(".asta-citations-source")) && !to?.closest(".asta-citations-pill, .asta-citations-source")) light(root, "", false);
905
+ });
906
+ document.addEventListener("focusin", (e) => {
907
+ const t = el(e);
908
+ const root = t?.closest("[data-asta-cite]");
909
+ if (!root) return;
910
+ const pill = t.closest(".asta-citations-pill");
911
+ const source = t.closest(".asta-citations-source[data-src]");
912
+ if (pill && pill.matches(":focus-visible")) showCard(pill);
913
+ if (pill || source) light(root, (pill || source).dataset.src, true);
914
+ });
915
+ document.addEventListener("focusout", (e) => {
916
+ const t = el(e);
917
+ const root = t?.closest("[data-asta-cite]");
918
+ if (!root) return;
919
+ const to = e.relatedTarget instanceof Element ? e.relatedTarget : null;
920
+ const pill = t.closest(".asta-citations-pill");
921
+ if (pill && !pill.hasAttribute("data-pinned") && !pill.parentElement.contains(to)) hideCard(pill);
922
+ if (!to?.closest(".asta-citations-pill, .asta-citations-source")) light(root, "", false);
923
+ });
924
+ document.addEventListener("click", (e) => {
925
+ const t = el(e);
926
+ const root = t?.closest("[data-asta-cite]");
927
+ if (!root) return;
928
+ const pill = t.closest(".asta-citations-pill");
929
+ if (pill) {
930
+ // Tap or click pins the card (touch has no hover); a second click closes it.
931
+ if (pill.hasAttribute("data-pinned")) hideCard(pill);
932
+ else {
933
+ showCard(pill);
934
+ pill.setAttribute("data-pinned", "");
935
+ }
936
+ return;
937
+ }
938
+ const toggle = t.closest("[data-asta-cite-toggle]");
939
+ if (!toggle) return;
940
+ const open = !root.hasAttribute("data-expanded");
941
+ root.toggleAttribute("data-expanded", open);
942
+ root.querySelectorAll("[data-extra]").forEach((n) => (n.hidden = !open));
943
+ root.querySelectorAll("[data-asta-cite-toggle]").forEach((b) => {
944
+ b.setAttribute("aria-expanded", String(open));
945
+ const label = b.querySelector("[data-label]");
946
+ const text = open ? b.dataset.less : b.dataset.more;
947
+ if (label && text) label.textContent = text;
948
+ });
949
+ if (toggle.closest(".asta-citations-more")) root.querySelector(".asta-citations-toggle")?.focus();
950
+ });
951
+
952
+ /* ---------- Trace waterfall ---------- */
953
+
954
+ const rowsOf = (tr) => [...tr.querySelectorAll('[role="row"][data-id]')];
955
+ function descendants(tr, id) {
956
+ const out = [];
957
+ const walk = (pid) =>
958
+ rowsOf(tr).forEach((r) => {
959
+ if (r.dataset.parent !== pid) return;
960
+ out.push(r);
961
+ walk(r.dataset.id);
962
+ });
963
+ walk(id);
964
+ return out;
965
+ }
966
+ function fold(tr, row, open) {
967
+ if (!row.hasAttribute("aria-expanded")) return;
968
+ row.setAttribute("aria-expanded", String(open));
969
+ descendants(tr, row.dataset.id).forEach((r) => {
970
+ // A row shows when every ancestor is expanded.
971
+ let p = tr.querySelector(`[role="row"][data-id="${CSS.escape(r.dataset.parent || "")}"]`);
972
+ let vis = true;
973
+ while (p) {
974
+ if (p.getAttribute("aria-expanded") === "false") vis = false;
975
+ p = p.dataset.parent ? tr.querySelector(`[role="row"][data-id="${CSS.escape(p.dataset.parent)}"]`) : null;
976
+ }
977
+ r.hidden = !vis;
978
+ });
979
+ }
980
+ function focusRow(tr, row) {
981
+ if (!row) return;
982
+ rowsOf(tr).forEach((r) => (r.tabIndex = r === row ? 0 : -1));
983
+ row.focus({ preventScroll: false });
984
+ }
985
+ function select(tr, row) {
986
+ rowsOf(tr).forEach((r) => r.setAttribute("aria-selected", String(r === row)));
987
+ const detail = tr.querySelector("[data-asta-trace-detail]");
988
+ const tpl = row && tr.querySelector(`template[data-asta-trace-for="${CSS.escape(row.dataset.id)}"]`);
989
+ if (detail) {
990
+ if (tpl) detail.replaceChildren(tpl.content.cloneNode(true));
991
+ detail.hidden = !row || !tpl;
992
+ if (!detail.hidden) {
993
+ detail.removeAttribute("data-fresh");
994
+ void detail.offsetWidth;
995
+ detail.setAttribute("data-fresh", "");
996
+ }
997
+ }
998
+ if (row) fire(tr, "asta:trace-select", { id: row.dataset.id });
999
+ }
1000
+ document.addEventListener("click", (e) => {
1001
+ const t = el(e);
1002
+ const tr = t?.closest("[data-asta-trace]");
1003
+ if (!tr) return;
1004
+ if (t.closest("[data-asta-trace-close]")) {
1005
+ const sel = tr.querySelector('[role="row"][aria-selected="true"]');
1006
+ select(tr, null);
1007
+ focusRow(tr, sel);
1008
+ return;
1009
+ }
1010
+ const row = t.closest('[role="row"][data-id]');
1011
+ if (!row) return;
1012
+ if (t.closest("[data-asta-trace-toggle]")) {
1013
+ fold(tr, row, row.getAttribute("aria-expanded") === "false");
1014
+ focusRow(tr, row);
1015
+ return;
1016
+ }
1017
+ focusRow(tr, row);
1018
+ select(tr, row);
1019
+ });
1020
+ document.addEventListener("keydown", (e) => {
1021
+ const t = el(e);
1022
+ const tr = t?.closest("[data-asta-trace]");
1023
+ if (!tr) return;
1024
+ if (e.key === "Escape" && tr.querySelector("[data-asta-trace-detail]:not([hidden])")) {
1025
+ const sel = tr.querySelector('[role="row"][aria-selected="true"]');
1026
+ select(tr, null);
1027
+ focusRow(tr, sel);
1028
+ return;
1029
+ }
1030
+ const row = t.closest('[role="row"][data-id]');
1031
+ if (!row || t !== row) return;
1032
+ const vis = rowsOf(tr).filter((r) => !r.hidden);
1033
+ const i = vis.indexOf(row);
1034
+ const parent = row.dataset.parent && tr.querySelector(`[role="row"][data-id="${CSS.escape(row.dataset.parent)}"]`);
1035
+ const keys = {
1036
+ ArrowDown: () => focusRow(tr, vis[i + 1]),
1037
+ ArrowUp: () => focusRow(tr, vis[i - 1]),
1038
+ Home: () => focusRow(tr, vis[0]),
1039
+ End: () => focusRow(tr, vis[vis.length - 1]),
1040
+ ArrowRight: () => (row.getAttribute("aria-expanded") === "false" ? fold(tr, row, true) : row.hasAttribute("aria-expanded") && focusRow(tr, vis[i + 1])),
1041
+ ArrowLeft: () => (row.getAttribute("aria-expanded") === "true" ? fold(tr, row, false) : focusRow(tr, parent)),
1042
+ Enter: () => select(tr, row),
1043
+ " ": () => select(tr, row),
1044
+ };
1045
+ if (!keys[e.key]) return;
1046
+ e.preventDefault();
1047
+ keys[e.key]();
1048
+ });
1049
+
1050
+ /* ---------- Prompt composer ---------- */
1051
+
1052
+ const PERSON =
1053
+ '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 8a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM3.5 13.5c.6-2.2 2.3-3.5 4.5-3.5s3.9 1.3 4.5 3.5"/></svg>';
1054
+ const TRIG = /(?:^|\s)([@/])([^\s@/]{0,30})$/;
1055
+ const trig = new WeakMap();
1056
+ const dismissed = new WeakMap();
1057
+ const parts = (pc) => pc.querySelector("[data-asta-prompt-field]");
1058
+ const openMenu = (pc) => pc.querySelector("[data-asta-prompt-menu]:not([hidden])");
1059
+ const caretNode = () => {
1060
+ const sel = getSelection();
1061
+ return sel && sel.rangeCount && sel.isCollapsed ? sel.getRangeAt(0) : null;
1062
+ };
1063
+ function read(field) {
1064
+ let text = "";
1065
+ const refs = [];
1066
+ const walk = (n) =>
1067
+ n.childNodes.forEach((c) => {
1068
+ if (c.nodeType === 3) text += c.nodeValue;
1069
+ else if (c.nodeType === 1 && c.dataset.token) {
1070
+ text += `${c.dataset.token}${c.dataset.label}`;
1071
+ refs.push({ type: c.dataset.token === "/" ? "command" : "mention", id: c.dataset.id, label: c.dataset.label });
1072
+ } else if (c.nodeName === "BR") text += "\n";
1073
+ else if (c.nodeType === 1) {
1074
+ if (c.nodeName === "DIV" && text && !text.endsWith("\n")) text += "\n";
1075
+ walk(c);
1076
+ }
1077
+ });
1078
+ walk(field);
1079
+ return { text: text.replace(/ /g, " "), refs };
1080
+ }
1081
+ function syncPrompt(pc) {
1082
+ const field = parts(pc);
1083
+ if (!field) return;
1084
+ const { text, refs } = read(field);
1085
+ const value = pc.querySelector("[data-asta-prompt-value]");
1086
+ if (value) value.value = text.trim();
1087
+ const refInput = pc.querySelector("[data-asta-prompt-refs]");
1088
+ if (refInput) refInput.value = JSON.stringify(refs);
1089
+ const files = pc.querySelector("[data-asta-prompt-input]")?.files?.length || 0;
1090
+ const filled = !!text.trim() || refs.length > 0;
1091
+ pc.toggleAttribute("data-filled", filled || field.textContent.length > 0 || refs.length > 0);
1092
+ const send = pc.querySelector(".asta-prompt-send");
1093
+ if (send) send.disabled = (!filled && !files) || pc.querySelector("[data-asta-prompt-field]").getAttribute("aria-disabled") === "true";
1094
+ }
1095
+ function closeMenu(pc) {
1096
+ pc.querySelectorAll("[data-asta-prompt-menu]").forEach((m) => (m.hidden = true));
1097
+ const field = parts(pc);
1098
+ field?.setAttribute("aria-expanded", "false");
1099
+ field?.removeAttribute("aria-activedescendant");
1100
+ trig.delete(pc);
1101
+ }
1102
+ function menuItems(menu) {
1103
+ return [...menu.querySelectorAll('[role="option"]')].filter((o) => !o.hidden);
1104
+ }
1105
+ function setActive(pc, menu, opt) {
1106
+ menu.querySelectorAll('[role="option"]').forEach((o) => o.setAttribute("aria-selected", String(o === opt)));
1107
+ const field = parts(pc);
1108
+ if (opt) {
1109
+ field.setAttribute("aria-activedescendant", idOf(opt, "asta-pc"));
1110
+ opt.scrollIntoView({ block: "nearest" });
1111
+ } else field.removeAttribute("aria-activedescendant");
1112
+ }
1113
+ function detect(pc) {
1114
+ const r = caretNode();
1115
+ const field = parts(pc);
1116
+ if (!r || !field.contains(r.startContainer) || r.startContainer.nodeType !== 3) return closeMenu(pc);
1117
+ const before = r.startContainer.nodeValue.slice(0, r.startOffset);
1118
+ const m = TRIG.exec(before);
1119
+ const menu = m && pc.querySelector(`[data-asta-prompt-menu="${m[1]}"]`);
1120
+ if (!m || !menu) return closeMenu(pc);
1121
+ const start = r.startOffset - m[2].length - 1;
1122
+ const key = `${m[1]}@${start}`;
1123
+ if (dismissed.get(pc) === key) return;
1124
+ trig.set(pc, { node: r.startContainer, start, end: r.startOffset });
1125
+ pc.querySelectorAll("[data-asta-prompt-menu]").forEach((x) => x !== menu && (x.hidden = true));
1126
+ const q = m[2].toLowerCase();
1127
+ menu.querySelectorAll('[role="option"]').forEach((o) => (o.hidden = !(o.dataset.label || "").toLowerCase().includes(q)));
1128
+ // A group label shows only while one of its options does.
1129
+ menu.querySelectorAll(".asta-prompt-group").forEach((g) => {
1130
+ let n = g.nextElementSibling;
1131
+ let any = false;
1132
+ while (n && !n.classList.contains("asta-prompt-group")) {
1133
+ if (n.getAttribute("role") === "option" && !n.hidden) any = true;
1134
+ n = n.nextElementSibling;
1135
+ }
1136
+ g.hidden = !any;
1137
+ });
1138
+ const empty = menu.querySelector(".asta-prompt-empty");
1139
+ if (empty) empty.hidden = menuItems(menu).length > 0;
1140
+ const wasHidden = menu.hidden;
1141
+ menu.hidden = false;
1142
+ // Sit the menu near the trigger, inside the composer.
1143
+ const rr = document.createRange();
1144
+ rr.setStart(r.startContainer, start);
1145
+ rr.setEnd(r.startContainer, start + 1);
1146
+ const box = pc.getBoundingClientRect();
1147
+ const x = Math.max(0, Math.min(rr.getBoundingClientRect().left - box.left - 12, box.width - menu.offsetWidth));
1148
+ menu.style.left = `${Math.round(x)}px`;
1149
+ field.setAttribute("aria-expanded", "true");
1150
+ field.setAttribute("aria-controls", idOf(menu, "asta-pc-menu"));
1151
+ const cur = menu.querySelector('[role="option"][aria-selected="true"]:not([hidden])');
1152
+ setActive(pc, menu, wasHidden || !cur ? menuItems(menu)[0] || null : cur);
1153
+ }
1154
+ function insert(pc, opt) {
1155
+ const at = trig.get(pc);
1156
+ const field = parts(pc);
1157
+ const menu = opt.closest("[data-asta-prompt-menu]");
1158
+ if (!at || !field.contains(at.node)) return;
1159
+ const range = document.createRange();
1160
+ range.setStart(at.node, at.start);
1161
+ range.setEnd(at.node, Math.min(at.end, at.node.nodeValue.length));
1162
+ range.deleteContents();
1163
+ const token = menu.getAttribute("data-asta-prompt-menu");
1164
+ const chip = document.createElement("span");
1165
+ chip.contentEditable = "false";
1166
+ chip.className = `asta-prompt-chip${token === "/" ? " asta-prompt-chip-command" : ""}`;
1167
+ chip.dataset.token = token;
1168
+ chip.dataset.id = opt.dataset.id || opt.dataset.label;
1169
+ chip.dataset.label = opt.dataset.label || "";
1170
+ chip.textContent = chip.dataset.label;
1171
+ const glyph = opt.querySelector(".asta-prompt-option-icon svg");
1172
+ if (glyph) chip.prepend(glyph.cloneNode(true));
1173
+ else if (opt.dataset.type === "person") chip.insertAdjacentHTML("afterbegin", PERSON);
1174
+ const space = document.createTextNode(" ");
1175
+ range.insertNode(space);
1176
+ range.insertNode(chip);
1177
+ const sel = getSelection();
1178
+ const after = document.createRange();
1179
+ after.setStart(space, 1);
1180
+ after.collapse(true);
1181
+ sel.removeAllRanges();
1182
+ sel.addRange(after);
1183
+ closeMenu(pc);
1184
+ syncPrompt(pc);
1185
+ field.focus();
1186
+ }
1187
+ function nextToken(dir) {
1188
+ const r = caretNode();
1189
+ if (!r) return null;
1190
+ const { startContainer: n, startOffset: o } = r;
1191
+ if (n.nodeType === 3) {
1192
+ if (dir < 0 && o === 0) return n.previousSibling?.dataset?.token ? n.previousSibling : null;
1193
+ if (dir > 0 && o === n.nodeValue.length) return n.nextSibling?.dataset?.token ? n.nextSibling : null;
1194
+ return null;
1195
+ }
1196
+ const c = n.childNodes[dir < 0 ? o - 1 : o];
1197
+ return c?.dataset?.token ? c : null;
1198
+ }
1199
+ function fmt(b) {
1200
+ return b < 1024 ? `${b} B` : b < 1048576 ? `${Math.round(b / 1024)} KB` : `${(b / 1048576).toFixed(1)} MB`;
1201
+ }
1202
+ function note(pc, msg, error) {
1203
+ const n = pc.querySelector("[data-asta-prompt-note]");
1204
+ if (!n) return;
1205
+ if (!n.dataset.idle) n.dataset.idle = n.innerHTML;
1206
+ n.toggleAttribute("data-error", !!error);
1207
+ n.setAttribute("role", error ? "alert" : "status");
1208
+ if (msg) n.textContent = msg;
1209
+ else n.innerHTML = n.dataset.idle;
1210
+ }
1211
+ function renderFiles(pc) {
1212
+ const input = pc.querySelector("[data-asta-prompt-input]");
1213
+ const list = pc.querySelector("[data-asta-prompt-files]");
1214
+ if (!input || !list) return;
1215
+ list.replaceChildren(
1216
+ ...[...input.files].map((f, i) => {
1217
+ const li = document.createElement("li");
1218
+ li.className = "asta-prompt-file";
1219
+ li.innerHTML =
1220
+ '<span class="asta-prompt-file-icon"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M9 1.5H4.5a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h7a1 1 0 0 0 1-1V5L9 1.5Z"/><path d="M9 1.5V5h3.5"/></svg></span><span class="asta-prompt-file-name"></span><span class="asta-prompt-file-size"></span><button type="button" class="asta-prompt-file-remove"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true"><path d="m4 4 8 8M12 4l-8 8"/></svg></button>';
1221
+ li.querySelector(".asta-prompt-file-name").textContent = f.name;
1222
+ li.querySelector(".asta-prompt-file-size").textContent = fmt(f.size);
1223
+ const rm = li.querySelector("button");
1224
+ rm.setAttribute("aria-label", `Remove ${f.name}`);
1225
+ rm.dataset.astaPromptRemove = String(i);
1226
+ return li;
1227
+ }),
1228
+ );
1229
+ list.hidden = !input.files.length;
1230
+ syncPrompt(pc);
1231
+ }
1232
+ function addFiles(pc, files) {
1233
+ const input = pc.querySelector("[data-asta-prompt-input]");
1234
+ if (!input || !files.length || typeof DataTransfer === "undefined") return;
1235
+ const max = Number(pc.getAttribute("data-max-size")) || 20 * 1048576;
1236
+ const dt = new DataTransfer();
1237
+ [...input.files].forEach((f) => dt.items.add(f));
1238
+ let err = "";
1239
+ [...files].forEach((f) => (f.size > max ? (err = `${f.name} is ${fmt(f.size)}. Attach files under ${fmt(max)}.`) : dt.items.add(f)));
1240
+ input.files = dt.files;
1241
+ note(pc, err, !!err);
1242
+ renderFiles(pc);
1243
+ }
1244
+ function running(pc, on) {
1245
+ pc.toggleAttribute("data-running", on);
1246
+ const field = parts(pc);
1247
+ if (on) note(pc, pc.getAttribute("data-running-text") || "Astabyte is working. Press Esc or Stop to end the run.");
1248
+ else note(pc, "");
1249
+ field?.setAttribute("aria-busy", String(on));
1250
+ }
1251
+ function clear(pc) {
1252
+ const field = parts(pc);
1253
+ if (field) field.replaceChildren();
1254
+ const input = pc.querySelector("[data-asta-prompt-input]");
1255
+ if (input) input.value = "";
1256
+ renderFiles(pc);
1257
+ syncPrompt(pc);
1258
+ }
1259
+ function stop(pc) {
1260
+ const form = pc.querySelector("form");
1261
+ if (window.htmx && form) window.htmx.trigger(form, "htmx:abort");
1262
+ running(pc, false);
1263
+ fire(pc, "asta:prompt-stop", {});
1264
+ parts(pc)?.focus();
1265
+ }
1266
+
1267
+ document.addEventListener("input", (e) => {
1268
+ const t = el(e);
1269
+ const pc = t?.closest("[data-asta-prompt]");
1270
+ if (!pc) return;
1271
+ if (t.closest("[data-asta-prompt-field]")) {
1272
+ dismissed.delete(pc);
1273
+ syncPrompt(pc);
1274
+ detect(pc);
1275
+ }
1276
+ });
1277
+ document.addEventListener("change", (e) => {
1278
+ const t = el(e);
1279
+ const pc = t?.closest("[data-asta-prompt]");
1280
+ if (pc && t.matches("[data-asta-prompt-input]")) {
1281
+ note(pc, "");
1282
+ renderFiles(pc);
1283
+ }
1284
+ });
1285
+ document.addEventListener("keydown", (e) => {
1286
+ const t = el(e);
1287
+ const pc = t?.closest("[data-asta-prompt]");
1288
+ if (!pc) return;
1289
+ if (e.key === "Escape" && pc.hasAttribute("data-running") && !openMenu(pc)) {
1290
+ e.preventDefault();
1291
+ stop(pc);
1292
+ return;
1293
+ }
1294
+ if (!t.closest("[data-asta-prompt-field]")) return;
1295
+ const menu = openMenu(pc);
1296
+ if (menu) {
1297
+ const items = menuItems(menu);
1298
+ const i = items.findIndex((o) => o.getAttribute("aria-selected") === "true");
1299
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
1300
+ e.preventDefault();
1301
+ if (items.length) setActive(pc, menu, items[(i + (e.key === "ArrowDown" ? 1 : -1) + items.length) % items.length]);
1302
+ return;
1303
+ }
1304
+ if ((e.key === "Enter" || e.key === "Tab") && !e.isComposing) {
1305
+ if (items[i]) {
1306
+ e.preventDefault();
1307
+ insert(pc, items[i]);
1308
+ return;
1309
+ }
1310
+ }
1311
+ if (e.key === "Escape") {
1312
+ e.preventDefault();
1313
+ const at = trig.get(pc);
1314
+ if (at) dismissed.set(pc, `${menu.getAttribute("data-asta-prompt-menu")}@${at.start}`);
1315
+ closeMenu(pc);
1316
+ return;
1317
+ }
1318
+ }
1319
+ if (e.key === "Backspace" || e.key === "Delete") {
1320
+ const tok = nextToken(e.key === "Backspace" ? -1 : 1);
1321
+ if (tok) {
1322
+ e.preventDefault();
1323
+ tok.remove();
1324
+ syncPrompt(pc);
1325
+ }
1326
+ return;
1327
+ }
1328
+ if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
1329
+ e.preventDefault();
1330
+ if (!pc.hasAttribute("data-running")) pc.querySelector("form")?.requestSubmit();
1331
+ }
1332
+ });
1333
+ document.addEventListener("pointerdown", (e) => {
1334
+ const opt = el(e)?.closest("[data-asta-prompt-menu] [role='option']");
1335
+ if (opt) e.preventDefault(); // keep the caret in the field
1336
+ });
1337
+ document.addEventListener("click", (e) => {
1338
+ const t = el(e);
1339
+ const pc = t?.closest("[data-asta-prompt]");
1340
+ if (!pc) {
1341
+ document.querySelectorAll("[data-asta-prompt]").forEach((p) => openMenu(p) && closeMenu(p));
1342
+ return;
1343
+ }
1344
+ const opt = t.closest("[data-asta-prompt-menu] [role='option']");
1345
+ if (opt) return insert(pc, opt);
1346
+ const rm = t.closest("[data-asta-prompt-remove]");
1347
+ if (rm) {
1348
+ const input = pc.querySelector("[data-asta-prompt-input]");
1349
+ const dt = new DataTransfer();
1350
+ [...input.files].forEach((f, i) => i !== Number(rm.dataset.astaPromptRemove) && dt.items.add(f));
1351
+ input.files = dt.files;
1352
+ renderFiles(pc);
1353
+ parts(pc)?.focus();
1354
+ return;
1355
+ }
1356
+ if (t.closest("[data-asta-prompt-stop]")) return stop(pc);
1357
+ if (!t.closest("[data-asta-prompt-menu]") && !t.closest("[data-asta-prompt-field]")) closeMenu(pc);
1358
+ });
1359
+ document.addEventListener("paste", (e) => {
1360
+ const field = el(e)?.closest("[data-asta-prompt-field]");
1361
+ if (!field) return;
1362
+ const pc = field.closest("[data-asta-prompt]");
1363
+ const files = e.clipboardData?.files;
1364
+ e.preventDefault();
1365
+ if (files?.length) return addFiles(pc, files);
1366
+ const text = e.clipboardData?.getData("text/plain") || "";
1367
+ if (!document.execCommand("insertText", false, text)) {
1368
+ const r = caretNode();
1369
+ r?.insertNode(document.createTextNode(text));
1370
+ syncPrompt(pc);
1371
+ }
1372
+ });
1373
+ ["dragover", "dragleave", "drop"].forEach((type) =>
1374
+ document.addEventListener(type, (e) => {
1375
+ const box = el(e)?.closest("[data-asta-prompt] .asta-prompt-box");
1376
+ if (!box || !e.dataTransfer?.types?.includes("Files")) return;
1377
+ e.preventDefault();
1378
+ box.toggleAttribute("data-drag", type === "dragover");
1379
+ if (type === "drop") addFiles(box.closest("[data-asta-prompt]"), e.dataTransfer.files);
1380
+ }),
1381
+ );
1382
+ document.addEventListener("submit", (e) => {
1383
+ const pc = el(e)?.closest("[data-asta-prompt]");
1384
+ if (!pc) return;
1385
+ syncPrompt(pc);
1386
+ const send = pc.querySelector(".asta-prompt-send");
1387
+ if (send?.disabled || pc.hasAttribute("data-running")) {
1388
+ e.preventDefault();
1389
+ return;
1390
+ }
1391
+ const form = e.target;
1392
+ const { text, refs } = read(parts(pc));
1393
+ const files = [...(pc.querySelector("[data-asta-prompt-input]")?.files || [])];
1394
+ fire(pc, "asta:prompt-send", { text: text.trim(), refs, files });
1395
+ // Without an action or hx-* attribute there is nowhere to post: the event is the whole contract.
1396
+ const htmxForm = [...form.attributes].some((a) => /^(hx|data-hx)-(post|get|put|patch)$/.test(a.name));
1397
+ if (!form.getAttribute("action") && !htmxForm) {
1398
+ e.preventDefault();
1399
+ clear(pc);
1400
+ }
1401
+ });
1402
+ document.addEventListener("htmx:beforeSend", (e) => {
1403
+ const pc = el(e)?.closest("[data-asta-prompt]");
1404
+ if (!pc) return;
1405
+ running(pc, true);
1406
+ queueMicrotask(() => clear(pc));
1407
+ });
1408
+ document.addEventListener("htmx:afterRequest", (e) => {
1409
+ const pc = el(e)?.closest("[data-asta-prompt]");
1410
+ if (pc) running(pc, false);
1411
+ });
1412
+
1413
+ /* ---------- Boot ---------- */
1414
+
1415
+ const boot = () => scan();
1416
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot, { once: true });
1417
+ else boot();
1418
+ document.addEventListener("htmx:afterSettle", (e) => scan(e.target instanceof Element ? e.target : document));
443
1419
  })();
444
1420
 
445
1421
  /* ---- runtime/blocks.js ---- */
@@ -955,6 +1931,490 @@
955
1931
  document.addEventListener("htmx:afterSettle", (e) => scan(e.detail?.elt?.parentElement || document));
956
1932
  })();
957
1933
 
1934
+ /* ---- runtime/controls.js ---- */
1935
+ /* Controls: scrub input, API keys.
1936
+ * Event delegation on document, so markup swapped in by htmx works without re-init.
1937
+ * Scrub [data-asta-scrub] (data-min, data-max, data-step, data-precision, data-unit): drag the
1938
+ * [data-asta-scrub-handle] to scrub (Shift ×10, Alt ×0.1), or type numbers, units and sums
1939
+ * ("1.5rem", "24*2", "+8") and press Enter. Arrows step. Sets data-scrubbing, data-mod, data-limit and
1940
+ * aria-invalid, keeps a hidden input in sync and fires "asta:scrub" with detail.value on every change
1941
+ * and "change" on the hidden input when a drag or edit ends
1942
+ * API keys [data-asta-keys] (data-undo-ms): [data-asta-keys-create|cancel] open and close the form, which is
1943
+ * checked on submit (a name, one scope at least). Without hx-post or action it makes a demo key and
1944
+ * fires "asta:key-create". [data-asta-keys-dismiss] closes the one-time secret (warns once if it wasn't
1945
+ * copied). [data-asta-keys-revoke|keep|confirm|undo] ask, revoke with an undo window, then fire
1946
+ * "asta:key-revoke" with detail.id and remove the row
1947
+ */
1948
+ (() => {
1949
+ if (window.astaControls) return;
1950
+ window.astaControls = true;
1951
+ const el = (e) => (e.target instanceof Element ? e.target : null);
1952
+ const near = (e, sel) => el(e)?.closest(sel) ?? null;
1953
+ const fire = (node, name, detail) => node.dispatchEvent(new CustomEvent(name, { bubbles: true, detail }));
1954
+
1955
+ /* ---------- Scrub input: the parser ---------- */
1956
+
1957
+ const UNITS = { px: ["len", 1], rem: ["len", 16], em: ["len", 16], pt: ["len", 4 / 3], deg: ["ang", 1], "°": ["ang", 1], rad: ["ang", 180 / Math.PI], turn: ["ang", 360], "%": ["pct", 1], ms: ["time", 1], s: ["time", 1000] };
1958
+
1959
+ function tokenize(src, unit) {
1960
+ const out = [];
1961
+ const base = unit ? UNITS[unit] : undefined;
1962
+ const re = /\s*(?:(\d*\.?\d+(?:e[+-]?\d+)?)\s*([a-z%°]*)|([-+*/×÷()]))\s*/giy;
1963
+ let i = 0;
1964
+ while (i < src.length) {
1965
+ re.lastIndex = i;
1966
+ const m = re.exec(src);
1967
+ if (!m) return null;
1968
+ i = re.lastIndex;
1969
+ if (m[3]) {
1970
+ out.push({ op: m[3] === "×" ? "*" : m[3] === "÷" ? "/" : m[3] });
1971
+ continue;
1972
+ }
1973
+ let v = Number(m[1]);
1974
+ const u = m[2].toLowerCase();
1975
+ if (u && u !== unit) {
1976
+ const typed = UNITS[u];
1977
+ if (!typed || !base || typed[0] !== base[0]) return null;
1978
+ v = (v * typed[1]) / base[1];
1979
+ }
1980
+ out.push({ num: v });
1981
+ }
1982
+ return out;
1983
+ }
1984
+
1985
+ // Numbers with units, + − × ÷ and brackets, without eval. A leading +, * or / works on the current value.
1986
+ function parse(text, current, unit) {
1987
+ let src = text.trim().replace(/,/g, ".").replace(/−/g, "-");
1988
+ if (!src || src.length > 64) return null;
1989
+ let rel = null;
1990
+ if (/^[+*/×÷]/.test(src)) {
1991
+ rel = src[0] === "×" ? "*" : src[0] === "÷" ? "/" : src[0];
1992
+ src = src.slice(1);
1993
+ }
1994
+ const tk = tokenize(src, unit);
1995
+ if (!tk?.length) return null;
1996
+ let p = 0;
1997
+ const isOp = (...ops) => tk[p] && ops.includes(tk[p].op);
1998
+ const factor = () => {
1999
+ const t = tk[p++];
2000
+ if (!t) return NaN;
2001
+ if (t.num !== undefined) return t.num;
2002
+ if (t.op === "-") return -factor();
2003
+ if (t.op === "+") return factor();
2004
+ if (t.op === "(") {
2005
+ const v = expr();
2006
+ return tk[p++]?.op === ")" ? v : NaN;
2007
+ }
2008
+ return NaN;
2009
+ };
2010
+ const term = () => {
2011
+ let v = factor();
2012
+ while (isOp("*", "/")) v = tk[p++].op === "*" ? v * factor() : v / factor();
2013
+ return v;
2014
+ };
2015
+ const expr = () => {
2016
+ let v = term();
2017
+ while (isOp("+", "-")) v = tk[p++].op === "+" ? v + term() : v - term();
2018
+ return v;
2019
+ };
2020
+ let v = expr();
2021
+ if (p !== tk.length || !Number.isFinite(v)) return null;
2022
+ if (rel === "+") v = current + v;
2023
+ else if (rel === "*") v = current * v;
2024
+ else if (rel === "/") v = v === 0 ? NaN : current / v;
2025
+ return Number.isFinite(v) ? v : null;
2026
+ }
2027
+ window.astaParseScrub = parse;
2028
+
2029
+ /* ---------- Scrub input: the field ---------- */
2030
+
2031
+ const num = (s, d) => (s == null || s === "" || Number.isNaN(Number(s)) ? d : Number(s));
2032
+ function cfg(root) {
2033
+ const d = root.dataset;
2034
+ return { min: num(d.min, -Infinity), max: num(d.max, Infinity), step: num(d.step, 1), precision: num(d.precision, 2), unit: d.unit || undefined };
2035
+ }
2036
+ const round = (v, p) => Math.round(v * 10 ** p) / 10 ** p;
2037
+ const fmt = (v, p) => String(round(v, p)).replace(/^-0$/, "0");
2038
+ const field = (root) => root.querySelector("input:not([type=hidden])");
2039
+ function valueOf(root) {
2040
+ if (typeof root._v !== "number") {
2041
+ const c = cfg(root);
2042
+ root._v = parse(field(root)?.value ?? "0", 0, c.unit) ?? 0;
2043
+ }
2044
+ return root._v;
2045
+ }
2046
+
2047
+ function flagLimit(root, which) {
2048
+ const c = cfg(root);
2049
+ root.setAttribute("data-limit", which);
2050
+ clearTimeout(root._lt);
2051
+ root._lt = setTimeout(() => root.removeAttribute("data-limit"), 420);
2052
+ const status = root.querySelector("[data-asta-scrub-status]");
2053
+ if (status) status.textContent = `${which === "max" ? "Maximum" : "Minimum"} is ${fmt(which === "max" ? c.max : c.min, c.precision)}${c.unit || ""}`;
2054
+ }
2055
+
2056
+ // Clamps, writes the field and the hidden input, and flags the edge when a value had to be held back.
2057
+ function set(root, want) {
2058
+ const c = cfg(root);
2059
+ const input = field(root);
2060
+ let v = round(want, c.precision);
2061
+ if (v > c.max) {
2062
+ v = c.max;
2063
+ flagLimit(root, "max");
2064
+ } else if (v < c.min) {
2065
+ v = c.min;
2066
+ flagLimit(root, "min");
2067
+ }
2068
+ const changed = v !== root._v;
2069
+ root._v = v;
2070
+ if (input) {
2071
+ input.value = fmt(v, c.precision);
2072
+ input.setAttribute("aria-valuenow", String(v));
2073
+ input.setAttribute("aria-valuetext", `${fmt(v, c.precision)}${c.unit ? ` ${c.unit}` : ""}`);
2074
+ input.removeAttribute("aria-invalid");
2075
+ }
2076
+ const hidden = root.querySelector("input[type=hidden]");
2077
+ if (hidden) hidden.value = String(v);
2078
+ if (changed) fire(root, "asta:scrub", { value: v });
2079
+ return v;
2080
+ }
2081
+ const settle = (root) => root.querySelector("input[type=hidden]")?.dispatchEvent(new Event("change", { bubbles: true }));
2082
+
2083
+ function commit(root, keepFocus) {
2084
+ const input = field(root);
2085
+ if (!input) return;
2086
+ const c = cfg(root);
2087
+ const cur = valueOf(root);
2088
+ const v = parse(input.value, cur, c.unit);
2089
+ if (v === null) {
2090
+ if (keepFocus) {
2091
+ input.setAttribute("aria-invalid", "true");
2092
+ // Keep the tip inside the panel: align it right when it would run past the edge.
2093
+ const box = root.closest("[role=group],section,form") ?? document.body;
2094
+ root.toggleAttribute("data-tip-end", root.getBoundingClientRect().left + 220 > box.getBoundingClientRect().right);
2095
+ return;
2096
+ }
2097
+ input.value = fmt(cur, c.precision);
2098
+ input.removeAttribute("aria-invalid");
2099
+ const status = root.querySelector("[data-asta-scrub-status]");
2100
+ if (status) status.textContent = `Kept ${fmt(cur, c.precision)}${c.unit || ""}`;
2101
+ return;
2102
+ }
2103
+ set(root, v);
2104
+ settle(root);
2105
+ if (keepFocus) input.select();
2106
+ }
2107
+
2108
+ let drag = null;
2109
+ document.addEventListener("pointerdown", (e) => {
2110
+ const handle = near(e, "[data-asta-scrub-handle]");
2111
+ const root = handle?.closest("[data-asta-scrub]");
2112
+ if (!root || field(root)?.disabled || (e.pointerType === "mouse" && e.button !== 0)) return;
2113
+ e.preventDefault();
2114
+ try {
2115
+ handle.setPointerCapture(e.pointerId);
2116
+ } catch {}
2117
+ drag = { root, handle, id: e.pointerId, x0: e.clientX, x: e.clientX, raw: valueOf(root), moved: false };
2118
+ });
2119
+ document.addEventListener("pointermove", (e) => {
2120
+ if (!drag || e.pointerId !== drag.id) return;
2121
+ const { root } = drag;
2122
+ if (!drag.moved) {
2123
+ if (Math.abs(e.clientX - drag.x0) < 3) return;
2124
+ drag.moved = true;
2125
+ root.setAttribute("data-scrubbing", "");
2126
+ document.documentElement.style.cursor = "ew-resize";
2127
+ }
2128
+ const c = cfg(root);
2129
+ const f = e.shiftKey ? 10 : e.altKey ? 0.1 : 1;
2130
+ const badge = root.querySelector(".asta-scrub-badge");
2131
+ if (f === 1) root.removeAttribute("data-mod");
2132
+ else {
2133
+ root.setAttribute("data-mod", String(f));
2134
+ if (badge) badge.textContent = `×${f}`;
2135
+ }
2136
+ // Half a step per pixel, snapped to the step so a drag never leaves 540.5 behind.
2137
+ const grid = c.step * f;
2138
+ const want = drag.raw + ((e.clientX - drag.x) / 2) * grid;
2139
+ drag.x = e.clientX;
2140
+ drag.raw = Math.min(c.max, Math.max(c.min, want));
2141
+ if (want > c.max) flagLimit(root, "max");
2142
+ else if (want < c.min) flagLimit(root, "min");
2143
+ set(root, Math.round(drag.raw / grid) * grid);
2144
+ });
2145
+ function endDrag(e) {
2146
+ if (!drag || e.pointerId !== drag.id) return;
2147
+ const { root, moved } = drag;
2148
+ drag = null;
2149
+ root.removeAttribute("data-scrubbing");
2150
+ root.removeAttribute("data-mod");
2151
+ document.documentElement.style.cursor = "";
2152
+ if (moved) settle(root);
2153
+ else {
2154
+ const input = field(root);
2155
+ input?.focus();
2156
+ input?.select();
2157
+ }
2158
+ }
2159
+ document.addEventListener("pointerup", endDrag);
2160
+ document.addEventListener("pointercancel", endDrag);
2161
+
2162
+ document.addEventListener("focusin", (e) => {
2163
+ if (e.target instanceof HTMLInputElement && e.target.matches(".asta-api-keys-secret > input")) return e.target.select();
2164
+ const root = near(e, "[data-asta-scrub]");
2165
+ if (root && e.target === field(root)) {
2166
+ valueOf(root);
2167
+ e.target.select();
2168
+ }
2169
+ });
2170
+ document.addEventListener("focusout", (e) => {
2171
+ const root = near(e, "[data-asta-scrub]");
2172
+ if (root && e.target === field(root)) commit(root, false);
2173
+ });
2174
+ document.addEventListener("input", (e) => {
2175
+ const root = near(e, "[data-asta-scrub]");
2176
+ if (root && e.target === field(root)) e.target.removeAttribute("aria-invalid");
2177
+ });
2178
+
2179
+ /* ---------- API keys ---------- */
2180
+
2181
+ const keysRoot = (e) => near(e, "[data-asta-keys]");
2182
+ const focusSoon = (node) => node && requestAnimationFrame(() => node.focus());
2183
+ const formOf = (root) => root.querySelector("[data-asta-keys-form]");
2184
+ const createBtn = (root) => root.querySelector("[data-asta-keys-create]");
2185
+
2186
+ function openForm(root) {
2187
+ const form = formOf(root);
2188
+ if (!form) return;
2189
+ form.hidden = false;
2190
+ createBtn(root)?.setAttribute("aria-expanded", "true");
2191
+ focusSoon(form.querySelector("input[name=name]"));
2192
+ }
2193
+ function closeForm(root, focus = true) {
2194
+ const form = formOf(root);
2195
+ if (!form) return;
2196
+ form.hidden = true;
2197
+ form.reset();
2198
+ form.querySelectorAll("[aria-invalid]").forEach((n) => n.removeAttribute("aria-invalid"));
2199
+ form.querySelectorAll(".asta-api-keys-msg").forEach((m) => showMsg(m, null));
2200
+ form.querySelector("[data-asta-keys-alert]")?.setAttribute("hidden", "");
2201
+ createBtn(root)?.setAttribute("aria-expanded", "false");
2202
+ if (focus) focusSoon(createBtn(root));
2203
+ }
2204
+ // A hint line keeps its hint in data-hint and its error in data-error-text.
2205
+ function showMsg(msg, on) {
2206
+ const text = msg.querySelector("span:last-child") ?? msg;
2207
+ msg.toggleAttribute("data-error", !!on);
2208
+ text.textContent = on ? msg.dataset.errorText : msg.dataset.hint;
2209
+ }
2210
+ function check(form) {
2211
+ const name = form.querySelector("input[name=name]");
2212
+ const scopes = [...form.querySelectorAll("input[name=scopes]")];
2213
+ const noName = !name?.value.trim();
2214
+ const noScope = scopes.length > 0 && !scopes.some((s) => s.checked);
2215
+ if (name && noName) name.setAttribute("aria-invalid", "true");
2216
+ else name?.removeAttribute("aria-invalid");
2217
+ const nameMsg = name && document.getElementById(name.getAttribute("aria-describedby"));
2218
+ if (nameMsg) showMsg(nameMsg, noName);
2219
+ const fs = form.querySelector(".asta-api-keys-scopes");
2220
+ const scopeMsg = fs && document.getElementById(fs.getAttribute("aria-describedby"));
2221
+ if (scopeMsg) showMsg(scopeMsg, noScope);
2222
+ if (noName) name.focus();
2223
+ else if (noScope) scopes[0].focus();
2224
+ return !noName && !noScope;
2225
+ }
2226
+
2227
+ const ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
2228
+ const tail = () => Array.from({ length: 24 }, () => ALPHABET[Math.floor(Math.random() * ALPHABET.length)]).join("");
2229
+
2230
+ // Demo create: fill the reveal row with a key that is clearly marked demo and put it on top.
2231
+ function demoCreate(root, form) {
2232
+ const list = root.querySelector(".asta-api-keys-list");
2233
+ const tpl = root.querySelector("template[data-asta-keys-reveal]");
2234
+ if (!list || !tpl) return;
2235
+ const name = form.querySelector("input[name=name]").value.trim();
2236
+ const scopes = [...form.querySelectorAll("input[name=scopes]:checked")].map((s) => s.value);
2237
+ const secret = `ak_live_demo_${tail()}`;
2238
+ const li = tpl.content.firstElementChild.cloneNode(true);
2239
+ li.dataset.name = name;
2240
+ li.dataset.scopes = scopes.join(",");
2241
+ li.dataset.secret = secret;
2242
+ li.querySelectorAll("[data-slot=name]").forEach((n) => (n.textContent = name));
2243
+ const input = li.querySelector("input[readonly]");
2244
+ if (input) {
2245
+ input.value = secret;
2246
+ input.setAttribute("aria-label", `Secret for ${name}`);
2247
+ }
2248
+ li.querySelector("[data-asta-copy]")?.setAttribute("data-asta-copy", secret);
2249
+ list.prepend(li);
2250
+ closeForm(root, false);
2251
+ fire(root, "asta:key-create", { name, scopes, expires: form.querySelector("select")?.value ?? null });
2252
+ focusSoon(li.querySelector("[data-asta-copy]"));
2253
+ }
2254
+
2255
+ // After the secret is dismissed, the key joins the list masked, built from the row template.
2256
+ function rowFromReveal(root, reveal) {
2257
+ const tpl = root.querySelector("template[data-asta-keys-row]");
2258
+ if (!tpl || !reveal.dataset.secret) return null;
2259
+ const li = tpl.content.firstElementChild.cloneNode(true);
2260
+ const name = reveal.dataset.name;
2261
+ const masked = `ak_live_…${reveal.dataset.secret.slice(-4)}`;
2262
+ const scopes = (reveal.dataset.scopes || "").split(",").filter(Boolean);
2263
+ li.dataset.id = `k${Date.now().toString(36)}`;
2264
+ li.dataset.name = name;
2265
+ li.dataset.key = masked;
2266
+ li.querySelectorAll("[data-slot=name]").forEach((n) => (n.textContent = name));
2267
+ li.querySelectorAll("[data-slot=key]").forEach((n) => (n.textContent = masked));
2268
+ li.querySelectorAll("[data-slot=created]").forEach((n) => (n.textContent = `Created ${new Date().toLocaleDateString("en-US", { month: "short", day: "numeric" })}`));
2269
+ const chips = li.querySelector("[data-slot=scopes]");
2270
+ if (chips) {
2271
+ chips.textContent = "";
2272
+ const code = document.createElement("code");
2273
+ code.textContent = scopes[0] ?? "";
2274
+ chips.append(code);
2275
+ if (scopes.length > 1) {
2276
+ const more = document.createElement("span");
2277
+ more.title = scopes.slice(1).join(", ");
2278
+ more.textContent = `+${scopes.length - 1}`;
2279
+ chips.append(more);
2280
+ }
2281
+ }
2282
+ li.querySelector("[data-asta-keys-revoke]")?.setAttribute("aria-label", `Revoke ${name}`);
2283
+ return li;
2284
+ }
2285
+
2286
+ function dismiss(root, reveal) {
2287
+ const note = reveal.querySelector(".asta-api-keys-note");
2288
+ if (!reveal.hasAttribute("data-copied") && note && !note.hasAttribute("data-warn")) {
2289
+ note.setAttribute("data-warn", "");
2290
+ return;
2291
+ }
2292
+ const row = rowFromReveal(root, reveal);
2293
+ if (row) reveal.replaceWith(row);
2294
+ else reveal.remove();
2295
+ fire(root, "asta:key-dismiss");
2296
+ focusSoon(root.querySelector("[data-asta-keys-heading]") ?? createBtn(root));
2297
+ }
2298
+
2299
+ const timers = new WeakMap();
2300
+ function askRevoke(row, open) {
2301
+ const confirm = row.querySelector(".asta-api-keys-confirm");
2302
+ if (!confirm) return;
2303
+ confirm.hidden = !open;
2304
+ const btn = row.querySelector("[data-asta-keys-revoke]");
2305
+ btn?.setAttribute("aria-expanded", String(open));
2306
+ focusSoon(open ? confirm.querySelector("[data-asta-keys-keep]") : btn);
2307
+ }
2308
+ function revoke(root, row) {
2309
+ const ms = Number(root.dataset.undoMs) || 8000;
2310
+ row.querySelector(".asta-api-keys-confirm")?.setAttribute("hidden", "");
2311
+ row.querySelector("[data-asta-keys-revoke]")?.setAttribute("aria-expanded", "false");
2312
+ row.style.setProperty("--asta-undo", `${ms}ms`);
2313
+ row.setAttribute("data-revoked", "");
2314
+ focusSoon(row.querySelector("[data-asta-keys-undo]"));
2315
+ timers.set(
2316
+ row,
2317
+ setTimeout(() => {
2318
+ timers.delete(row);
2319
+ const hadFocus = row.contains(document.activeElement);
2320
+ const next = row.nextElementSibling ?? row.previousElementSibling;
2321
+ fire(row, "asta:key-revoke", { id: row.dataset.id });
2322
+ row.remove();
2323
+ if (hadFocus) focusSoon(next?.querySelector("[data-asta-keys-revoke],[data-asta-copy]") ?? createBtn(root));
2324
+ }, ms),
2325
+ );
2326
+ }
2327
+ function undo(row) {
2328
+ clearTimeout(timers.get(row));
2329
+ timers.delete(row);
2330
+ row.removeAttribute("data-revoked");
2331
+ fire(row, "asta:key-restore", { id: row.dataset.id });
2332
+ focusSoon(row.querySelector("[data-asta-keys-revoke]"));
2333
+ }
2334
+
2335
+ document.addEventListener("click", (e) => {
2336
+ const root = keysRoot(e);
2337
+ if (!root) return;
2338
+ const row = near(e, ".asta-api-keys-row");
2339
+ if (near(e, "[data-asta-keys-create]")) {
2340
+ const form = formOf(root);
2341
+ if (form && !form.hidden) form.querySelector("input[name=name]")?.focus();
2342
+ else openForm(root);
2343
+ } else if (near(e, "[data-asta-keys-cancel]")) closeForm(root);
2344
+ else if (near(e, "[data-asta-keys-dismiss]")) dismiss(root, near(e, ".asta-api-keys-reveal"));
2345
+ else if (row && near(e, "[data-asta-keys-revoke]")) askRevoke(row, row.querySelector(".asta-api-keys-confirm")?.hidden ?? false);
2346
+ else if (row && near(e, "[data-asta-keys-keep]")) askRevoke(row, false);
2347
+ else if (row && near(e, "[data-asta-keys-confirm]")) revoke(root, row);
2348
+ else if (row && near(e, "[data-asta-keys-undo]")) undo(row);
2349
+ });
2350
+
2351
+ // A copy inside the reveal row counts as saved.
2352
+ document.addEventListener("asta:copy", (e) => {
2353
+ const reveal = near(e, ".asta-api-keys-reveal");
2354
+ if (!reveal) return;
2355
+ reveal.setAttribute("data-copied", "");
2356
+ reveal.querySelector(".asta-api-keys-note")?.removeAttribute("data-warn");
2357
+ });
2358
+
2359
+ // Capture phase, so an invalid form never reaches htmx or the browser.
2360
+ document.addEventListener(
2361
+ "submit",
2362
+ (e) => {
2363
+ const form = e.target instanceof HTMLFormElement && e.target.matches("[data-asta-keys-form]") ? e.target : null;
2364
+ const root = form?.closest("[data-asta-keys]");
2365
+ if (!root) return;
2366
+ if (!check(form)) {
2367
+ e.preventDefault();
2368
+ e.stopPropagation();
2369
+ return;
2370
+ }
2371
+ const remote = form.hasAttribute("action") || [...form.attributes].some((a) => /^(hx|data-hx)-(post|put)$/.test(a.name));
2372
+ if (!remote) {
2373
+ e.preventDefault();
2374
+ demoCreate(root, form);
2375
+ }
2376
+ },
2377
+ true,
2378
+ );
2379
+
2380
+ document.addEventListener("keydown", (e) => {
2381
+ const root = keysRoot(e);
2382
+ if (root) {
2383
+ if (e.key !== "Escape") return;
2384
+ if (near(e, "[data-asta-keys-form]")) {
2385
+ e.preventDefault();
2386
+ closeForm(root);
2387
+ } else if (near(e, ".asta-api-keys-confirm")) {
2388
+ e.preventDefault();
2389
+ askRevoke(near(e, ".asta-api-keys-row"), false);
2390
+ }
2391
+ return;
2392
+ }
2393
+ const sroot = near(e, "[data-asta-scrub]");
2394
+ if (!sroot || e.target !== field(sroot)) return;
2395
+ const c = cfg(sroot);
2396
+ const input = e.target;
2397
+ if (e.key === "Enter") {
2398
+ e.preventDefault();
2399
+ commit(sroot, true);
2400
+ } else if (e.key === "Escape") {
2401
+ e.preventDefault();
2402
+ input.value = fmt(valueOf(sroot), c.precision);
2403
+ input.removeAttribute("aria-invalid");
2404
+ input.select();
2405
+ } else if (e.key === "ArrowUp" || e.key === "ArrowDown" || e.key === "PageUp" || e.key === "PageDown") {
2406
+ e.preventDefault();
2407
+ const page = e.key.startsWith("Page");
2408
+ const f = page ? 10 : e.shiftKey ? 10 : e.altKey ? 0.1 : 1;
2409
+ const dir = e.key === "ArrowUp" || e.key === "PageUp" ? 1 : -1;
2410
+ const typed = parse(input.value, valueOf(sroot), c.unit);
2411
+ set(sroot, (typed ?? valueOf(sroot)) + dir * c.step * f);
2412
+ settle(sroot);
2413
+ input.select();
2414
+ }
2415
+ });
2416
+ })();
2417
+
958
2418
  /* ---- runtime/data.js ---- */
959
2419
  /* Data components for Astabyte UI. Event delegation on document, so htmx swaps need no re-init.
960
2420
  * DataTable [data-asta-dt] with [data-asta-dt-all], [data-asta-dt-row], [data-asta-dt-clear]