@qikbar/qikbar 0.0.25 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +121 -0
  3. package/bin/qikbar.mjs +203 -0
  4. package/dist/ai/agent.d.ts +42 -0
  5. package/dist/ai/byok.d.ts +29 -0
  6. package/dist/ai/embeddings.d.ts +51 -0
  7. package/dist/ai/index.d.ts +12 -0
  8. package/dist/ai/mcp.d.ts +84 -0
  9. package/dist/ai/providers.d.ts +82 -0
  10. package/dist/ai/sse.d.ts +9 -0
  11. package/dist/ai.js +54 -0
  12. package/dist/ai.js.map +7 -0
  13. package/dist/chunks/bar-P3SCR4SJ.js +2555 -0
  14. package/dist/chunks/bar-P3SCR4SJ.js.map +7 -0
  15. package/dist/chunks/chunk-5FI7DNG7.js +271 -0
  16. package/dist/chunks/chunk-5FI7DNG7.js.map +7 -0
  17. package/dist/chunks/chunk-INTEVQYK.js +108 -0
  18. package/dist/chunks/chunk-INTEVQYK.js.map +7 -0
  19. package/dist/chunks/chunk-JHQAIXM7.js +458 -0
  20. package/dist/chunks/chunk-JHQAIXM7.js.map +7 -0
  21. package/dist/chunks/chunk-MPTP2EWW.js +8 -0
  22. package/dist/chunks/chunk-MPTP2EWW.js.map +7 -0
  23. package/dist/chunks/chunk-MRHKJ2FZ.js +419 -0
  24. package/dist/chunks/chunk-MRHKJ2FZ.js.map +7 -0
  25. package/dist/chunks/chunk-N4Y2Z6YD.js +69 -0
  26. package/dist/chunks/chunk-N4Y2Z6YD.js.map +7 -0
  27. package/dist/chunks/chunk-OLXZNYZ4.js +193 -0
  28. package/dist/chunks/chunk-OLXZNYZ4.js.map +7 -0
  29. package/dist/chunks/chunk-PQEHV3D4.js +124 -0
  30. package/dist/chunks/chunk-PQEHV3D4.js.map +7 -0
  31. package/dist/chunks/chunk-R2AY6LRL.js +575 -0
  32. package/dist/chunks/chunk-R2AY6LRL.js.map +7 -0
  33. package/dist/chunks/chunk-TIM4VBM4.js +98 -0
  34. package/dist/chunks/chunk-TIM4VBM4.js.map +7 -0
  35. package/dist/chunks/chunk-YCVJQ7U3.js +52 -0
  36. package/dist/chunks/chunk-YCVJQ7U3.js.map +7 -0
  37. package/dist/chunks/launcher-B5MGOPEQ.js +37 -0
  38. package/dist/chunks/launcher-B5MGOPEQ.js.map +7 -0
  39. package/dist/core/define.d.ts +40 -0
  40. package/dist/core/frecency.d.ts +16 -0
  41. package/dist/core/hotkeys.d.ts +39 -0
  42. package/dist/core/labels.d.ts +98 -0
  43. package/dist/core/launcher.d.ts +8 -0
  44. package/dist/core/lazy.d.ts +60 -0
  45. package/dist/core/search.d.ts +42 -0
  46. package/dist/core/storage.d.ts +5 -0
  47. package/dist/core/types.d.ts +737 -0
  48. package/dist/element/index.d.ts +56 -0
  49. package/dist/element.js +146 -0
  50. package/dist/element.js.map +7 -0
  51. package/dist/extensions/index.d.ts +30 -0
  52. package/dist/extensions/math.d.ts +14 -0
  53. package/dist/extensions.js +476 -0
  54. package/dist/extensions.js.map +7 -0
  55. package/dist/index.d.ts +31 -0
  56. package/dist/index.js +85 -0
  57. package/dist/index.js.map +7 -0
  58. package/dist/locales/index.d.ts +24 -0
  59. package/dist/locales.js +810 -0
  60. package/dist/locales.js.map +7 -0
  61. package/dist/qikbar.global.js +302 -0
  62. package/dist/qikbar.global.js.map +7 -0
  63. package/dist/react/index.d.ts +66 -0
  64. package/dist/react.js +121 -0
  65. package/dist/react.js.map +7 -0
  66. package/dist/server/index.d.ts +66 -0
  67. package/dist/server.js +129 -0
  68. package/dist/server.js.map +7 -0
  69. package/dist/solid/index.d.ts +42 -0
  70. package/dist/solid.js +93 -0
  71. package/dist/solid.js.map +7 -0
  72. package/dist/styles.css +253 -0
  73. package/dist/svelte/index.d.ts +58 -0
  74. package/dist/svelte.js +55 -0
  75. package/dist/svelte.js.map +7 -0
  76. package/dist/theme.d.ts +5 -0
  77. package/dist/theme.js +20 -0
  78. package/dist/theme.js.map +7 -0
  79. package/dist/ui/bar.d.ts +338 -0
  80. package/dist/ui/dom.d.ts +21 -0
  81. package/dist/ui/icons.d.ts +93 -0
  82. package/dist/ui/markdown.d.ts +10 -0
  83. package/dist/ui/nav.d.ts +8 -0
  84. package/dist/ui/styles.d.ts +6 -0
  85. package/dist/ui/themes.d.ts +27 -0
  86. package/dist/ui/views.d.ts +156 -0
  87. package/dist/ui/webmcp.d.ts +33 -0
  88. package/dist/utils.d.ts +10 -0
  89. package/dist/utils.js +50 -0
  90. package/dist/utils.js.map +7 -0
  91. package/dist/vue/index.d.ts +74 -0
  92. package/dist/vue.js +122 -0
  93. package/dist/vue.js.map +7 -0
  94. package/package.json +129 -43
  95. package/dist/qikbar.es.js +0 -8748
  96. package/dist/qikbar.umd.js +0 -113
  97. package/dist/types/boot.d.ts +0 -72
  98. package/dist/types/index.d.ts +0 -1
  99. package/dist/types/init.d.ts +0 -2
  100. package/dist/types/main.d.ts +0 -4
  101. package/dist/types/shared/AsyncRoot.d.ts +0 -5
  102. package/dist/types/shared/CommandFooter.d.ts +0 -5
  103. package/dist/types/shared/Crumbs.d.ts +0 -6
  104. package/dist/types/shared/Details.d.ts +0 -3
  105. package/dist/types/shared/ErrorBoundary.d.ts +0 -15
  106. package/dist/types/shared/Icon.d.ts +0 -4
  107. package/dist/types/shared/List.d.ts +0 -30
  108. package/dist/types/shared/Qikbar.d.ts +0 -5
  109. package/dist/types/shared/Root.d.ts +0 -4
  110. package/dist/types/shared/Search.d.ts +0 -1
  111. package/dist/types/shared/commandContext.d.ts +0 -8
  112. package/dist/types/shared/useDebounce.d.ts +0 -1
  113. package/dist/types/utils/liquid.d.ts +0 -4
  114. package/dist/types/vite-env.d.ts +0 -1
@@ -0,0 +1,2555 @@
1
+ import {
2
+ createAIClient,
3
+ runAgent
4
+ } from "./chunk-N4Y2Z6YD.js";
5
+ import {
6
+ action
7
+ } from "./chunk-INTEVQYK.js";
8
+ import {
9
+ css,
10
+ cssVarName,
11
+ resolveThemeVars
12
+ } from "./chunk-R2AY6LRL.js";
13
+ import {
14
+ Frecency,
15
+ copyText,
16
+ defaultNavigate,
17
+ iconSvg,
18
+ matchItem,
19
+ rank,
20
+ renderMarkdown
21
+ } from "./chunk-JHQAIXM7.js";
22
+ import {
23
+ defaultStorage,
24
+ scopedStorage
25
+ } from "./chunk-YCVJQ7U3.js";
26
+ import {
27
+ SequenceMatcher,
28
+ allowedInInput,
29
+ formatHotkey,
30
+ isEditable,
31
+ matchesHotkey
32
+ } from "./chunk-PQEHV3D4.js";
33
+ import {
34
+ en,
35
+ format
36
+ } from "./chunk-TIM4VBM4.js";
37
+ import {
38
+ __publicField
39
+ } from "./chunk-MPTP2EWW.js";
40
+
41
+ // src/ui/dom.ts
42
+ function h(tag, props, ...children) {
43
+ let el = document.createElement(tag);
44
+ if (props)
45
+ for (let key in props) {
46
+ let value = props[key];
47
+ value == null || value === !1 || (key === "class" ? el.className = value : key === "style" && typeof value == "object" ? Object.assign(el.style, value) : key.startsWith("on") && typeof value == "function" ? el.addEventListener(key.slice(2).toLowerCase(), value) : key === "html" ? el.innerHTML = value : key in el && typeof value != "string" ? el[key] = value : el.setAttribute(key, value === !0 ? "" : String(value)));
48
+ }
49
+ return append(el, children), el;
50
+ }
51
+ function append(el, children) {
52
+ for (let child of children)
53
+ Array.isArray(child) ? append(el, child) : child != null && child !== !1 && el.append(child instanceof Node ? child : String(child));
54
+ }
55
+ var URL_RE = /^(https?:|\/|\.\.?\/|data:image\/|blob:)/;
56
+ function renderIcon(icon, size = 16) {
57
+ if (icon == null || icon === "") return null;
58
+ let wrap = h("span", { class: "qb-icon", "aria-hidden": "true" });
59
+ if (typeof icon == "function")
60
+ wrap.append(icon());
61
+ else if (typeof Node < "u" && icon instanceof Node)
62
+ wrap.append(icon.cloneNode(!0));
63
+ else if (typeof icon == "object" && "url" in icon)
64
+ wrap.append(h("img", { src: icon.url, alt: icon.alt ?? "", loading: "lazy", decoding: "async", draggable: "false" }));
65
+ else if (typeof icon == "object" && "color" in icon) {
66
+ wrap.classList.add("qb-icon-tinted"), wrap.style.setProperty("--qb-tint", colorValue(icon.color));
67
+ let inner = renderIcon(icon.icon ?? "dot", size);
68
+ inner && wrap.append(...inner.childNodes);
69
+ } else if (typeof icon == "string") {
70
+ let svg = iconSvg(icon, size);
71
+ svg ? wrap.innerHTML = svg : icon.trimStart().startsWith("<svg") ? wrap.innerHTML = icon : URL_RE.test(icon) ? wrap.append(h("img", { src: icon, alt: "", loading: "lazy", decoding: "async", draggable: "false" })) : (wrap.classList.add("qb-icon-text"), wrap.textContent = icon);
72
+ }
73
+ return wrap;
74
+ }
75
+ function renderKbd(hotkey, className = "qb-kbd") {
76
+ let wrap = h("span", { class: "qb-kbds", "aria-label": hotkey });
77
+ return formatHotkey(hotkey).forEach((combo, i) => {
78
+ i > 0 && wrap.append(h("span", { class: "qb-kbd-then" }, "then"));
79
+ for (let key of combo) wrap.append(h("kbd", { class: className }, key));
80
+ }), wrap;
81
+ }
82
+ function highlight(text, positions) {
83
+ if (!positions || positions.length === 0) return text;
84
+ let frag = document.createDocumentFragment(), last = 0, i = 0;
85
+ for (; i < positions.length; ) {
86
+ let start = positions[i], end = start;
87
+ for (; i + 1 < positions.length && positions[i + 1] === end + 1; )
88
+ i++, end++;
89
+ start > last && frag.append(text.slice(last, start)), frag.append(h("mark", { class: "qb-match" }, text.slice(start, end + 1))), last = end + 1, i++;
90
+ }
91
+ return last < text.length && frag.append(text.slice(last)), frag;
92
+ }
93
+ var NAMED_COLORS = {
94
+ default: "var(--qb-fg-muted)",
95
+ gray: "var(--qb-fg-subtle)",
96
+ blue: "#3b82f6",
97
+ green: "#22c55e",
98
+ yellow: "#eab308",
99
+ orange: "#f97316",
100
+ red: "#ef4444",
101
+ purple: "#a855f7",
102
+ pink: "#ec4899"
103
+ };
104
+ function colorValue(color) {
105
+ return color ? NAMED_COLORS[color] ?? color : NAMED_COLORS.default;
106
+ }
107
+ function renderTag(tag) {
108
+ let value = typeof tag == "string" ? tag : tag.value, color = typeof tag == "string" ? void 0 : tag.color, el = h("span", { class: "qb-tag" }, value);
109
+ return color && el.style.setProperty("--qb-tint", colorValue(color)), el;
110
+ }
111
+ var rtf = typeof Intl < "u" && "RelativeTimeFormat" in Intl ? new Intl.RelativeTimeFormat(void 0, { numeric: "auto", style: "short" }) : null;
112
+ function relativeTime(date) {
113
+ let d = new Date(date), diff = (d.getTime() - Date.now()) / 1e3, abs = Math.abs(diff);
114
+ return rtf ? abs < 60 ? rtf.format(Math.round(diff), "second") : abs < 3600 ? rtf.format(Math.round(diff / 60), "minute") : abs < 86400 ? rtf.format(Math.round(diff / 3600), "hour") : abs < 86400 * 30 ? rtf.format(Math.round(diff / 86400), "day") : abs < 86400 * 365 ? rtf.format(Math.round(diff / (86400 * 30)), "month") : rtf.format(Math.round(diff / (86400 * 365)), "year") : d.toLocaleDateString();
115
+ }
116
+ function renderAccessory(acc) {
117
+ let el = h("span", { class: "qb-accessory", title: acc.tooltip }), icon = renderIcon(acc.icon, 14);
118
+ return icon && el.append(icon), acc.tag && el.append(renderTag(acc.tag)), acc.text && el.append(h("span", null, acc.text)), acc.date != null && el.append(h("time", { datetime: new Date(acc.date).toISOString() }, relativeTime(acc.date))), acc.kbd && el.append(renderKbd(acc.kbd)), el;
119
+ }
120
+ var idCounter = 0;
121
+ function uid(prefix = "qb") {
122
+ return `${prefix}-${(++idCounter).toString(36)}`;
123
+ }
124
+
125
+ // src/ui/webmcp.ts
126
+ function modelContext() {
127
+ let doc = typeof document < "u" ? document.modelContext : void 0, nav = typeof navigator < "u" ? navigator.modelContext : void 0, ctx = doc ?? nav;
128
+ return ctx && typeof ctx.registerTool == "function" ? ctx : void 0;
129
+ }
130
+ var safeName = (s) => s.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
131
+ function exposeWebMCP(bar, options = {}) {
132
+ let mc = modelContext();
133
+ if (!mc) return () => {
134
+ };
135
+ let prefix = safeName(options.prefix ?? "qikbar"), controller = new AbortController(), names = [], found = /* @__PURE__ */ new Map(), lookup = (id) => found.get(id) ?? bar.rootItems().find((i) => bar.idOf(i) === id), register = (tool) => {
136
+ try {
137
+ mc.registerTool(tool, { signal: controller.signal }), names.push(tool.name);
138
+ } catch (err) {
139
+ console.warn(`[qikbar] could not register WebMCP tool "${tool.name}"`, err);
140
+ }
141
+ };
142
+ if (register({
143
+ name: `${prefix}_list_commands`,
144
+ description: `List the commands and pages available in this app's command bar (${typeof document < "u" ? document.title : "this app"}). Returns ids you can pass to ${prefix}_run.`,
145
+ inputSchema: { type: "object", properties: {} },
146
+ annotations: { readOnlyHint: !0 },
147
+ execute: async () => JSON.stringify(
148
+ bar.rootItems().filter((i) => !bar.idOf(i).startsWith("qikbar.")).map((i) => ({ id: bar.idOf(i), title: i.title, subtitle: i.subtitle, section: i.section, description: i.description, href: i.href ?? i.url }))
149
+ )
150
+ }), register({
151
+ name: `${prefix}_search`,
152
+ description: `Search this app's commands, pages and records (including live data sources). Returns matching items with ids you can pass to ${prefix}_run.`,
153
+ inputSchema: { type: "object", properties: { query: { type: "string", description: "What to look for" } }, required: ["query"] },
154
+ annotations: { readOnlyHint: !0, untrustedContentHint: !0 },
155
+ execute: async (args, opts) => {
156
+ let results = await bar.searchForAgent(String(args.query ?? ""), void 0, opts?.signal ?? new AbortController().signal, found);
157
+ return results.length ? JSON.stringify(results) : "No results.";
158
+ }
159
+ }), options.run !== !1 && register({
160
+ name: `${prefix}_run`,
161
+ description: "Open a page or run a command in this app by id (from list_commands or search). Destructive commands ask the user first.",
162
+ inputSchema: {
163
+ type: "object",
164
+ properties: {
165
+ id: { type: "string" },
166
+ arguments: { type: "object", description: "Values for the command arguments, if it has any.", additionalProperties: { type: "string" } }
167
+ },
168
+ required: ["id"]
169
+ },
170
+ execute: async (args) => {
171
+ let item = lookup(String(args.id ?? ""));
172
+ if (!item) return `No item with id "${String(args.id)}". Call ${prefix}_search or ${prefix}_list_commands first.`;
173
+ try {
174
+ return await bar.runForAgent(item, args.arguments, void 0, "agent");
175
+ } catch (err) {
176
+ return `Error: ${err instanceof Error ? err.message : String(err)}`;
177
+ }
178
+ }
179
+ }), options.tools !== !1)
180
+ for (let { tool, rt, prefix: ext } of bar.toolList())
181
+ register({
182
+ name: safeName(`${prefix}_${ext ? `${ext}_` : ""}${tool.name}`),
183
+ description: tool.description,
184
+ inputSchema: tool.parameters ?? { type: "object", properties: {} },
185
+ annotations: tool.confirm ? { consequentialHint: !0 } : void 0,
186
+ execute: async (args) => {
187
+ if (tool.confirm) {
188
+ let msg = typeof tool.confirm == "function" ? tool.confirm(args) : bar.t("allowTool", { tool: tool.name });
189
+ if (!await bar.confirm({ title: msg, confirmLabel: bar.t("allow") })) return "The user declined.";
190
+ }
191
+ let result = await tool.run(args, bar.toolContext(rt));
192
+ return typeof result == "string" ? result : JSON.stringify(result ?? "Done.");
193
+ }
194
+ });
195
+ return () => {
196
+ if (controller.abort(), typeof mc.unregisterTool == "function")
197
+ for (let name of names)
198
+ try {
199
+ mc.unregisterTool(name);
200
+ } catch {
201
+ }
202
+ };
203
+ }
204
+
205
+ // src/ui/views.ts
206
+ var LONG_PRESS_MS = 480, VIRTUAL_THRESHOLD = 150, OVERSCAN = 10, optionId = (bar, key) => `${bar.instanceId}-opt-${key.replace(/[^\w-]/g, "_")}`;
207
+ function px(value, fallback) {
208
+ let n = parseFloat(value);
209
+ return Number.isFinite(n) && n > 0 ? n : fallback;
210
+ }
211
+ var detailCache = /* @__PURE__ */ new WeakMap(), ListRenderer = class {
212
+ constructor(bar, frame) {
213
+ __publicField(this, "bar", bar);
214
+ __publicField(this, "frame", frame);
215
+ __publicField(this, "el");
216
+ __publicField(this, "hasInput", !0);
217
+ __publicField(this, "scroller");
218
+ __publicField(this, "inner");
219
+ __publicField(this, "emptyEl");
220
+ __publicField(this, "detailEl");
221
+ __publicField(this, "cache", /* @__PURE__ */ new Map());
222
+ __publicField(this, "renderedKeys", []);
223
+ __publicField(this, "selectedEl");
224
+ __publicField(this, "virtual", !1);
225
+ __publicField(this, "offsets", []);
226
+ __publicField(this, "rowHeight", 42);
227
+ __publicField(this, "sectionHeight", 30);
228
+ __publicField(this, "rafId", 0);
229
+ __publicField(this, "detailFor");
230
+ __publicField(this, "press");
231
+ __publicField(this, "onScroll", () => {
232
+ !this.virtual || this.rafId || (this.rafId = requestAnimationFrame(() => {
233
+ this.rafId = 0, this.renderWindow();
234
+ }));
235
+ });
236
+ __publicField(this, "onPointerMove", (e) => {
237
+ let p = this.press;
238
+ if (p && !p.fired && Math.hypot(e.clientX - p.x, e.clientY - p.y) > 8 && this.cancelPress(), e.pointerType !== "mouse") return;
239
+ let el = e.target.closest?.("[data-index]");
240
+ if (!el) return;
241
+ let index = Number(el.dataset.index);
242
+ index !== this.frame.selected && this.select(index, !1);
243
+ });
244
+ __publicField(this, "onClick", (e) => {
245
+ let el = e.target.closest?.("[data-index]");
246
+ if (!el) return;
247
+ if (this.press?.fired) {
248
+ this.press = void 0, e.stopPropagation();
249
+ return;
250
+ }
251
+ let index = Number(el.dataset.index);
252
+ this.select(index, !1);
253
+ let item = this.frame.itemRows[index]?.item;
254
+ if (item && this.bar.isMulti(this.frame)) {
255
+ if (e.shiftKey) return this.bar.markRange(this.frame, item);
256
+ if (e.metaKey || e.ctrlKey) return this.bar.toggleMark(this.frame, item);
257
+ if (this.frame.marked?.size) return this.bar.toggleMark(this.frame, item);
258
+ }
259
+ this.bar.runPrimary(this.frame, e.metaKey || e.ctrlKey ? 1 : 0, "click");
260
+ });
261
+ /** Keep focus in the search box; on touch, a long press opens the actions. */
262
+ __publicField(this, "onPointerDown", (e) => {
263
+ if (e.preventDefault(), this.cancelPress(), e.pointerType === "mouse") return;
264
+ let el = e.target.closest?.("[data-index]");
265
+ if (!el) return;
266
+ let index = Number(el.dataset.index), press = {
267
+ x: e.clientX,
268
+ y: e.clientY,
269
+ fired: !1,
270
+ timer: setTimeout(() => {
271
+ press.fired = !0, this.select(index, !1), this.bar.openPanel(), navigator.vibrate?.(8);
272
+ }, LONG_PRESS_MS)
273
+ };
274
+ this.press = press;
275
+ });
276
+ __publicField(this, "cancelPress", (e) => {
277
+ let p = this.press;
278
+ p && (clearTimeout(p.timer), (!p.fired || e?.type === "pointercancel") && (this.press = void 0));
279
+ });
280
+ __publicField(this, "onContextMenu", (e) => {
281
+ let el = e.target.closest?.("[data-index]");
282
+ el && (e.preventDefault(), !(this.press?.fired || this.bar.panel) && (this.select(Number(el.dataset.index), !1), this.bar.openPanel()));
283
+ });
284
+ this.inner = h("div", { class: "qb-list-inner" }), this.scroller = h(
285
+ "div",
286
+ { class: `${bar.cls("qb-scroll qb-list", "list")}`, role: "listbox", id: `${bar.instanceId}-list`, "aria-label": bar.t("results"), tabindex: "-1" },
287
+ this.inner
288
+ ), this.emptyEl = h("div", { class: "qb-empty", hidden: !0 }), frame.view.type === "list" && frame.view.detail ? (this.detailEl = h("div", { class: bar.cls("qb-detail qb-md", "detail") }), this.el = h("div", { class: "qb-split", style: "display:flex;flex:1;min-width:0;position:relative" }, this.scroller, this.detailEl, this.emptyEl)) : this.el = h("div", { style: "display:flex;flex:1;min-width:0;position:relative" }, this.scroller, this.emptyEl), this.scroller.addEventListener("pointermove", this.onPointerMove), this.scroller.addEventListener("click", this.onClick), this.scroller.addEventListener("pointerdown", this.onPointerDown), this.scroller.addEventListener("pointerup", this.cancelPress), this.scroller.addEventListener("pointercancel", this.cancelPress), this.scroller.addEventListener("contextmenu", this.onContextMenu), this.scroller.addEventListener("scroll", this.onScroll, { passive: !0 });
289
+ }
290
+ measure() {
291
+ let cs = getComputedStyle(this.bar.dom.root);
292
+ this.rowHeight = px(cs.getPropertyValue("--qb-row-height"), 42), this.sectionHeight = px(cs.getPropertyValue("--qb-section-height"), 30), this.bar.isTouch && (this.rowHeight = Math.max(this.rowHeight, 48));
293
+ }
294
+ refresh() {
295
+ this.cache.clear(), this.inner.replaceChildren(), this.renderedKeys = [], this.selectedEl = void 0, this.update();
296
+ }
297
+ update() {
298
+ let rows = this.frame.rows, wasVirtual = this.virtual;
299
+ if (this.virtual = rows.length > VIRTUAL_THRESHOLD, this.virtual) {
300
+ wasVirtual || this.measure();
301
+ let y = 0;
302
+ this.offsets = rows.map((r) => {
303
+ let top = y;
304
+ return y += r.kind === "section" ? this.sectionHeight : this.rowHeight, top;
305
+ }), this.inner.style.height = `${y}px`, this.renderWindow();
306
+ } else {
307
+ if (wasVirtual) {
308
+ this.inner.style.height = "";
309
+ for (let { el } of this.cache.values()) el.style.cssText = "";
310
+ }
311
+ let keys = rows.map((r) => r.key), els = rows.map((r) => this.rowEl(r));
312
+ (!sameKeys(keys, this.renderedKeys) || els.some((el, i) => this.inner.children[i] !== el)) && (this.inner.replaceChildren(...els), this.renderedKeys = keys), this.prune(new Set(keys));
313
+ }
314
+ this.updateSelection(), this.updateEmpty(), this.updateDetail();
315
+ }
316
+ prune(keep) {
317
+ if (!(this.cache.size < 400))
318
+ for (let key of this.cache.keys()) keep.has(key) || this.cache.delete(key);
319
+ }
320
+ renderWindow() {
321
+ let rows = this.frame.rows, top = this.scroller.scrollTop, height = this.scroller.clientHeight || 400, start = bisect(this.offsets, top) - OVERSCAN;
322
+ start = Math.max(0, start);
323
+ let end = bisect(this.offsets, top + height) + OVERSCAN;
324
+ end = Math.min(rows.length, end + 1);
325
+ let els = [], keys = [];
326
+ for (let i = start; i < end; i++) {
327
+ let row = rows[i], el = this.rowEl(row);
328
+ el.style.position = "absolute", el.style.top = `${this.offsets[i]}px`, el.style.left = "0", el.style.right = "0", els.push(el), keys.push(row.key);
329
+ }
330
+ sameKeys(keys, this.renderedKeys) || (this.inner.replaceChildren(...els), this.renderedKeys = keys), this.updateSelection();
331
+ }
332
+ rowSig(row) {
333
+ if (row.kind === "section") return row.title;
334
+ let sig = `${row.index}|${row.positions?.join(",") ?? ""}`;
335
+ if (this.frame.view.type === "root" && this.bar.personalize) {
336
+ let id = this.bar.idOf(row.item);
337
+ sig += `|${this.bar.aliasOf(id) ?? ""}|${this.bar.pins().includes(id) ? "p" : ""}`;
338
+ }
339
+ return sig;
340
+ }
341
+ rowEl(row) {
342
+ let sig = this.rowSig(row), cached = this.cache.get(row.key);
343
+ if (cached && cached.sig === sig && (row.kind === "section" || cached.el.__item === row.item)) return cached.el;
344
+ let el = row.kind === "section" ? this.sectionEl(row.title) : this.itemEl(row);
345
+ return row.kind === "item" && (el.__item = row.item), this.cache.set(row.key, { el, sig }), el;
346
+ }
347
+ sectionEl(title) {
348
+ return h("div", { class: this.bar.cls("qb-section", "section"), role: "presentation" }, title);
349
+ }
350
+ itemEl(row) {
351
+ let { item } = row, isRoot = this.frame.view.type === "root", right = [];
352
+ if (isRoot && this.bar.personalize) {
353
+ let id = this.bar.idOf(item), alias = this.bar.aliasOf(id);
354
+ alias && right.push(h("span", { class: "qb-alias", title: this.bar.t("alias") }, alias)), this.bar.pins().includes(id) && right.push(h("span", { class: "qb-pin", title: this.bar.t("pinned") }, renderIcon("pin", 13)));
355
+ }
356
+ return item.accessories?.length ? right.push(h("span", { class: "qb-item-accessories" }, ...item.accessories.map(renderAccessory))) : item.shortcut && right.push(h("span", { class: "qb-item-accessories" }, renderKbd(item.shortcut))), isRoot && !item.accessories?.length && !item.shortcut && right.push(h("span", { class: "qb-item-kind" }, this.kindOf(item))), h(
357
+ "div",
358
+ {
359
+ class: this.bar.cls("qb-item", "item"),
360
+ role: "option",
361
+ id: optionId(this.bar, row.key),
362
+ "aria-selected": "false",
363
+ "data-index": String(row.index)
364
+ },
365
+ this.bar.isMulti(this.frame) ? h("span", { class: "qb-check", "aria-hidden": "true" }, renderIcon("check", 12)) : null,
366
+ h("span", { class: "qb-item-icon" }, renderIcon(item.icon ?? (isRoot ? "command" : void 0), 16)),
367
+ h(
368
+ "span",
369
+ { class: "qb-item-text" },
370
+ h("span", { class: "qb-item-title" }, highlight(item.title, row.positions)),
371
+ item.subtitle ? h("span", { class: "qb-item-subtitle" }, item.subtitle) : null
372
+ ),
373
+ ...right
374
+ );
375
+ }
376
+ kindOf(item) {
377
+ return this.bar.itemExt.get(item) ? this.bar.t("kindCommand") : item.href ? this.bar.t("kindPage") : item.url ? this.bar.t("kindLink") : this.bar.t("kindCommand");
378
+ }
379
+ updateSelection() {
380
+ let row = this.frame.itemRows[this.frame.selected], el = row ? this.cache.get(row.key)?.el : void 0;
381
+ if (this.selectedEl && this.selectedEl !== el && this.selectedEl.setAttribute("aria-selected", "false"), el && el.setAttribute("aria-selected", "true"), this.selectedEl = el, this.bar.isMulti(this.frame))
382
+ for (let r of this.frame.itemRows) {
383
+ let rowEl = this.cache.get(r.key)?.el;
384
+ if (!rowEl) continue;
385
+ let marked = this.bar.isMarked(this.frame, r.key);
386
+ marked ? rowEl.dataset.marked = "" : delete rowEl.dataset.marked, rowEl.setAttribute("aria-checked", marked ? "true" : "false");
387
+ }
388
+ }
389
+ updateEmpty() {
390
+ let f = this.frame, empty = f.itemRows.length === 0;
391
+ if (this.scroller.hidden = empty && !this.detailEl, !empty || f.loading > 0 && !f.error) {
392
+ this.emptyEl.hidden = !0;
393
+ return;
394
+ }
395
+ let view = f.view, icon = "search", title = this.bar.t("noResults"), desc = f.query ? this.bar.t("nothingMatches", { query: f.query }) : null;
396
+ f.error ? (icon = "alert", title = this.bar.t("loadFailed"), desc = f.error) : view.emptyView ? (icon = view.emptyView.icon ?? icon, title = view.emptyView.title, desc = view.emptyView.description ?? null) : f.view.type === "root" && !f.query && (title = this.bar.t("startTyping"), desc = null), this.emptyEl.replaceChildren(
397
+ renderIcon(icon, 28) ?? "",
398
+ h("div", { class: "qb-empty-title" }, title),
399
+ desc ? h("div", { class: "qb-empty-desc" }, desc) : ""
400
+ ), this.emptyEl.hidden = !1;
401
+ }
402
+ updateDetail() {
403
+ let pane = this.detailEl;
404
+ if (!pane) return;
405
+ let item = this.bar.selectedItem(this.frame);
406
+ if (item === this.detailFor) return;
407
+ if (this.detailFor = item, !item?.detail) {
408
+ pane.innerHTML = item?.description ? this.bar.md(item.description) : "";
409
+ return;
410
+ }
411
+ let value = detailCache.get(item);
412
+ if (value === void 0) {
413
+ let d = item.detail;
414
+ value = typeof d == "function" ? Promise.resolve(d()) : d, detailCache.set(item, value);
415
+ }
416
+ typeof value == "string" ? pane.innerHTML = this.bar.md(value) : (pane.innerHTML = "", value.then(
417
+ (md) => {
418
+ detailCache.set(item, md), this.detailFor === item && (pane.innerHTML = this.bar.md(md));
419
+ },
420
+ (err) => {
421
+ this.detailFor === item && (pane.textContent = String(err?.message ?? err));
422
+ }
423
+ ));
424
+ }
425
+ select(index, scroll = !0) {
426
+ let n = this.frame.itemRows.length;
427
+ n && (this.frame.selected = (index % n + n) % n, this.frame.selectedKey = this.frame.itemRows[this.frame.selected].key, this.frame.userMoved = !0, scroll && this.ensureVisible(), this.updateSelection(), this.bar.invalidate());
428
+ }
429
+ move(delta) {
430
+ let n = this.frame.itemRows.length;
431
+ if (!n) return;
432
+ let next = this.frame.selected + delta;
433
+ this.select(Math.abs(delta) === 1 ? next : Math.max(0, Math.min(n - 1, next)));
434
+ }
435
+ ensureVisible() {
436
+ let f = this.frame, row = f.itemRows[f.selected];
437
+ if (!row) return;
438
+ let rowIndex = f.rows.indexOf(row), prev = f.rows[rowIndex - 1], top, bottom;
439
+ if (this.virtual)
440
+ top = this.offsets[rowIndex], bottom = top + this.rowHeight, prev?.kind === "section" && (top = this.offsets[rowIndex - 1]);
441
+ else {
442
+ let el = this.cache.get(row.key)?.el;
443
+ if (!el) return;
444
+ if (top = el.offsetTop, bottom = top + el.offsetHeight, prev?.kind === "section") {
445
+ let sec = this.cache.get(prev.key)?.el;
446
+ sec && (top = sec.offsetTop);
447
+ }
448
+ }
449
+ let pad = 8, s = this.scroller;
450
+ f.selected === 0 ? s.scrollTop = 0 : top < s.scrollTop + pad ? s.scrollTop = top - pad : bottom > s.scrollTop + s.clientHeight - pad && (s.scrollTop = bottom - s.clientHeight + pad), this.virtual && this.renderWindow();
451
+ }
452
+ onKey(e) {
453
+ let k = e.key, mod = e.metaKey || e.ctrlKey;
454
+ if ((k === "ArrowDown" || k === "ArrowUp") && e.shiftKey && !mod && this.bar.isMulti(this.frame)) {
455
+ let current = this.frame.itemRows[this.frame.selected]?.item;
456
+ current && this.bar.toggleMark(this.frame, current, !0), this.move(k === "ArrowDown" ? 1 : -1);
457
+ let next = this.frame.itemRows[this.frame.selected]?.item;
458
+ return next && this.bar.toggleMark(this.frame, next, !0), !0;
459
+ }
460
+ if (k === "ArrowDown" && mod) return this.select(this.frame.itemRows.length - 1), !0;
461
+ if (k === "ArrowUp" && mod) return this.select(0), !0;
462
+ let emacs = e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey;
463
+ if (k === "ArrowDown" || emacs && (k === "n" || k === "j")) return this.move(1), !0;
464
+ if (k === "ArrowUp" || emacs && k === "p") return this.move(-1), !0;
465
+ if (k === "PageDown") return this.move(8), !0;
466
+ if (k === "PageUp") return this.move(-8), !0;
467
+ if (k === "Enter" && !mod && !e.altKey)
468
+ return this.bar.runPrimary(this.frame), !0;
469
+ if (k === "Tab" && !e.shiftKey && !mod && !e.altKey) {
470
+ let item = this.bar.selectedItem(this.frame);
471
+ if (item?.arguments?.length) {
472
+ let act = this.bar.actionsFor(item, this.frame)[0];
473
+ return act && this.bar.runAction(this.frame, item, act), !0;
474
+ }
475
+ return this.frame.view.type === "root" && this.bar.ai && this.bar.ask(this.frame.query), !0;
476
+ }
477
+ return !1;
478
+ }
479
+ scrollTop() {
480
+ return this.scroller.scrollTop;
481
+ }
482
+ restoreScroll(top) {
483
+ this.scroller.scrollTop = top, this.virtual && this.renderWindow();
484
+ }
485
+ resetScroll() {
486
+ this.scroller.scrollTop = 0;
487
+ }
488
+ destroy() {
489
+ cancelAnimationFrame(this.rafId), this.press && clearTimeout(this.press.timer);
490
+ }
491
+ };
492
+ function sameKeys(a, b) {
493
+ if (a.length !== b.length) return !1;
494
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return !1;
495
+ return !0;
496
+ }
497
+ function bisect(offsets, y) {
498
+ let lo = 0, hi = offsets.length - 1;
499
+ for (; lo < hi; ) {
500
+ let mid = lo + hi + 1 >> 1;
501
+ offsets[mid] <= y ? lo = mid : hi = mid - 1;
502
+ }
503
+ return lo;
504
+ }
505
+ var GridRenderer = class extends ListRenderer {
506
+ constructor(bar, frame) {
507
+ super(bar, frame);
508
+ let v = frame.view;
509
+ this.scroller.className = bar.cls("qb-scroll qb-grid", "grid"), this.scroller.style.setProperty("--qb-columns", String(v.columns ?? 5)), v.aspectRatio && this.scroller.style.setProperty("--qb-aspect", v.aspectRatio), v.fit && this.scroller.style.setProperty("--qb-fit", v.fit), this.inner.style.display = "contents";
510
+ }
511
+ update() {
512
+ let rows = this.frame.rows.slice(0, 600), keys = rows.map((r) => r.key), els = rows.map((r) => this.rowEl(r));
513
+ sameKeys(keys, this.renderedKeys) || (this.inner.replaceChildren(...els), this.renderedKeys = keys), this.updateSelection(), this.updateEmpty();
514
+ }
515
+ itemEl(row) {
516
+ let { item } = row, media = h("div", { class: "qb-cell-media" });
517
+ if (item.image) media.append(h("img", { src: item.image, alt: "", loading: "lazy", decoding: "async", draggable: "false" }));
518
+ else {
519
+ let icon = renderIcon(item.icon, 28);
520
+ icon && media.append(icon);
521
+ }
522
+ return h(
523
+ "div",
524
+ { class: this.bar.cls("qb-cell", "item"), role: "option", id: optionId(this.bar, row.key), "aria-selected": "false", "data-index": String(row.index), title: item.title },
525
+ this.bar.isMulti(this.frame) ? h("span", { class: "qb-check", "aria-hidden": "true" }, renderIcon("check", 12)) : null,
526
+ media,
527
+ h("div", { class: "qb-cell-title" }, highlight(item.title, row.positions)),
528
+ item.subtitle ? h("div", { class: "qb-cell-subtitle" }, item.subtitle) : null
529
+ );
530
+ }
531
+ ensureVisible() {
532
+ let row = this.frame.itemRows[this.frame.selected];
533
+ (row && this.cache.get(row.key)?.el)?.scrollIntoView({ block: "nearest" });
534
+ }
535
+ onKey(e) {
536
+ let cols = this.frame.view.columns ?? 5;
537
+ return e.key === "ArrowRight" && !e.metaKey && !e.ctrlKey ? (this.move(1), !0) : e.key === "ArrowLeft" && !e.metaKey && !e.ctrlKey ? (this.move(-1), !0) : e.key === "ArrowDown" && !e.metaKey && !e.ctrlKey ? (this.step(cols), !0) : e.key === "ArrowUp" && !e.metaKey && !e.ctrlKey ? (this.step(-cols), !0) : super.onKey(e);
538
+ }
539
+ step(delta) {
540
+ let n = this.frame.itemRows.length, next = this.frame.selected + delta;
541
+ next >= 0 && next < n && this.select(next);
542
+ }
543
+ }, DetailRenderer = class {
544
+ constructor(bar, frame) {
545
+ __publicField(this, "bar", bar);
546
+ __publicField(this, "frame", frame);
547
+ __publicField(this, "el");
548
+ __publicField(this, "hasInput", !1);
549
+ __publicField(this, "body");
550
+ __publicField(this, "rendered", "");
551
+ __publicField(this, "raf", 0);
552
+ let v = frame.view;
553
+ this.body = h("div", { class: bar.cls("qb-detail qb-md", "detail"), tabindex: "-1" });
554
+ let children = [this.body];
555
+ v.metadata?.length && children.push(
556
+ h(
557
+ "div",
558
+ { class: "qb-meta" },
559
+ ...v.metadata.map(
560
+ (m) => h(
561
+ "div",
562
+ null,
563
+ h("div", { class: "qb-meta-label" }, m.label),
564
+ h(
565
+ "div",
566
+ { class: "qb-meta-value" },
567
+ renderIcon(m.icon, 14),
568
+ m.tag ? renderTag(m.tag) : null,
569
+ m.href ? h("a", { href: m.href, target: /^https?:/.test(m.href) ? "_blank" : null, rel: "noopener" }, m.value ?? m.href) : m.value ?? null
570
+ )
571
+ )
572
+ )
573
+ )
574
+ ), this.el = h("div", { style: "display:flex;flex:1;min-width:0" }, ...children);
575
+ }
576
+ update() {
577
+ this.raf || (this.raf = requestAnimationFrame(() => {
578
+ this.raf = 0, this.render();
579
+ }));
580
+ }
581
+ render() {
582
+ let d = this.frame.detail;
583
+ if (!d) return;
584
+ let key = `${d.text.length}|${d.done}|${d.error ?? ""}`;
585
+ if (key === this.rendered) return;
586
+ this.rendered = key;
587
+ let stick = this.body.scrollTop + this.body.clientHeight >= this.body.scrollHeight - 24, html = this.bar.md(d.text);
588
+ d.done || (html += '<span class="qb-caret"></span>'), d.error && (html += `<p class="qb-msg-error">${d.error.replace(/</g, "&lt;")}</p>`), this.body.innerHTML = html, stick && !d.done && (this.body.scrollTop = this.body.scrollHeight);
589
+ }
590
+ onKey(e) {
591
+ return e.key === "ArrowDown" ? (this.body.scrollTop += 40, !0) : e.key === "ArrowUp" ? (this.body.scrollTop -= 40, !0) : e.key === "Enter" && !e.metaKey && !e.ctrlKey ? (this.bar.runPrimary(this.frame), !0) : !1;
592
+ }
593
+ viewActions() {
594
+ let d = this.frame.detail;
595
+ return [
596
+ {
597
+ title: this.bar.t("copyContent"),
598
+ icon: "copy",
599
+ shortcut: "mod+shift+c",
600
+ keepOpen: !0,
601
+ run: async (ctx) => {
602
+ let ok = await ctx.copy(d?.text ?? "");
603
+ return ctx.toast({ title: ok ? this.bar.t("copied") : this.bar.t("copyFailed"), style: ok ? "success" : "failure" }), !1;
604
+ }
605
+ }
606
+ ];
607
+ }
608
+ focusTarget() {
609
+ return this.body;
610
+ }
611
+ scrollTop() {
612
+ return this.body.scrollTop;
613
+ }
614
+ restoreScroll(top) {
615
+ this.body.scrollTop = top;
616
+ }
617
+ destroy() {
618
+ cancelAnimationFrame(this.raf);
619
+ }
620
+ }, FormRenderer = class {
621
+ constructor(bar, frame) {
622
+ __publicField(this, "bar", bar);
623
+ __publicField(this, "frame", frame);
624
+ __publicField(this, "el");
625
+ __publicField(this, "hasInput", !1);
626
+ __publicField(this, "inputs", /* @__PURE__ */ new Map());
627
+ __publicField(this, "errors", /* @__PURE__ */ new Map());
628
+ let v = frame.view, children = [];
629
+ for (let field of v.fields) {
630
+ let id = `${bar.instanceId}-f-${field.name}`, label = h("label", { class: "qb-form-label", for: id, "data-required": field.required ? "" : null }, field.type === "checkbox" ? "" : field.label ?? field.name), control = this.control(field, id), error = h("div", { class: "qb-field-error", hidden: !0, id: `${id}-err` });
631
+ this.errors.set(field.name, error), children.push(label, h("div", { class: "qb-field" }, control, field.description ? h("div", { class: "qb-field-desc" }, field.description) : null, error));
632
+ }
633
+ this.el = h("form", { class: bar.cls("qb-form", "form"), novalidate: !0 }, ...children), this.el.addEventListener("submit", (e) => {
634
+ e.preventDefault(), this.submit();
635
+ });
636
+ }
637
+ control(field, id) {
638
+ let values = this.frame.form.values, set = (value) => {
639
+ values[field.name] = value, this.frame.form.errors[field.name] && (delete this.frame.form.errors[field.name], this.showErrors());
640
+ }, el;
641
+ if (field.type === "checkbox") {
642
+ let input = h("input", { type: "checkbox", id, checked: !!values[field.name] });
643
+ return input.addEventListener("change", () => set(input.checked)), this.inputs.set(field.name, input), h("label", { class: "qb-field-check" }, input, h("span", null, field.label ?? field.name));
644
+ }
645
+ if (field.type === "select") {
646
+ let select = h("select", { class: "qb-field-input", id }, ...(field.options ?? []).map((o) => h("option", { value: o.value }, o.title)));
647
+ select.value = String(values[field.name] ?? ""), select.addEventListener("change", () => set(select.value)), el = select;
648
+ } else if (field.type === "textarea") {
649
+ let ta = h("textarea", { class: "qb-field-input", id, placeholder: field.placeholder ?? "", rows: 4 });
650
+ ta.value = String(values[field.name] ?? ""), ta.addEventListener("input", () => set(ta.value)), el = ta;
651
+ } else {
652
+ let input = h("input", {
653
+ class: "qb-field-input",
654
+ id,
655
+ type: field.type ?? "text",
656
+ placeholder: field.placeholder ?? "",
657
+ autocomplete: field.type === "password" ? "off" : "on",
658
+ spellcheck: "false"
659
+ });
660
+ input.value = String(values[field.name] ?? ""), input.addEventListener("input", () => set(field.type === "number" ? input.value === "" ? "" : Number(input.value) : input.value)), el = input;
661
+ }
662
+ return el.setAttribute("aria-describedby", `${id}-err`), this.inputs.set(field.name, el), el;
663
+ }
664
+ showErrors() {
665
+ let errs = this.frame.form.errors;
666
+ for (let [name, el] of this.errors) {
667
+ let msg = errs[name];
668
+ el.hidden = !msg, el.textContent = msg ?? "", this.inputs.get(name)?.setAttribute("aria-invalid", msg ? "true" : "false");
669
+ }
670
+ }
671
+ submit() {
672
+ let v = this.frame.view, form = this.frame.form;
673
+ form.errors = {};
674
+ for (let f of v.fields) {
675
+ let value = form.values[f.name];
676
+ if (f.required && (value === "" || value == null || value === !1)) form.errors[f.name] = this.bar.t("fieldRequired", { field: f.label ?? f.name });
677
+ else {
678
+ let msg = f.validate?.(value, form.values);
679
+ msg && (form.errors[f.name] = msg);
680
+ }
681
+ }
682
+ this.showErrors();
683
+ let first = Object.keys(form.errors)[0];
684
+ if (first) {
685
+ this.inputs.get(first)?.focus();
686
+ return;
687
+ }
688
+ this.bar.runAction(this.frame, void 0, {
689
+ title: v.submitLabel ?? this.bar.t("submit"),
690
+ run: (ctx) => v.onSubmit({ ...form.values }, ctx)
691
+ });
692
+ }
693
+ update() {
694
+ }
695
+ onKey(e) {
696
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey))
697
+ return this.submit(), !0;
698
+ let t = e.target;
699
+ return e.key === "Enter" && t.tagName === "INPUT" && t.type !== "checkbox" ? (this.submit(), !0) : !1;
700
+ }
701
+ footerPrimary() {
702
+ return { title: this.frame.view.submitLabel ?? this.bar.t("submit"), hotkey: "mod+enter", run: () => this.submit() };
703
+ }
704
+ focusTarget() {
705
+ return this.el.contains(document.activeElement) ? document.activeElement : this.el.querySelector("input,textarea,select") ?? this.el;
706
+ }
707
+ scrollTop() {
708
+ return this.el.scrollTop;
709
+ }
710
+ restoreScroll(top) {
711
+ this.el.scrollTop = top;
712
+ }
713
+ destroy() {
714
+ }
715
+ }, ChatRenderer = class {
716
+ constructor(bar, frame) {
717
+ __publicField(this, "bar", bar);
718
+ __publicField(this, "frame", frame);
719
+ __publicField(this, "el");
720
+ __publicField(this, "hasInput", !0);
721
+ __publicField(this, "turnEls", []);
722
+ __publicField(this, "emptyEl");
723
+ __publicField(this, "raf", 0);
724
+ this.el = h("div", { class: bar.cls("qb-chat", "chat"), role: "log", "aria-live": "polite", tabindex: "-1" });
725
+ }
726
+ update() {
727
+ this.raf || (this.raf = requestAnimationFrame(() => {
728
+ this.raf = 0, this.render();
729
+ }));
730
+ }
731
+ render() {
732
+ let turns = this.frame.chat?.turns ?? [];
733
+ if (!turns.length) {
734
+ this.emptyEl || (this.emptyEl = this.empty(), this.el.replaceChildren(this.emptyEl));
735
+ return;
736
+ }
737
+ this.emptyEl && (this.emptyEl.remove(), this.emptyEl = void 0);
738
+ let stick = this.el.scrollTop + this.el.clientHeight >= this.el.scrollHeight - 40;
739
+ turns.forEach((turn, i) => {
740
+ let sig = `${turn.text.length}|${turn.streaming}|${turn.error ?? ""}|${turn.tools.map((t) => t.state).join()}`, existing = this.turnEls[i];
741
+ if (existing && existing.sig === sig) return;
742
+ let el;
743
+ if (turn.role === "user") el = h("div", { class: "qb-msg-user" }, turn.text);
744
+ else {
745
+ let head = h("div", { class: "qb-msg-head" }, renderIcon("sparkles", 13), this.bar.aiName), tools = turn.tools.length ? h(
746
+ "div",
747
+ { class: "qb-tools" },
748
+ ...turn.tools.map((t) => {
749
+ let icon = renderIcon(t.state === "running" ? "loader" : t.state === "done" ? "check" : "x", 12);
750
+ return t.state === "running" && icon.classList.add("qb-spin"), h("span", { class: "qb-tool", "data-state": t.state }, icon, t.label);
751
+ })
752
+ ) : null, md = h("div", { class: "qb-md" }), html = this.bar.md(turn.text);
753
+ turn.streaming && (html += turn.text || !turn.tools.length ? '<span class="qb-caret"></span>' : ""), md.innerHTML = html, el = h("div", { class: "qb-msg-ai" }, head, tools, md, turn.error ? h("div", { class: "qb-msg-error" }, turn.error) : null);
754
+ }
755
+ existing ? existing.el.replaceWith(el) : this.el.append(el), this.turnEls[i] = { el, sig };
756
+ }), stick && (this.el.scrollTop = this.el.scrollHeight);
757
+ }
758
+ empty() {
759
+ let suggestions = this.bar.aiOptions?.suggestions ?? [], defaults = suggestions.length ? suggestions : this.bar.t("chatSuggestions").split("|");
760
+ return h(
761
+ "div",
762
+ { class: "qb-chat-empty" },
763
+ renderIcon("sparkles", 26),
764
+ h("div", { class: "qb-empty-title" }, this.bar.t("askAnything")),
765
+ h("div", { class: "qb-empty-desc" }, this.bar.t("chatHint")),
766
+ h(
767
+ "div",
768
+ { class: "qb-suggestions" },
769
+ ...defaults.map((s) => {
770
+ let b = h("button", { class: "qb-suggestion", type: "button" }, s);
771
+ return b.addEventListener("click", () => this.bar.sendChat(this.frame, s)), b;
772
+ })
773
+ )
774
+ );
775
+ }
776
+ lastAnswer() {
777
+ let turns = this.frame.chat?.turns ?? [];
778
+ for (let i = turns.length - 1; i >= 0; i--) if (turns[i].role === "assistant" && turns[i].text) return turns[i].text;
779
+ return "";
780
+ }
781
+ onKey(e) {
782
+ if (e.key === "Enter" && !e.shiftKey && !e.metaKey && !e.ctrlKey && !e.altKey) {
783
+ let q = this.frame.query.trim();
784
+ return q && this.bar.sendChat(this.frame, q), !0;
785
+ }
786
+ return e.key === "ArrowUp" && !this.frame.query ? (this.el.scrollTop -= 60, !0) : e.key === "ArrowDown" && !this.frame.query ? (this.el.scrollTop += 60, !0) : !1;
787
+ }
788
+ placeholder() {
789
+ return this.frame.chat?.turns.length ?? 0 ? this.bar.t("followUp") : this.bar.t("askAnythingPlaceholder");
790
+ }
791
+ footerPrimary() {
792
+ return this.frame.chat?.controller ? { title: this.bar.t("stop"), hotkey: "escape", run: () => {
793
+ this.bar.stopChat(this.frame);
794
+ } } : { title: this.bar.t("send"), hotkey: "enter", run: () => this.bar.sendChat(this.frame, this.frame.query) };
795
+ }
796
+ viewActions() {
797
+ let view = this.frame.view;
798
+ return [
799
+ {
800
+ title: this.bar.t("copyAnswer"),
801
+ icon: "copy",
802
+ shortcut: "mod+shift+c",
803
+ keepOpen: !0,
804
+ run: async (ctx) => {
805
+ let ok = await copyText(this.lastAnswer());
806
+ return ctx.toast({ title: ok ? this.bar.t("copiedAnswer") : this.bar.t("nothingToCopy"), style: ok ? "success" : "failure" }), !1;
807
+ }
808
+ },
809
+ {
810
+ title: this.bar.t("newChat"),
811
+ icon: "plus",
812
+ shortcut: "mod+shift+o",
813
+ run: (ctx) => (ctx.render({ ...view, type: "chat", prompt: void 0 }), !1)
814
+ }
815
+ ];
816
+ }
817
+ scrollTop() {
818
+ return this.el.scrollTop;
819
+ }
820
+ restoreScroll(top) {
821
+ this.el.scrollTop = top;
822
+ }
823
+ destroy() {
824
+ cancelAnimationFrame(this.raf);
825
+ }
826
+ };
827
+
828
+ // src/ui/bar.ts
829
+ var VIEW_TYPES = /* @__PURE__ */ new Set(["list", "grid", "detail", "form", "chat"]), isView = (x) => !!x && typeof x == "object" && VIEW_TYPES.has(x.type), DEFAULT_LINKS = "nav a[href], header a[href], aside a[href], [data-qikbar-index] a[href]", DEFAULT_ACTIONS_HOTKEY = "mod+.", toolName = (s) => s.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64), frameCounter = 0, Bar = class {
830
+ constructor(config = {}) {
831
+ __publicField(this, "config");
832
+ __publicField(this, "instanceId", uid("qikbar"));
833
+ __publicField(this, "storageAdapter");
834
+ __publicField(this, "storage");
835
+ __publicField(this, "frecency");
836
+ __publicField(this, "registrations", /* @__PURE__ */ new Map());
837
+ __publicField(this, "regCounter", 0);
838
+ __publicField(this, "sources", /* @__PURE__ */ new Set());
839
+ __publicField(this, "sourceExt", /* @__PURE__ */ new WeakMap());
840
+ __publicField(this, "itemExt", /* @__PURE__ */ new WeakMap());
841
+ __publicField(this, "extensions", /* @__PURE__ */ new Map());
842
+ __publicField(this, "configExtensions", []);
843
+ __publicField(this, "configSources", []);
844
+ __publicField(this, "ids", /* @__PURE__ */ new WeakMap());
845
+ __publicField(this, "listeners", /* @__PURE__ */ new Map());
846
+ __publicField(this, "stack", []);
847
+ __publicField(this, "_open", !1);
848
+ __publicField(this, "rootCache", null);
849
+ __publicField(this, "routeItems", []);
850
+ __publicField(this, "autoItems", []);
851
+ __publicField(this, "shortcutItems", []);
852
+ __publicField(this, "aiOptions");
853
+ __publicField(this, "ai");
854
+ __publicField(this, "dom");
855
+ __publicField(this, "renderer");
856
+ __publicField(this, "panel");
857
+ __publicField(this, "toastState");
858
+ __publicField(this, "toastTimer");
859
+ __publicField(this, "toastId", 0);
860
+ __publicField(this, "hud");
861
+ __publicField(this, "confirmState");
862
+ __publicField(this, "argMode");
863
+ __publicField(this, "seq", new SequenceMatcher());
864
+ __publicField(this, "prevFocus", null);
865
+ __publicField(this, "teardown", []);
866
+ __publicField(this, "appliedVars", []);
867
+ __publicField(this, "scheduled", !1);
868
+ __publicField(this, "scrollLock");
869
+ __publicField(this, "closeTimer");
870
+ __publicField(this, "destroyed", !1);
871
+ __publicField(this, "styleEl");
872
+ __publicField(this, "searchEventTimer");
873
+ __publicField(this, "webmcpCleanup");
874
+ __publicField(this, "labelCache");
875
+ // ─── Semantic search ─────────────────────────────────────────────────────
876
+ __publicField(this, "vectors", /* @__PURE__ */ new Map());
877
+ __publicField(this, "semanticWarned", !1);
878
+ // ─── Keyboard ────────────────────────────────────────────────────────────
879
+ __publicField(this, "onGlobalKeyDown", (e) => {
880
+ if (this.destroyed || e.defaultPrevented || e.isComposing) return;
881
+ let hotkeys = this.config.hotkey === !1 ? [] : [].concat(this.config.hotkey ?? "mod+k"), inField = isEditable(e.target);
882
+ if (hotkeys.some((hk) => matchesHotkey(e, hk) && (!inField || allowedInInput(hk)))) {
883
+ e.preventDefault(), e.stopPropagation(), this.isInline ? (this.open(), this.focusInput()) : this.toggle();
884
+ return;
885
+ }
886
+ if (this._open && !this.isInline || this.isInline && this.dom?.root.contains(e.target)) return;
887
+ let ta = this.toastState?.act;
888
+ if (ta?.shortcut && !inField && matchesHotkey(e, ta.shortcut)) {
889
+ e.preventDefault(), this.runToastAction();
890
+ return;
891
+ }
892
+ if (this.config.shortcuts === !1 || (this.rootItems(), !this.shortcutItems.length)) return;
893
+ let candidates = this.shortcutItems.map((i) => i.shortcut).filter((s) => !inField || allowedInInput(s)), matched = this.seq.feed(e, candidates);
894
+ if (!matched.length) return;
895
+ let item = this.shortcutItems.find((i) => i.shortcut === matched[0]);
896
+ if (!item) return;
897
+ e.preventDefault();
898
+ let frame = this.createFrame({ type: "root" }), act = this.actionsFor(item, frame)[0];
899
+ act && this.runAction(frame, item, act, void 0, "shortcut");
900
+ });
901
+ __publicField(this, "onGlobalClick", (e) => {
902
+ let trigger = e.target?.closest?.("[data-qikbar-open]");
903
+ if (!trigger || this.destroyed) return;
904
+ let target = trigger.getAttribute("data-qikbar-open");
905
+ (target ? target !== this.instanceId && target !== this.config.namespace : this.isInline) || (e.preventDefault(), this.open({ query: trigger.getAttribute("data-qikbar-query") ?? void 0 }));
906
+ });
907
+ __publicField(this, "onDialogKeyDown", (e) => {
908
+ if (e.stopPropagation(), e.isComposing || e.keyCode === 229) return;
909
+ let frame = this.top;
910
+ if (!frame) return;
911
+ if (this.confirmState) {
912
+ if (e.key === "Escape")
913
+ e.preventDefault(), this.confirmState.resolve(!1);
914
+ else if (e.key === "Tab") {
915
+ let buttons = [...this.dom?.layer.querySelectorAll("button") ?? []], i = buttons.indexOf(document.activeElement);
916
+ e.preventDefault(), buttons[(i + (e.shiftKey ? -1 : 1) + buttons.length) % buttons.length]?.focus();
917
+ }
918
+ e.stopPropagation();
919
+ return;
920
+ }
921
+ let ta = this.toastState?.act;
922
+ if (ta?.shortcut && matchesHotkey(e, ta.shortcut) && !(isEditable(e.target) && e.target.value)) {
923
+ e.preventDefault(), this.runToastAction();
924
+ return;
925
+ }
926
+ if (this.panel) {
927
+ this.onPanelKey(e) && (e.preventDefault(), e.stopPropagation());
928
+ return;
929
+ }
930
+ if (this.argMode) {
931
+ if (e.key === "Escape") {
932
+ e.preventDefault(), e.stopPropagation(), this.argMode = void 0, this.flush(), this.focusInput();
933
+ return;
934
+ }
935
+ if (e.key === "Enter") {
936
+ e.preventDefault(), this.submitArgs();
937
+ return;
938
+ }
939
+ return;
940
+ }
941
+ if (e.key === "Escape") {
942
+ e.preventDefault(), e.stopPropagation(), this.escape();
943
+ return;
944
+ }
945
+ if (matchesHotkey(e, this.actionsHotkey)) {
946
+ e.preventDefault(), this.openPanel();
947
+ return;
948
+ }
949
+ if (this.renderer?.onKey(e)) {
950
+ e.preventDefault();
951
+ return;
952
+ }
953
+ let actions = this.actionsFor(this.selectedItem(frame), frame);
954
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && frame.view.type !== "form") {
955
+ let second = actions[1];
956
+ if (second && !second.shortcut) {
957
+ e.preventDefault(), this.runAction(frame, this.selectedItem(frame), second);
958
+ return;
959
+ }
960
+ }
961
+ for (let act of actions)
962
+ if (act.shortcut && matchesHotkey(e, act.shortcut)) {
963
+ e.preventDefault(), this.runAction(frame, this.selectedItem(frame), act);
964
+ return;
965
+ }
966
+ e.key === "Backspace" && this.stack.length > 1 && e.target === this.dom?.input && !this.dom.input.value && !e.repeat && (e.preventDefault(), this.pop());
967
+ });
968
+ if (this.config = { ...config }, this.storageAdapter = config.storage ?? defaultStorage(), this.storage = scopedStorage(this.storageAdapter, config.namespace ?? "qikbar"), this.frecency = new Frecency(this.storage), this.applyConfig(config, !0), !(typeof document > "u") && (this.listen(document, "keydown", this.onGlobalKeyDown, !0), this.listen(document, "click", this.onGlobalClick, !0), this.applyWebMCP(), this.inlineTarget())) {
969
+ let start = () => this.open({ focus: !1 });
970
+ document.readyState === "loading" ? this.listen(document, "DOMContentLoaded", start) : start();
971
+ }
972
+ }
973
+ // ─── Public API ──────────────────────────────────────────────────────────
974
+ get isOpen() {
975
+ return this._open;
976
+ }
977
+ get query() {
978
+ return this.top?.query ?? "";
979
+ }
980
+ get top() {
981
+ return this.stack[this.stack.length - 1];
982
+ }
983
+ get isInline() {
984
+ return !!this.config.inline;
985
+ }
986
+ /** Touch-friendly mode: no keyboard hints, long-press for actions, bigger targets. */
987
+ get isTouch() {
988
+ let t = this.config.touch ?? "auto";
989
+ return t !== "auto" ? t : typeof matchMedia < "u" && matchMedia("(hover: none) and (pointer: coarse)").matches;
990
+ }
991
+ applyTouch() {
992
+ let root = this.dom?.root;
993
+ root && (this.isTouch ? root.dataset.qbTouch = "" : delete root.dataset.qbTouch);
994
+ }
995
+ /** Track the visible viewport so the bar stays above the on-screen keyboard. */
996
+ watchViewport() {
997
+ let vv = typeof window < "u" ? window.visualViewport : void 0;
998
+ if (!vv || this.isInline) return;
999
+ let update = () => {
1000
+ this._open && this.dom && this.dom.root.style.setProperty("--qb-vvh", `${Math.round(vv.height)}px`);
1001
+ };
1002
+ vv.addEventListener("resize", update), vv.addEventListener("scroll", update), this.teardown.push(() => {
1003
+ vv.removeEventListener("resize", update), vv.removeEventListener("scroll", update);
1004
+ }), update();
1005
+ }
1006
+ get aiName() {
1007
+ return this.aiOptions?.name ?? "AI";
1008
+ }
1009
+ get actionsHotkey() {
1010
+ return this.config.actionsHotkey ?? DEFAULT_ACTIONS_HOTKEY;
1011
+ }
1012
+ /** The active labels (English merged with `config.labels`). */
1013
+ get labels() {
1014
+ let src = this.config.labels;
1015
+ return (!this.labelCache || this.labelCache.src !== src) && (this.labelCache = { src, labels: src ? { ...en, ...src } : en }), this.labelCache.labels;
1016
+ }
1017
+ /** A translated label with `{placeholders}` filled in. `{ai}` is always available. */
1018
+ t(key, vars = {}) {
1019
+ return format(this.labels[key], { ai: this.aiName, ...vars });
1020
+ }
1021
+ /** Title of an action, translated when it's an untouched built-in. */
1022
+ actionTitle(act) {
1023
+ return act.labelKey && act.title === en[act.labelKey] ? this.t(act.labelKey) : act.title;
1024
+ }
1025
+ open(options = {}) {
1026
+ if (this.destroyed || typeof document > "u") return;
1027
+ if (this.mount(), clearTimeout(this.closeTimer), !this._open) {
1028
+ this._open = !0, this.prevFocus = document.activeElement, this.rootCache = null, this.autoIndex(), this.resetToRoot(), this.applyTheme();
1029
+ let dom = this.dom;
1030
+ dom.root.dataset.qbState = "open";
1031
+ let vv = typeof window < "u" ? window.visualViewport : void 0;
1032
+ vv && !this.isInline && dom.root.style.setProperty("--qb-vvh", `${Math.round(vv.height)}px`), dom.overlay.hidden = this.isInline, dom.dialog.hidden = !1, this.isInline || this.lockScroll(), this.emit("open", void 0), this.config.onOpen?.(), this.track({ type: "open" });
1033
+ }
1034
+ options.view && this.push(options.view), options.query != null && this.setQuery(options.query), this.flush(), options.focus !== !1 && this.focusInput(), this.emitChange();
1035
+ }
1036
+ close() {
1037
+ if (!this._open || !this.dom) return;
1038
+ if (this.closePanel(), this.confirmState?.resolve(!1), this.confirmState = void 0, this.argMode = void 0, this.isInline) {
1039
+ this.resetToRoot(), this.flush(), document.activeElement?.blur?.(), this.emitChange();
1040
+ return;
1041
+ }
1042
+ this._open = !1;
1043
+ let dom = this.dom;
1044
+ dom.root.dataset.qbState = "closing";
1045
+ let finish = () => {
1046
+ if (!this._open) {
1047
+ dom.root.dataset.qbState = "closed", dom.dialog.hidden = !0, dom.overlay.hidden = !0, this.renderer?.destroy(), this.renderer = void 0, dom.body.replaceChildren();
1048
+ for (let f of this.stack) this.destroyFrame(f);
1049
+ this.stack = [];
1050
+ }
1051
+ };
1052
+ typeof matchMedia < "u" && matchMedia("(prefers-reduced-motion: reduce)").matches ? finish() : this.closeTimer = setTimeout(finish, 120), this.unlockScroll();
1053
+ let prev = this.prevFocus;
1054
+ prev && typeof prev.focus == "function" && document.contains(prev) && prev.focus({ preventScroll: !0 }), this.toastState && this.renderToast(), this.emit("close", void 0), this.config.onClose?.(), this.track({ type: "close" }), this.emitChange();
1055
+ }
1056
+ toggle() {
1057
+ this._open && !this.isInline ? this.close() : this.open();
1058
+ }
1059
+ register(commands) {
1060
+ let id = ++this.regCounter;
1061
+ return this.registrations.set(id, Array.isArray(commands) ? commands : [commands]), this.invalidateRoot(), () => {
1062
+ this.registrations.delete(id), this.invalidateRoot();
1063
+ };
1064
+ }
1065
+ addSource(source) {
1066
+ return this.sources.add(source), () => {
1067
+ this.sources.delete(source);
1068
+ for (let f of this.stack) f.sourceResults?.delete(source.id);
1069
+ this.invalidate();
1070
+ };
1071
+ }
1072
+ use(ext, provided = {}) {
1073
+ this.extensions.get(ext.name)?.cleanup?.();
1074
+ let storage = scopedStorage(this.storageAdapter, `${this.config.namespace ?? "qikbar"}:ext:${ext.name}`), rt = {
1075
+ ext,
1076
+ provided,
1077
+ storage,
1078
+ prefs: () => {
1079
+ let stored = storage.get("preferences") ?? {}, out = {};
1080
+ for (let p of ext.preferences ?? []) p.default !== void 0 && (out[p.name] = p.default);
1081
+ return { ...out, ...stored, ...provided };
1082
+ },
1083
+ missing: () => {
1084
+ let values = rt.prefs();
1085
+ return (ext.preferences ?? []).filter((p) => p.required && (values[p.name] === void 0 || values[p.name] === ""));
1086
+ }
1087
+ }, items = (ext.commands ?? []).map((cmd) => {
1088
+ let { name, ...rest } = cmd, item = { section: ext.title, icon: ext.icon, ...rest, id: `${ext.name}.${name}` };
1089
+ return this.itemExt.set(item, rt), item;
1090
+ }), removeSources = (ext.sources ?? []).map((s) => (this.sourceExt.set(s, rt), this.addSource(s))), setupCleanup;
1091
+ try {
1092
+ setupCleanup = ext.setup?.({ bar: this, preferences: rt.prefs(), storage });
1093
+ } catch (err) {
1094
+ console.error(`[qikbar] extension "${ext.name}" setup failed`, err);
1095
+ }
1096
+ let disposed = !1, entry = {
1097
+ rt,
1098
+ items,
1099
+ cleanup: () => {
1100
+ disposed || (disposed = !0, removeSources.forEach((r) => r()), typeof setupCleanup == "function" && setupCleanup(), this.extensions.get(ext.name) === entry && this.extensions.delete(ext.name), this.invalidateRoot());
1101
+ }
1102
+ };
1103
+ return this.extensions.set(ext.name, entry), this.invalidateRoot(), entry.cleanup;
1104
+ }
1105
+ configure(partial) {
1106
+ let prev = this.config;
1107
+ this.config = { ...this.config, ...partial }, this.applyConfig(partial, !1, prev), ("webmcp" in partial || "tools" in partial) && this.applyWebMCP(), this.dom && (("theme" in partial || "appearance" in partial) && this.applyTheme(), "classNames" in partial && this.applyClassNames(), "dir" in partial && (this.dom.root.dir = this.config.dir ?? ""), "touch" in partial && this.applyTouch(), "labels" in partial && this.renderer?.refresh?.()), this.invalidateRoot();
1108
+ }
1109
+ push(view, ext) {
1110
+ if (!this._open && (this.open(), !this._open))
1111
+ return;
1112
+ let top = this.top;
1113
+ top && this.renderer && (top.scrollTop = this.renderer.scrollTop());
1114
+ let frame = this.createFrame(view, ext ?? top?.ext);
1115
+ this.stack.push(frame), this.closePanel(), this.argMode = void 0, this.startFrame(frame), this.flush(), this.focusInput(), this.emitChange();
1116
+ }
1117
+ pop() {
1118
+ if (this.stack.length <= 1) return;
1119
+ let frame = this.stack.pop();
1120
+ this.destroyFrame(frame), this.closePanel(), this.argMode = void 0, this.flush(), this.focusInput(), this.emitChange();
1121
+ }
1122
+ setQuery(query) {
1123
+ let frame = this.top;
1124
+ frame && (this.dom && (this.dom.input.value = query), this.onQueryChange(frame, query));
1125
+ }
1126
+ ask(prompt) {
1127
+ if (!this.ai) {
1128
+ this.toast({ style: "failure", title: this.t("aiNotConfigured"), message: "Pass `ai` to createQikbar()." });
1129
+ return;
1130
+ }
1131
+ this.push({ type: "chat", prompt: prompt?.trim() || void 0 });
1132
+ }
1133
+ commands() {
1134
+ return this.rootItems();
1135
+ }
1136
+ // ─── Pins & aliases ──────────────────────────────────────────────────────
1137
+ get personalize() {
1138
+ return this.config.personalize !== !1;
1139
+ }
1140
+ pins() {
1141
+ return this.storage.get("pins") ?? [];
1142
+ }
1143
+ pin(id, pinned = !this.pins().includes(id)) {
1144
+ let list = this.pins().filter((x) => x !== id);
1145
+ pinned && list.unshift(id), this.storage.set("pins", list);
1146
+ let item = this.rootItems().find((i) => this.idOf(i) === id);
1147
+ item && this.track({ type: pinned ? "pin" : "unpin", item: this.eventItem(item) }), this.invalidateRoot();
1148
+ }
1149
+ aliases() {
1150
+ return this.storage.get("aliases") ?? {};
1151
+ }
1152
+ aliasOf(id) {
1153
+ for (let [alias, target] of Object.entries(this.aliases())) if (target === id) return alias;
1154
+ }
1155
+ setAlias(id, alias) {
1156
+ let map = { ...this.aliases() };
1157
+ for (let [k, v] of Object.entries(map)) v === id && delete map[k];
1158
+ let clean = alias == null ? "" : normalizeAlias(alias);
1159
+ clean && (map[clean] = id), this.storage.set("aliases", map);
1160
+ let item = this.rootItems().find((i) => this.idOf(i) === id);
1161
+ item && this.track({ type: "alias", item: this.eventItem(item), alias: clean || null }), this.invalidateRoot();
1162
+ }
1163
+ /** Whether pin/alias actions apply to this item. */
1164
+ personalizable(item, frame) {
1165
+ return !this.personalize || frame.view.type !== "root" || isFallback(item) ? !1 : !this.idOf(item).startsWith("qikbar.") && this.rootItems().includes(item);
1166
+ }
1167
+ aliasForm(item) {
1168
+ let id = this.idOf(item), current = this.aliasOf(id);
1169
+ return {
1170
+ type: "form",
1171
+ title: item.title,
1172
+ submitLabel: this.t("save"),
1173
+ fields: [
1174
+ {
1175
+ name: "alias",
1176
+ label: this.t("alias"),
1177
+ placeholder: this.t("aliasPlaceholder"),
1178
+ description: this.t("aliasDescription", { title: item.title }),
1179
+ required: !0,
1180
+ defaultValue: current ?? "",
1181
+ validate: (value) => {
1182
+ let alias = normalizeAlias(String(value ?? "")), owner = this.aliases()[alias];
1183
+ if (owner && owner !== id) {
1184
+ let other = this.rootItems().find((i) => this.idOf(i) === owner);
1185
+ return this.t("aliasTaken", { alias, title: other?.title ?? owner });
1186
+ }
1187
+ }
1188
+ }
1189
+ ],
1190
+ onSubmit: (values) => {
1191
+ let alias = normalizeAlias(String(values.alias ?? ""));
1192
+ return this.setAlias(id, alias), this.toast({ style: "success", title: this.t("aliasSaved", { alias }) }), this.pop(), !1;
1193
+ }
1194
+ };
1195
+ }
1196
+ on(event, handler) {
1197
+ let set = this.listeners.get(event);
1198
+ return set || this.listeners.set(event, set = /* @__PURE__ */ new Set()), set.add(handler), () => set.delete(handler);
1199
+ }
1200
+ preload() {
1201
+ return Promise.resolve();
1202
+ }
1203
+ destroy() {
1204
+ this.destroyed = !0, this._open && !this.isInline && this.unlockScroll(), this._open = !1;
1205
+ for (let f of this.stack) this.destroyFrame(f);
1206
+ this.stack = [];
1207
+ for (let e of this.extensions.values()) e.cleanup?.();
1208
+ for (let fn of this.teardown) fn();
1209
+ this.teardown = [], this.webmcpCleanup?.(), this.webmcpCleanup = void 0, clearTimeout(this.searchEventTimer), clearTimeout(this.toastTimer), this.dom?.root.remove(), this.hud?.remove(), this.dom = void 0, this.listeners.clear();
1210
+ }
1211
+ // ─── Config ──────────────────────────────────────────────────────────────
1212
+ applyConfig(partial, initial, prev) {
1213
+ if (("routes" in partial || "labels" in partial || initial) && (this.routeItems = (this.config.routes ?? []).map((r) => ({
1214
+ id: `route:${r.path}`,
1215
+ title: r.title,
1216
+ subtitle: r.subtitle,
1217
+ icon: r.icon ?? "arrow-right",
1218
+ keywords: [...r.keywords ?? [], r.path],
1219
+ section: r.section ?? this.t("navigation"),
1220
+ href: r.path,
1221
+ shortcut: r.shortcut
1222
+ }))), ("sources" in partial || initial) && (initial || prev?.sources !== this.config.sources)) {
1223
+ for (let remove of this.configSources) remove();
1224
+ this.configSources = (this.config.sources ?? []).map((src) => this.addSource(src));
1225
+ }
1226
+ if ("ai" in partial || initial) {
1227
+ let ai = this.config.ai;
1228
+ this.aiOptions = ai ? "stream" in ai ? { provider: ai } : ai : void 0, this.ai = this.aiOptions ? createAIClient(this.aiOptions.provider, this.aiOptions.system) : void 0;
1229
+ }
1230
+ if ("extensions" in partial || initial) {
1231
+ let next = (this.config.extensions ?? []).map((e) => Array.isArray(e) ? { ext: e[0], prefs: e[1] } : { ext: e, prefs: void 0 }), sameRef = !initial && prev?.extensions === this.config.extensions, sameContent = next.length === this.configExtensions.length && next.every((n, i) => n.ext === this.configExtensions[i].ext && shallowEqual(n.prefs, this.configExtensions[i].prefs));
1232
+ if (!sameRef && !sameContent) {
1233
+ for (let e of this.configExtensions) e.uninstall();
1234
+ this.configExtensions = next.map((n) => ({ ...n, uninstall: this.use(n.ext, n.prefs) }));
1235
+ }
1236
+ }
1237
+ }
1238
+ applyWebMCP() {
1239
+ this.webmcpCleanup?.(), this.webmcpCleanup = void 0;
1240
+ let opt = this.config.webmcp;
1241
+ !opt || this.destroyed || (this.webmcpCleanup = exposeWebMCP(this, opt === !0 ? {} : opt));
1242
+ }
1243
+ inlineTarget() {
1244
+ let t = this.config.inline;
1245
+ return !t || typeof document > "u" ? null : typeof t == "string" ? document.querySelector(t) : t;
1246
+ }
1247
+ // ─── Events ──────────────────────────────────────────────────────────────
1248
+ emit(event, payload) {
1249
+ this.listeners.get(event)?.forEach((fn) => {
1250
+ try {
1251
+ fn(payload);
1252
+ } catch (err) {
1253
+ console.error(err);
1254
+ }
1255
+ });
1256
+ }
1257
+ emitChange() {
1258
+ let state = { open: this._open, query: this.query, depth: this.stack.length, loading: !!this.top?.loading };
1259
+ this.emit("change", state);
1260
+ }
1261
+ /** Report a usage event to `onEvent` and `on('event')`. */
1262
+ track(event) {
1263
+ try {
1264
+ this.config.onEvent?.(event);
1265
+ } catch (err) {
1266
+ console.error(err);
1267
+ }
1268
+ this.emit("event", event);
1269
+ }
1270
+ eventItem(item) {
1271
+ return { id: this.idOf(item), title: item.title, section: item.section };
1272
+ }
1273
+ /** Report what the user searched for once they stop typing. */
1274
+ scheduleSearchEvent(frame) {
1275
+ clearTimeout(this.searchEventTimer);
1276
+ let q = frame.query.trim();
1277
+ if (!q || !this.config.onEvent && !this.listeners.get("event")?.size) return;
1278
+ let tries = 0, fire = () => {
1279
+ if (frame !== this.top || frame.query.trim() !== q) return;
1280
+ if (frame.loading > 0 && tries++ < 10) {
1281
+ this.searchEventTimer = setTimeout(fire, 300);
1282
+ return;
1283
+ }
1284
+ let results = frame.itemRows.filter((r) => !isFallback(r.item)).length, view = frame.view.type;
1285
+ this.track({ type: "search", query: q, results, view }), results || this.track({ type: "no_results", query: q, view });
1286
+ };
1287
+ this.searchEventTimer = setTimeout(fire, 800);
1288
+ }
1289
+ listen(target, type, fn, capture = !1) {
1290
+ target.addEventListener(type, fn, capture), this.teardown.push(() => target.removeEventListener(type, fn, capture));
1291
+ }
1292
+ // ─── Root items ──────────────────────────────────────────────────────────
1293
+ idOf(item) {
1294
+ return item.id ?? this.ids.get(item) ?? item.title;
1295
+ }
1296
+ invalidateRoot() {
1297
+ if (this.rootCache = null, this._open) {
1298
+ for (let f of this.stack)
1299
+ f.actionCache = void 0, f.view.type === "root" && this.computeRows(f);
1300
+ this.renderer?.refresh?.(), this.invalidate();
1301
+ }
1302
+ }
1303
+ rootItems() {
1304
+ if (this.rootCache) return this.rootCache;
1305
+ let out = [], seen = /* @__PURE__ */ new Set(), add = (item, prefix) => {
1306
+ try {
1307
+ if (item.when && !item.when()) return;
1308
+ } catch {
1309
+ return;
1310
+ }
1311
+ let id = item.id ?? `${prefix}:${item.section ?? ""}:${item.title}`;
1312
+ for (; seen.has(id); ) id += "'";
1313
+ seen.add(id), this.ids.set(item, id), out.push(item);
1314
+ };
1315
+ for (let c of this.config.commands ?? []) add(c, "cmd");
1316
+ for (let c of this.routeItems) add(c, "route");
1317
+ for (let list of this.registrations.values()) for (let c of list) add(c, "reg");
1318
+ for (let e of this.extensions.values()) for (let c of e.items) add(c, "ext");
1319
+ for (let c of this.autoItems) add(c, "auto");
1320
+ return this.ai && this.aiOptions?.fallback !== !1 && add(
1321
+ {
1322
+ id: "qikbar.ask-ai",
1323
+ title: this.t("askAi"),
1324
+ subtitle: this.t("askAiSubtitle"),
1325
+ icon: "sparkles",
1326
+ section: "AI",
1327
+ keywords: ["chat", "assistant", "ai", "help"],
1328
+ searchOnly: !0,
1329
+ view: { type: "chat" }
1330
+ },
1331
+ "qb"
1332
+ ), this.rootCache = out, this.shortcutItems = out.filter((i) => i.shortcut), out;
1333
+ }
1334
+ autoIndex() {
1335
+ let opt = this.config.autoIndex;
1336
+ if (!opt || typeof document > "u") {
1337
+ this.autoItems.length && (this.autoItems = [], this.rootCache = null);
1338
+ return;
1339
+ }
1340
+ let o = opt === !0 ? {} : opt, items = [], seen = /* @__PURE__ */ new Set();
1341
+ if (o.links !== !1)
1342
+ for (let a of document.querySelectorAll(o.links ?? DEFAULT_LINKS)) {
1343
+ if (a.closest(".qb-root") || a.closest("[data-qikbar-ignore]")) continue;
1344
+ let raw = a.getAttribute("href") ?? "";
1345
+ if (!raw || raw.startsWith("#") && !raw.startsWith("#/") || /^(javascript|mailto|tel):/i.test(raw)) continue;
1346
+ let title = (a.getAttribute("aria-label") || a.textContent || a.title || "").replace(/\s+/g, " ").trim().slice(0, 80);
1347
+ if (!title) continue;
1348
+ let external = a.host !== location.host, href = external ? a.href : raw.startsWith("#") ? raw : a.pathname + a.search + a.hash;
1349
+ if (seen.has(href)) continue;
1350
+ seen.add(href);
1351
+ let sectionEl = a.closest("[data-qikbar-section],nav[aria-label],aside[aria-label]");
1352
+ items.push({
1353
+ id: `auto:${href}`,
1354
+ title,
1355
+ subtitle: external ? a.host : raw.startsWith("#") ? raw : a.pathname,
1356
+ section: sectionEl?.dataset.qikbarSection ?? sectionEl?.getAttribute("aria-label") ?? o.section ?? this.t("pages"),
1357
+ icon: external ? "globe" : "file",
1358
+ keywords: [href],
1359
+ ...external ? { url: href } : { href }
1360
+ });
1361
+ }
1362
+ if (o.elements !== !1)
1363
+ for (let el of document.querySelectorAll("[data-qikbar]")) {
1364
+ if (el.closest(".qb-root")) continue;
1365
+ let title = (el.dataset.qikbar || el.getAttribute("aria-label") || el.textContent || "").replace(/\s+/g, " ").trim().slice(0, 80);
1366
+ title && items.push({
1367
+ id: `el:${el.id || title}`,
1368
+ title,
1369
+ subtitle: el.dataset.qikbarSubtitle,
1370
+ keywords: el.dataset.qikbarKeywords?.split(",").map((k) => k.trim()),
1371
+ section: el.dataset.qikbarSection ?? this.t("actions"),
1372
+ icon: el.dataset.qikbarIcon ?? "zap",
1373
+ shortcut: el.dataset.qikbarShortcut,
1374
+ run: () => {
1375
+ el.click();
1376
+ }
1377
+ });
1378
+ }
1379
+ this.autoItems = items, this.rootCache = null;
1380
+ }
1381
+ // ─── Frames ──────────────────────────────────────────────────────────────
1382
+ createFrame(view, ext, args) {
1383
+ return {
1384
+ id: ++frameCounter,
1385
+ view,
1386
+ query: ("query" in view && typeof view.query == "string" ? view.query : "") || "",
1387
+ selected: 0,
1388
+ rows: [],
1389
+ itemRows: [],
1390
+ loading: 0,
1391
+ controller: new AbortController(),
1392
+ ext,
1393
+ args
1394
+ };
1395
+ }
1396
+ resetToRoot() {
1397
+ for (let f of this.stack) this.destroyFrame(f);
1398
+ let root = this.createFrame({ type: "root" });
1399
+ root.sourceResults = /* @__PURE__ */ new Map(), this.stack = [root], this.renderer?.destroy(), this.renderer = void 0, this.dom && (this.dom.input.value = ""), this.computeRows(root);
1400
+ }
1401
+ destroyFrame(frame) {
1402
+ frame.controller.abort(), frame.queryController?.abort(), frame.chat?.controller?.abort();
1403
+ try {
1404
+ frame.view.onClose?.();
1405
+ } catch (err) {
1406
+ console.error(err);
1407
+ }
1408
+ }
1409
+ /** Start async work for a freshly pushed frame. */
1410
+ startFrame(frame) {
1411
+ let v = frame.view;
1412
+ if (v.type === "list" || v.type === "grid")
1413
+ typeof v.items == "function" && this.loadItems(frame, !0), this.computeRows(frame);
1414
+ else if (v.type === "detail")
1415
+ this.loadDetail(frame, v);
1416
+ else if (v.type === "form") {
1417
+ let values = {};
1418
+ for (let f of v.fields) values[f.name] = f.defaultValue ?? (f.type === "checkbox" ? !1 : f.type === "select" ? f.options?.[0]?.value ?? "" : "");
1419
+ frame.form = { values, errors: {} };
1420
+ } else v.type === "chat" && (frame.chat = { messages: [], turns: [] }, v.prompt && queueMicrotask(() => this.sendChat(frame, v.prompt)));
1421
+ }
1422
+ replaceFrame(frame, view) {
1423
+ let index = this.stack.indexOf(frame);
1424
+ if (index < 0) return;
1425
+ let next = this.createFrame(view, frame.ext, frame.args);
1426
+ view.type === frame.view.type && !("query" in view && view.query != null) && (next.query = frame.query), frame === this.top && this.renderer && (next.scrollTop = this.renderer.scrollTop()), next.selectedKey = frame.itemRows[frame.selected]?.key, next.userMoved = !!next.selectedKey, this.destroyFrame(frame), this.stack[index] = next, this.startFrame(next), this.invalidate();
1427
+ }
1428
+ // ─── Rows ────────────────────────────────────────────────────────────────
1429
+ computeRows(frame) {
1430
+ let v = frame.view, groups;
1431
+ v.type === "root" ? groups = this.rootGroups(frame) : v.type === "list" || v.type === "grid" ? groups = this.listGroups(frame, v) : groups = [];
1432
+ let rows = [], itemRows = [], keys = /* @__PURE__ */ new Set();
1433
+ for (let g of groups)
1434
+ if (g.entries.length) {
1435
+ g.title && rows.push({ kind: "section", key: `s:${g.title}`, title: g.title });
1436
+ for (let e of g.entries) {
1437
+ let key = v.type === "root" ? this.idOf(e.item) : e.item.id ?? `${g.title}:${e.item.title}`;
1438
+ for (; keys.has(key); ) key += "'";
1439
+ keys.add(key);
1440
+ let row = { kind: "item", key, item: e.item, positions: e.positions, index: itemRows.length };
1441
+ rows.push(row), itemRows.push(row);
1442
+ }
1443
+ }
1444
+ if (frame.rows = rows, frame.itemRows = itemRows, frame.userMoved || (frame.selectedKey = void 0, frame.selected = 0), frame.selectedKey) {
1445
+ let idx = itemRows.findIndex((r) => r.key === frame.selectedKey);
1446
+ frame.selected = idx >= 0 ? idx : Math.min(frame.selected, Math.max(0, itemRows.length - 1));
1447
+ } else frame.selected = Math.min(frame.selected, Math.max(0, itemRows.length - 1));
1448
+ frame.selectedKey = itemRows[frame.selected]?.key;
1449
+ }
1450
+ rootGroups(frame) {
1451
+ let q = frame.query.trim(), items = this.rootItems(), groups = [], bySection = /* @__PURE__ */ new Map(), group = (title) => {
1452
+ let g = bySection.get(title);
1453
+ return g || (g = { title, entries: [] }, bySection.set(title, g), groups.push(g)), g;
1454
+ }, byId = () => new Map(items.map((i) => [this.idOf(i), i]));
1455
+ if (!q) {
1456
+ let shown = /* @__PURE__ */ new Set();
1457
+ if (this.personalize) {
1458
+ let map = byId();
1459
+ for (let id of this.pins()) {
1460
+ let item = map.get(id);
1461
+ !item || shown.has(item) || (group(this.t("pinned")).entries.push({ item }), shown.add(item));
1462
+ }
1463
+ }
1464
+ let recentsLimit = this.config.recents === !1 ? 0 : typeof this.config.recents == "number" ? this.config.recents : 4;
1465
+ if (recentsLimit) {
1466
+ let map = byId(), added = 0;
1467
+ for (let id of this.frecency.top(recentsLimit * 2 + shown.size)) {
1468
+ let item = map.get(id);
1469
+ if (!(!item || item.searchOnly || shown.has(item)) && (group(this.t("recent")).entries.push({ item }), shown.add(item), ++added >= recentsLimit))
1470
+ break;
1471
+ }
1472
+ }
1473
+ for (let item of items)
1474
+ item.searchOnly || shown.has(item) || group(item.section ?? this.t("commands")).entries.push({ item });
1475
+ return groups;
1476
+ }
1477
+ let addSources = (position) => {
1478
+ for (let source of this.sources) {
1479
+ if ((source.position ?? "bottom") !== position) continue;
1480
+ let results = frame.sourceResults?.get(source.id);
1481
+ if (!results?.length) continue;
1482
+ let g = group(source.title ?? this.t("results")), list = source.filter ? rank(results, q) : results.map((item) => ({ item, positions: matchItem(item, q)?.positions }));
1483
+ for (let r of list.slice(0, source.limit ?? 8)) g.entries.push({ item: r.item, positions: r.positions });
1484
+ }
1485
+ }, aliased = this.personalize ? this.aliases()[normalizeAlias(q)] : void 0, aliasItem = aliased ? byId().get(aliased) : void 0;
1486
+ aliasItem && group(aliasItem.section ?? this.t("commands")).entries.push({ item: aliasItem }), addSources("top");
1487
+ let pins = this.personalize ? new Set(this.pins()) : void 0, ranked = rank(items, q, {
1488
+ boost: (i) => {
1489
+ let id = this.idOf(i);
1490
+ return this.frecency.score(id) * 0.3 + (pins?.has(id) ? 0.15 : 0);
1491
+ },
1492
+ limit: 300
1493
+ });
1494
+ for (let r of ranked) r.item !== aliasItem && group(r.item.section ?? this.t("commands")).entries.push({ item: r.item, positions: r.positions });
1495
+ let related = this.relatedResults(frame, ranked.map((r) => r.item));
1496
+ if (related.length) {
1497
+ let g = group(this.t("related"));
1498
+ for (let item of related) item !== aliasItem && g.entries.push({ item });
1499
+ }
1500
+ addSources("bottom");
1501
+ let fallbacks = (this.config.fallbacks ?? []).map((f, i) => ({ ...f, id: `fallback:${i}`, title: f.title.replaceAll("{query}", q), subtitle: f.subtitle?.replaceAll("{query}", q) }));
1502
+ if (this.ai && this.aiOptions?.fallback !== !1 && fallbacks.unshift({
1503
+ id: "qikbar.ask-ai-fallback",
1504
+ title: this.t("askAi"),
1505
+ subtitle: `\u201C${q.length > 60 ? `${q.slice(0, 60)}\u2026` : q}\u201D`,
1506
+ icon: "sparkles",
1507
+ accessories: [{ kbd: "tab" }],
1508
+ noHistory: !0,
1509
+ run: () => ({ type: "chat", prompt: q })
1510
+ }), fallbacks.length) {
1511
+ let g = group(this.t("useQueryWith", { query: q.length > 24 ? `${q.slice(0, 24)}\u2026` : q }));
1512
+ for (let item of fallbacks) g.entries.push({ item });
1513
+ }
1514
+ return groups;
1515
+ }
1516
+ listGroups(frame, v) {
1517
+ let items = typeof v.items == "function" ? frame.items ?? [] : v.items, q = frame.query.trim(), entries = (v.filter ?? typeof v.items != "function") && q ? rank(items, q).map((r) => ({ item: r.item, positions: r.positions })) : items.map((item) => ({ item })), groups = [], bySection = /* @__PURE__ */ new Map();
1518
+ for (let e of entries) {
1519
+ let title = e.item.section ?? "", g = bySection.get(title);
1520
+ g || (g = { title, entries: [] }, bySection.set(title, g), groups.push(g)), g.entries.push(e);
1521
+ }
1522
+ return groups;
1523
+ }
1524
+ // ─── Loading ─────────────────────────────────────────────────────────────
1525
+ onQueryChange(frame, query) {
1526
+ if (frame.query === query) return;
1527
+ frame.query = query;
1528
+ let v = frame.view;
1529
+ (v.type === "root" || v.type === "list" || v.type === "grid") && (frame.selected = 0, frame.selectedKey = void 0, frame.userMoved = !1, v.type === "root" ? (this.searchSources(frame), this.searchSemantic(frame)) : typeof v.items == "function" && this.loadItems(frame, !1), this.computeRows(frame), this.renderer?.resetScroll?.(), this.scheduleSearchEvent(frame)), this.invalidate(), this.emitChange();
1530
+ }
1531
+ searchSources(frame) {
1532
+ frame.queryController?.abort();
1533
+ let controller = new AbortController();
1534
+ frame.queryController = controller;
1535
+ let q = frame.query.trim(), results = frame.sourceResults ?? (frame.sourceResults = /* @__PURE__ */ new Map());
1536
+ for (let source of this.sources) {
1537
+ let prev = results.get(source.id);
1538
+ if (q.length < (source.minQueryLength ?? 1)) {
1539
+ results.delete(source.id);
1540
+ continue;
1541
+ }
1542
+ prev && results.set(source.id, prev.filter((item) => matchItem(item, q)));
1543
+ let run = async () => {
1544
+ if (!controller.signal.aborted) {
1545
+ frame.loading++, this.invalidate();
1546
+ try {
1547
+ let rt = this.sourceExt.get(source), items = await source.search({ query: q, signal: controller.signal, ctx: this.makeContext(frame, { ext: rt, signal: controller.signal }) });
1548
+ if (controller.signal.aborted) return;
1549
+ if (rt) for (let i of items) this.itemExt.set(i, rt);
1550
+ results.set(source.id, items);
1551
+ } catch (err) {
1552
+ controller.signal.aborted || console.error(`[qikbar] source "${source.id}" failed`, err);
1553
+ } finally {
1554
+ frame.loading--, !controller.signal.aborted && this.stack.includes(frame) && this.computeRows(frame), this.invalidate();
1555
+ }
1556
+ }
1557
+ }, delay = source.debounce ?? 150, timer = setTimeout(run, delay);
1558
+ controller.signal.addEventListener("abort", () => clearTimeout(timer));
1559
+ }
1560
+ }
1561
+ /** Find items by meaning, in the background, and show them as "Related". */
1562
+ searchSemantic(frame) {
1563
+ let opt = this.config.semantic;
1564
+ if (frame.related = void 0, !opt) return;
1565
+ let q = frame.query.trim();
1566
+ if (q.length < (opt.minQueryLength ?? 3)) return;
1567
+ let signal = (frame.queryController ?? new AbortController()).signal, timer = setTimeout(async () => {
1568
+ if (!signal.aborted) {
1569
+ frame.loading++, this.invalidate();
1570
+ try {
1571
+ let candidates = this.rootItems().filter((i) => !this.idOf(i).startsWith("qikbar."));
1572
+ if (opt.sources) for (let list of frame.sourceResults?.values() ?? []) candidates.push(...list);
1573
+ let keyOf = (i) => this.rootItems().includes(i) ? this.idOf(i) : `src:${i.id ?? i.title}`, missing = candidates.filter((i) => this.vectors.get(keyOf(i))?.text !== embedText(i));
1574
+ for (let i = 0; i < missing.length; i += 128) {
1575
+ let batch = missing.slice(i, i + 128), vecs = await opt.embed(batch.map(embedText), { signal });
1576
+ if (signal.aborted) return;
1577
+ batch.forEach((item, n) => {
1578
+ let v = vecs[n];
1579
+ v && this.vectors.set(keyOf(item), { text: embedText(item), vec: normalize(v) });
1580
+ });
1581
+ }
1582
+ let [qv] = await opt.embed([q], { signal });
1583
+ if (signal.aborted || !qv) return;
1584
+ let query = normalize(qv), threshold = opt.threshold ?? 0.35, scored = [];
1585
+ for (let item of candidates) {
1586
+ let v = this.vectors.get(keyOf(item));
1587
+ if (!v) continue;
1588
+ let score = dot(query, v.vec);
1589
+ score >= threshold && scored.push({ item, score });
1590
+ }
1591
+ scored.sort((a, b) => b.score - a.score), frame.related = scored.slice(0, (opt.limit ?? 5) * 3), this.stack.includes(frame) && this.computeRows(frame);
1592
+ } catch (err) {
1593
+ !signal.aborted && !this.semanticWarned && (this.semanticWarned = !0, console.warn("[qikbar] semantic search failed", err));
1594
+ } finally {
1595
+ frame.loading--, this.invalidate();
1596
+ }
1597
+ }
1598
+ }, opt.debounce ?? 250);
1599
+ signal.addEventListener("abort", () => clearTimeout(timer));
1600
+ }
1601
+ /** Related results that the fuzzy search didn't already find. */
1602
+ relatedResults(frame, found) {
1603
+ if (!frame.related?.length) return [];
1604
+ let seen = new Set(found);
1605
+ return frame.related.filter((r) => !seen.has(r.item) && !r.item.searchOnly).slice(0, this.config.semantic?.limit ?? 5).map((r) => r.item);
1606
+ }
1607
+ loadItems(frame, immediate) {
1608
+ let v = frame.view;
1609
+ if (typeof v.items != "function") return;
1610
+ let loader = v.items;
1611
+ frame.queryController?.abort();
1612
+ let controller = new AbortController();
1613
+ frame.queryController = controller, frame.controller.signal.addEventListener("abort", () => controller.abort());
1614
+ let run = async () => {
1615
+ if (!controller.signal.aborted) {
1616
+ frame.loading++, frame.error = void 0, this.invalidate();
1617
+ try {
1618
+ let result = loader({ query: frame.query, signal: controller.signal, ctx: this.makeContext(frame, { signal: controller.signal }) });
1619
+ if (result && typeof result[Symbol.asyncIterator] == "function")
1620
+ for await (let batch of result) {
1621
+ if (controller.signal.aborted) return;
1622
+ this.setItems(frame, batch);
1623
+ }
1624
+ else {
1625
+ let items = await result;
1626
+ controller.signal.aborted || this.setItems(frame, items);
1627
+ }
1628
+ } catch (err) {
1629
+ controller.signal.aborted || (frame.error = err instanceof Error ? err.message : String(err), frame.items = [], this.computeRows(frame));
1630
+ } finally {
1631
+ frame.loading--, this.invalidate();
1632
+ }
1633
+ }
1634
+ };
1635
+ if (immediate) run();
1636
+ else {
1637
+ let timer = setTimeout(run, v.debounce ?? 120);
1638
+ controller.signal.addEventListener("abort", () => clearTimeout(timer));
1639
+ }
1640
+ }
1641
+ setItems(frame, items) {
1642
+ if (frame.items = items, frame.ext) for (let i of items) this.itemExt.set(i, frame.ext);
1643
+ this.computeRows(frame), this.invalidate();
1644
+ }
1645
+ async loadDetail(frame, v) {
1646
+ frame.detail = { text: "", done: !1 }, frame.loading++;
1647
+ try {
1648
+ let md = v.markdown;
1649
+ if (typeof md == "function" && (md = await md()), typeof md == "string") frame.detail.text = md;
1650
+ else
1651
+ for await (let chunk of md) {
1652
+ if (frame.controller.signal.aborted) return;
1653
+ frame.detail.text += chunk, this.invalidate();
1654
+ }
1655
+ } catch (err) {
1656
+ frame.controller.signal.aborted || (frame.detail.error = err instanceof Error ? err.message : String(err));
1657
+ } finally {
1658
+ frame.detail.done = !0, frame.loading--, this.invalidate();
1659
+ }
1660
+ }
1661
+ // ─── Context ─────────────────────────────────────────────────────────────
1662
+ makeContext(frame, extra = {}) {
1663
+ let ext = extra.ext ?? frame.ext;
1664
+ return {
1665
+ bar: this,
1666
+ get query() {
1667
+ return frame.query;
1668
+ },
1669
+ signal: extra.signal ?? frame.controller.signal,
1670
+ preferences: ext ? ext.prefs() : {},
1671
+ arguments: extra.args ?? frame.args ?? {},
1672
+ storage: ext?.storage ?? this.storage,
1673
+ ai: this.ai,
1674
+ push: (view) => this.push(view, ext),
1675
+ pop: () => this.pop(),
1676
+ render: (view) => {
1677
+ this.stack.includes(frame) ? this.replaceFrame(frame, view) : this.push(view, ext);
1678
+ },
1679
+ close: () => this.close(),
1680
+ navigate: (href, options) => this.navigate(href, options?.newTab ?? !1),
1681
+ openUrl: (url) => {
1682
+ this.close(), window.open(url, "_blank", "noopener,noreferrer");
1683
+ },
1684
+ copy: (text) => copyText(text),
1685
+ toast: (options) => this.toast(options),
1686
+ confirm: (options) => this.confirm(options),
1687
+ setQuery: (q) => {
1688
+ frame === this.top ? this.setQuery(q) : frame.query = q;
1689
+ },
1690
+ get selection() {
1691
+ return frame.marked ? [...frame.marked.values()] : [];
1692
+ },
1693
+ labels: this.labels
1694
+ };
1695
+ }
1696
+ navigate(href, newTab = !1) {
1697
+ this.isInline || this.close();
1698
+ let nav = this.config.navigate;
1699
+ if (nav) return nav(href, { newTab });
1700
+ defaultNavigate(href, newTab);
1701
+ }
1702
+ // ─── Actions ─────────────────────────────────────────────────────────────
1703
+ actionsFor(item, frame) {
1704
+ if (frame.marked?.size) return this.bulkActions(frame);
1705
+ let builtIn = this.renderer?.frame === frame ? this.renderer.viewActions?.() ?? [] : [], viewActions = [...frame.view.actions ?? [], ...builtIn];
1706
+ if (!item) return viewActions;
1707
+ frame.actionCache ?? (frame.actionCache = /* @__PURE__ */ new WeakMap());
1708
+ let cached = frame.actionCache.get(item);
1709
+ if (cached) return cached;
1710
+ let acts = [];
1711
+ if (item.run && acts.push({ title: frame.view.type === "root" ? this.t("runCommand") : this.t("run"), icon: "corner-down-left", run: item.run }), item.view) {
1712
+ let view = item.view;
1713
+ acts.push({ title: this.t("open"), icon: "chevron-right", run: (ctx) => typeof view == "function" ? view(ctx) : view });
1714
+ }
1715
+ if (item.href) {
1716
+ let href = item.href;
1717
+ acts.push(action.navigate(href)), acts.push(action.navigateNewTab(href)), acts.push(action.copy(() => new URL(href, location.href).href, { title: this.t("copyLink"), icon: "link", shortcut: "mod+shift+c" }));
1718
+ }
1719
+ item.url && (acts.push(action.open(item.url)), acts.push(action.copy(item.url, { title: this.t("copyUrl"), icon: "link", shortcut: "mod+shift+c" }))), item.actions && acts.push(...item.actions), acts.push(...viewActions);
1720
+ let rt = this.itemExt.get(item);
1721
+ if (frame.view.type === "root" && rt?.ext.preferences?.length && acts.push({
1722
+ title: this.t("configure", { name: rt.ext.title }),
1723
+ icon: "settings",
1724
+ section: this.t("extension"),
1725
+ run: () => this.preferencesForm(rt)
1726
+ }), this.isMulti(frame) && acts.push({
1727
+ title: this.t("select"),
1728
+ icon: "check-square",
1729
+ shortcut: "mod+shift+x",
1730
+ keepOpen: !0,
1731
+ run: () => (this.toggleMark(frame, item), !1)
1732
+ }), this.personalizable(item, frame)) {
1733
+ let id = this.idOf(item), pinned = this.pins().includes(id), alias = this.aliasOf(id);
1734
+ acts.push({
1735
+ title: pinned ? this.t("unpin") : this.t("pin"),
1736
+ icon: "pin",
1737
+ section: this.t("customize"),
1738
+ shortcut: "mod+shift+p",
1739
+ keepOpen: !0,
1740
+ run: () => (this.pin(id, !pinned), !1)
1741
+ }), acts.push({
1742
+ title: alias ? this.t("editAlias") : this.t("setAlias"),
1743
+ icon: "at-sign",
1744
+ section: this.t("customize"),
1745
+ run: () => this.aliasForm(item)
1746
+ }), alias && acts.push({
1747
+ title: this.t("removeAlias"),
1748
+ icon: "x",
1749
+ section: this.t("customize"),
1750
+ keepOpen: !0,
1751
+ run: () => (this.setAlias(id, null), this.toast({ title: this.t("aliasRemoved") }), !1)
1752
+ });
1753
+ }
1754
+ return frame.view.type === "root" && this.frecency.score(this.idOf(item)) > 0 && acts.push({
1755
+ title: this.t("clearHistory"),
1756
+ icon: "history",
1757
+ section: this.t("history"),
1758
+ keepOpen: !0,
1759
+ run: () => (this.frecency.clear(), this.computeRows(frame), this.invalidate(), !1)
1760
+ }), frame.actionCache.set(item, acts), acts;
1761
+ }
1762
+ selectedItem(frame = this.top) {
1763
+ if (frame)
1764
+ return frame.itemRows[frame.selected]?.item;
1765
+ }
1766
+ async runAction(frame, item, act, args, via = "keyboard") {
1767
+ let many = act.runMany && frame.marked?.size ? [...frame.marked.values()] : void 0;
1768
+ if (many && (item = void 0), item?.arguments?.length && !args) {
1769
+ this.enterArgMode(frame, item, act);
1770
+ return;
1771
+ }
1772
+ let rt = (item && this.itemExt.get(item)) ?? frame.ext;
1773
+ if (item && rt && rt.missing().length) {
1774
+ this.push(this.preferencesForm(rt, () => this.runAction(frame, item, act, args)), rt);
1775
+ return;
1776
+ }
1777
+ item && frame.view.type === "root" && !item.noHistory && this.frecency.record(this.idOf(item)), item ? (this.config.onRun?.(item, act), this.emit("run", { item, action: act }), this.track({ type: "run", item: this.eventItem(item), action: this.actionTitle(act), via })) : many && this.track({ type: "run", item: this.eventItem(many[0]), action: this.actionTitle(act), via, count: many.length });
1778
+ let handled = !1, base = this.makeContext(frame, { ext: rt, args }), ctx = Object.create(base, {
1779
+ push: { value: (v) => (handled = !0, base.push(v)) },
1780
+ render: { value: (v) => (handled = !0, base.render(v)) },
1781
+ pop: { value: () => (handled = !0, base.pop()) },
1782
+ close: { value: () => (handled = !0, base.close()) },
1783
+ navigate: { value: (href, o) => (handled = !0, base.navigate(href, o)) },
1784
+ openUrl: { value: (url) => (handled = !0, base.openUrl(url)) }
1785
+ });
1786
+ frame.loading++, this.invalidate();
1787
+ try {
1788
+ let result = many ? await act.runMany(many, ctx) : await act.run(ctx);
1789
+ many && this.stack.includes(frame) && this.clearMarks(frame), isView(result) ? this.push(result, rt) : result === !1 || act.keepOpen || handled || this.close();
1790
+ } catch (err) {
1791
+ console.error(err);
1792
+ let message = err instanceof Error ? err.message : String(err);
1793
+ this.track({ type: "error", message }), this.toast({ style: "failure", title: this.t("somethingWentWrong"), message });
1794
+ } finally {
1795
+ frame.loading--, this.invalidate();
1796
+ }
1797
+ }
1798
+ runPrimary(frame = this.top, index = 0, via = "keyboard") {
1799
+ if (!frame) return;
1800
+ let item = this.selectedItem(frame), act = this.actionsFor(item, frame)[index];
1801
+ act && this.runAction(frame, item, act, void 0, via);
1802
+ }
1803
+ // ─── Multi-select ────────────────────────────────────────────────────────
1804
+ isMulti(frame) {
1805
+ let v = frame.view;
1806
+ return (v.type === "list" || v.type === "grid") && !!v.multiSelect;
1807
+ }
1808
+ rowKeyOf(frame, item) {
1809
+ return frame.itemRows.find((r) => r.item === item)?.key;
1810
+ }
1811
+ isMarked(frame, key) {
1812
+ return !!frame.marked?.has(key);
1813
+ }
1814
+ toggleMark(frame, item, on) {
1815
+ if (!this.isMulti(frame)) return;
1816
+ let key = this.rowKeyOf(frame, item);
1817
+ if (!key) return;
1818
+ frame.marked ?? (frame.marked = /* @__PURE__ */ new Map()), on ?? !frame.marked.has(key) ? frame.marked.set(key, item) : frame.marked.delete(key), frame.anchor = key, this.marksChanged(frame);
1819
+ }
1820
+ /** Mark every row between the anchor and `item` (Shift-click). */
1821
+ markRange(frame, item) {
1822
+ if (!this.isMulti(frame)) return;
1823
+ let rows = frame.itemRows, to = rows.findIndex((r) => r.item === item), from = frame.anchor ? rows.findIndex((r) => r.key === frame.anchor) : -1;
1824
+ if (to < 0) return;
1825
+ frame.marked ?? (frame.marked = /* @__PURE__ */ new Map());
1826
+ let [a, b] = from < 0 ? [to, to] : from < to ? [from, to] : [to, from];
1827
+ for (let i = a; i <= b; i++) frame.marked.set(rows[i].key, rows[i].item);
1828
+ frame.anchor = rows[to].key, this.marksChanged(frame);
1829
+ }
1830
+ markAll(frame) {
1831
+ frame.marked ?? (frame.marked = /* @__PURE__ */ new Map());
1832
+ for (let r of frame.itemRows) frame.marked.set(r.key, r.item);
1833
+ this.marksChanged(frame);
1834
+ }
1835
+ clearMarks(frame) {
1836
+ frame.marked?.size && (frame.marked.clear(), frame.anchor = void 0, this.marksChanged(frame));
1837
+ }
1838
+ marksChanged(frame) {
1839
+ frame.actionCache = void 0, this.panel && frame === this.top && this.closePanel(), this.renderer?.refresh?.(), this.invalidate();
1840
+ let n = frame.marked?.size ?? 0;
1841
+ n && this.announce(this.t("selected", { count: n }));
1842
+ }
1843
+ bulkActions(frame) {
1844
+ let first = [...frame.marked.values()][0], marks = frame.marked;
1845
+ frame.marked = void 0;
1846
+ let base;
1847
+ try {
1848
+ base = this.actionsFor(first, frame);
1849
+ } finally {
1850
+ frame.marked = marks;
1851
+ }
1852
+ let bulk = base.filter((a) => a.runMany), builtIn = [];
1853
+ return frame.marked.size < frame.itemRows.length && builtIn.push({ title: this.t("selectAll"), icon: "check-square", shortcut: "mod+shift+a", keepOpen: !0, run: () => (this.markAll(frame), !1) }), builtIn.push({ title: this.t("clearSelection"), icon: "x", keepOpen: !0, run: () => (this.clearMarks(frame), !1) }), [...bulk, ...builtIn];
1854
+ }
1855
+ preferencesForm(rt, then) {
1856
+ let values = rt.prefs();
1857
+ return {
1858
+ type: "form",
1859
+ title: this.t("configure", { name: rt.ext.title }),
1860
+ submitLabel: then ? this.t("saveAndContinue") : this.t("save"),
1861
+ fields: (rt.ext.preferences ?? []).map((p) => ({
1862
+ name: p.name,
1863
+ label: p.title,
1864
+ description: p.description,
1865
+ type: p.type === "text" ? "text" : p.type,
1866
+ required: p.required,
1867
+ placeholder: p.placeholder,
1868
+ options: p.options,
1869
+ defaultValue: values[p.name] ?? p.default
1870
+ })),
1871
+ onSubmit: (vals) => {
1872
+ let stored = rt.storage.get("preferences") ?? {};
1873
+ return rt.storage.set("preferences", { ...stored, ...vals }), this.toast({ style: "success", title: this.t("preferencesSaved") }), this.pop(), then?.(), !1;
1874
+ }
1875
+ };
1876
+ }
1877
+ // ─── Arguments ───────────────────────────────────────────────────────────
1878
+ enterArgMode(frame, item, act) {
1879
+ this.argMode = { item, action: act, frame, values: {} }, this.closePanel(), this.flush(), this.dom?.args.querySelector("input,select")?.focus();
1880
+ }
1881
+ submitArgs() {
1882
+ let m = this.argMode;
1883
+ if (!m || !this.dom) return;
1884
+ let missing = (m.item.arguments ?? []).find((a) => a.required && !m.values[a.name]?.trim());
1885
+ if (missing) {
1886
+ this.dom.args.querySelector(`[name="${CSS.escape(missing.name)}"]`)?.focus();
1887
+ return;
1888
+ }
1889
+ this.argMode = void 0, this.runAction(m.frame, m.item, m.action, m.values), this.flush();
1890
+ }
1891
+ // ─── AI chat ─────────────────────────────────────────────────────────────
1892
+ sendChat(frame, text) {
1893
+ let chat = frame.chat;
1894
+ if (!chat || !this.aiOptions || !text.trim() || chat.controller && !chat.controller.signal.aborted) return;
1895
+ let controller = new AbortController();
1896
+ frame.controller.signal.addEventListener("abort", () => controller.abort()), chat.controller = controller, chat.messages.push({ role: "user", content: text }), chat.turns.push({ role: "user", text, tools: [] });
1897
+ let turn = { role: "assistant", text: "", tools: [], streaming: !0 };
1898
+ chat.turns.push(turn), frame === this.top && this.dom && (this.dom.input.value = "", frame.query = ""), frame.loading++, this.invalidate();
1899
+ let view = frame.view, useTools = view.tools !== !1 && this.aiOptions.tools !== !1;
1900
+ this.track({ type: "ask_ai", prompt: text }), (async () => {
1901
+ try {
1902
+ let tools = useTools ? await this.agentTools(frame, controller.signal) : [];
1903
+ if (controller.signal.aborted) return;
1904
+ for await (let ev of runAgent({
1905
+ provider: this.aiOptions.provider,
1906
+ messages: chat.messages,
1907
+ system: view.system ?? this.systemPrompt(useTools),
1908
+ tools,
1909
+ maxSteps: this.aiOptions.maxSteps ?? 6,
1910
+ signal: controller.signal
1911
+ })) {
1912
+ if (ev.type === "text") turn.text += ev.text;
1913
+ else if (ev.type === "message") chat.messages.push(ev.message);
1914
+ else if (ev.type === "tool_start")
1915
+ turn.text && !/\n\s*$/.test(turn.text) && (turn.text += `
1916
+
1917
+ `), turn.tools.push({ label: ev.label, state: "running" });
1918
+ else if (ev.type === "tool_end") {
1919
+ let t = turn.tools.find((x) => x.state === "running");
1920
+ t && (t.state = ev.ok ? "done" : "error");
1921
+ } else ev.type === "error" && (turn.error = ev.error);
1922
+ this.invalidate();
1923
+ }
1924
+ } catch (err) {
1925
+ controller.signal.aborted || (turn.error = err instanceof Error ? err.message : String(err));
1926
+ } finally {
1927
+ turn.streaming = !1;
1928
+ for (let t of turn.tools) t.state === "running" && (t.state = "error");
1929
+ frame.loading--, chat.controller = void 0, this.invalidate();
1930
+ }
1931
+ })();
1932
+ }
1933
+ stopChat(frame) {
1934
+ let c = frame.chat?.controller;
1935
+ return c && !c.signal.aborted ? (c.abort(), !0) : !1;
1936
+ }
1937
+ systemPrompt(withTools) {
1938
+ let lines = [
1939
+ `You are ${this.aiName}, the assistant built into this web app's command bar.`,
1940
+ "Answer concisely in Markdown. Prefer short paragraphs and lists."
1941
+ ];
1942
+ if (typeof document < "u" && lines.push(`The user is on the page "${document.title}" (${location.pathname}).`), withTools) {
1943
+ let items = this.rootItems().filter((i) => !i.id?.startsWith("qikbar."));
1944
+ lines.push(
1945
+ "",
1946
+ "You can act inside the app:",
1947
+ "- Call `run` with an item id to open a page or run a command when the user asks you to go somewhere or do something.",
1948
+ "- Call `search` to find commands, pages and records that are not listed below.",
1949
+ "Only call tools when the user wants something done or found in the app; otherwise just answer. After acting, confirm briefly what you did.",
1950
+ "",
1951
+ "Available items (id | title | section):",
1952
+ ...items.slice(0, 80).map((i) => `${this.idOf(i)} | ${i.title}${i.subtitle ? ` \u2014 ${i.subtitle}` : ""} | ${i.section ?? "Commands"}`)
1953
+ ), items.length > 80 && lines.push(`\u2026and ${items.length - 80} more (use search).`);
1954
+ }
1955
+ return this.aiOptions?.system && lines.push("", this.aiOptions.system), lines.join(`
1956
+ `);
1957
+ }
1958
+ /**
1959
+ * Run an item on behalf of an AI model (chat or WebMCP agent) and describe what happened.
1960
+ * Navigation happens without closing a chat; destructive primary actions ask first.
1961
+ */
1962
+ async runForAgent(item, rawArgs, frame, via) {
1963
+ let ctxFrame = frame ?? this.createFrame({ type: "root" }), rt = this.itemExt.get(item);
1964
+ if (rt?.missing().length) throw new Error(`${rt.ext.title} needs to be configured first. Ask the user to open it from the command bar.`);
1965
+ let act = this.actionsFor(item, this.stack[0] ?? ctxFrame)[0];
1966
+ if (!act) throw new Error("This item has no action.");
1967
+ if (act.style === "destructive" && !await this.confirm({ title: `${this.actionTitle(act)}?`, message: item.title, destructive: !0, confirmLabel: this.actionTitle(act) }))
1968
+ return "The user cancelled.";
1969
+ if (this.track({ type: "run", item: this.eventItem(item), action: this.actionTitle(act), via }), item.href) {
1970
+ let nav = this.config.navigate;
1971
+ return nav ? nav(item.href, { newTab: !1 }) : defaultNavigate(item.href, !1), this.frecency.record(this.idOf(item)), `Navigated to ${item.href}.`;
1972
+ }
1973
+ if (item.url)
1974
+ return window.open(item.url, "_blank", "noopener,noreferrer"), `Opened ${item.url} in a new tab.`;
1975
+ let strArgs = Object.fromEntries(Object.entries(rawArgs ?? {}).map(([k, v]) => [k, String(v)])), ctx = Object.create(this.makeContext(ctxFrame, { ext: rt, args: strArgs }), {
1976
+ close: { value: () => {
1977
+ } }
1978
+ }), result = await act.run(ctx);
1979
+ return this.frecency.record(this.idOf(item)), isView(result) ? (this.push(result, rt), `Opened the "${item.title}" view for the user.`) : `Ran "${item.title}".`;
1980
+ }
1981
+ /** Search commands and sources for an AI model. Results carry ids for `run`. */
1982
+ async searchForAgent(q, frame, signal, found) {
1983
+ let ctxFrame = frame ?? this.createFrame({ type: "root" }), local = rank(this.rootItems(), q, { limit: 10 }).map((r) => r.item), remote = await Promise.all(
1984
+ [...this.sources].map(async (s) => {
1985
+ if (q.length < (s.minQueryLength ?? 1)) return [];
1986
+ try {
1987
+ let rt = this.sourceExt.get(s), items = await withTimeout(s.search({ query: q, signal, ctx: this.makeContext(ctxFrame, { ext: rt, signal }) }), 6e3);
1988
+ if (rt) for (let i of items) this.itemExt.set(i, rt);
1989
+ return items.slice(0, s.limit ?? 8).map((i) => ({ item: i, section: s.title ?? s.id }));
1990
+ } catch {
1991
+ return [];
1992
+ }
1993
+ })
1994
+ );
1995
+ return [...local.map((item) => ({ item, section: item.section ?? "Commands" })), ...remote.flat()].map(({ item, section }, n) => {
1996
+ let id = this.rootItems().includes(item) ? this.idOf(item) : item.id && !found.has(item.id) ? item.id : `${section}#${n}`;
1997
+ return found.set(id, item), { id, title: item.title, subtitle: item.subtitle, section, description: item.description, href: item.href ?? item.url };
1998
+ });
1999
+ }
2000
+ async agentTools(chatFrame, signal) {
2001
+ let found = /* @__PURE__ */ new Map(), lookup = (id) => found.get(id) ?? this.rootItems().find((i) => this.idOf(i) === id), tools = [
2002
+ {
2003
+ definition: {
2004
+ name: "search",
2005
+ description: "Search the app's commands, pages and records (including results from connected data sources). Returns matching items with ids you can pass to `run`.",
2006
+ parameters: { type: "object", properties: { query: { type: "string", description: "What to look for" } }, required: ["query"] }
2007
+ },
2008
+ label: (a) => `Searching \u201C${String(a.query ?? "")}\u201D`,
2009
+ run: async (args, signal2) => {
2010
+ let results = await this.searchForAgent(String(args.query ?? ""), chatFrame, signal2, found);
2011
+ return results.length ? results : "No results.";
2012
+ }
2013
+ },
2014
+ {
2015
+ definition: {
2016
+ name: "run",
2017
+ description: "Open or run an item (page, command or record) by id. Use ids from the system prompt or from `search`.",
2018
+ parameters: {
2019
+ type: "object",
2020
+ properties: {
2021
+ id: { type: "string" },
2022
+ arguments: { type: "object", description: "Values for the command arguments, if it has any.", additionalProperties: { type: "string" } }
2023
+ },
2024
+ required: ["id"]
2025
+ }
2026
+ },
2027
+ label: (a) => {
2028
+ let item = lookup(String(a.id ?? ""));
2029
+ return item ? `Opening ${item.title}` : `Running ${String(a.id ?? "")}`;
2030
+ },
2031
+ run: async (args) => {
2032
+ let item = lookup(String(args.id ?? ""));
2033
+ if (!item) throw new Error(`No item with id "${String(args.id)}". Use search first.`);
2034
+ return this.runForAgent(item, args.arguments, chatFrame, "ai");
2035
+ }
2036
+ }
2037
+ ];
2038
+ this.aiOptions?.pageContext !== !1 && typeof document < "u" && tools.push({
2039
+ definition: {
2040
+ name: "read_page",
2041
+ description: 'Read the visible text of the page the user is currently on. Use it when the user asks about "this page" or its content.',
2042
+ parameters: { type: "object", properties: {} }
2043
+ },
2044
+ label: () => "Reading this page",
2045
+ run: async () => {
2046
+ let text = (document.querySelector("main, [role=main], article") ?? document.body).innerText.replace(/\n{3,}/g, `
2047
+
2048
+ `).trim();
2049
+ return `# ${document.title}
2050
+ URL: ${location.href}
2051
+
2052
+ ${text.slice(0, 2e4)}`;
2053
+ }
2054
+ });
2055
+ let addTools = (list, rt, prefix) => {
2056
+ for (let tool of list)
2057
+ tools.push({
2058
+ definition: {
2059
+ name: toolName(prefix ? `${prefix}__${tool.name}` : tool.name),
2060
+ description: tool.description,
2061
+ parameters: tool.parameters ?? { type: "object", properties: {} }
2062
+ },
2063
+ label: () => tool.description.split(/[.\n]/)[0].slice(0, 60),
2064
+ run: async (args) => {
2065
+ if (tool.confirm) {
2066
+ let msg = typeof tool.confirm == "function" ? tool.confirm(args) : this.t("allowTool", { tool: tool.name });
2067
+ if (!await this.confirm({ title: msg, confirmLabel: this.t("allow") })) return "The user declined.";
2068
+ }
2069
+ return tool.run(args, this.makeContext(chatFrame, { ext: rt }));
2070
+ }
2071
+ });
2072
+ };
2073
+ addTools(this.config.tools ?? [], void 0, "");
2074
+ for (let e of this.extensions.values()) addTools(e.rt.ext.tools ?? [], e.rt, e.rt.ext.name);
2075
+ for (let provider of this.aiOptions?.mcp ?? [])
2076
+ try {
2077
+ addTools(await withTimeout(provider.tools(signal), 1e4), void 0, provider.name);
2078
+ } catch (err) {
2079
+ signal?.aborted || console.warn(`[qikbar] tools from "${provider.name}" are unavailable`, err);
2080
+ }
2081
+ return tools;
2082
+ }
2083
+ /** Every tool from config and extensions, with the extension it belongs to. */
2084
+ toolList() {
2085
+ let out = (this.config.tools ?? []).map((tool) => ({ tool, prefix: "" }));
2086
+ for (let e of this.extensions.values()) for (let tool of e.rt.ext.tools ?? []) out.push({ tool, rt: e.rt, prefix: e.rt.ext.name });
2087
+ return out;
2088
+ }
2089
+ /** Make a context for running a tool outside a chat (WebMCP). */
2090
+ toolContext(rt) {
2091
+ return this.makeContext(this.top ?? this.createFrame({ type: "root" }), { ext: rt });
2092
+ }
2093
+ // ─── Toasts & confirm ────────────────────────────────────────────────────
2094
+ toast(options) {
2095
+ let opts = typeof options == "string" ? { title: options } : options, id = ++this.toastId, resolveAct = (o) => o.action ?? (o.undo ? { title: this.t("undo"), shortcut: "mod+z", run: o.undo } : void 0), schedule = () => {
2096
+ clearTimeout(this.toastTimer);
2097
+ let s = this.toastState;
2098
+ if (!s) return;
2099
+ let duration = s.duration ?? (s.style === "loading" ? 0 : s.act ? 6e3 : 2600);
2100
+ duration > 0 && (this.toastTimer = setTimeout(() => hide(), duration));
2101
+ }, hide = () => {
2102
+ this.toastState?.id === id && (this.toastState = void 0, this.renderToast());
2103
+ };
2104
+ return this.toastState = { ...opts, id, act: resolveAct(opts) }, schedule(), this.renderToast(), {
2105
+ update: (p) => {
2106
+ if (this.toastState?.id !== id) return;
2107
+ let next = { ...this.toastState, ...p };
2108
+ this.toastState = { ...next, act: resolveAct(next) }, schedule(), this.renderToast();
2109
+ },
2110
+ hide
2111
+ };
2112
+ }
2113
+ /** Run the visible toast's action (e.g. Undo) and dismiss the toast. */
2114
+ async runToastAction() {
2115
+ let t = this.toastState, act = t?.act;
2116
+ if (!(!t || !act)) {
2117
+ clearTimeout(this.toastTimer), this.toastState = void 0, this.renderToast();
2118
+ try {
2119
+ await act.run(), t.undo && !t.action && this.track({ type: "undo", title: t.title });
2120
+ } catch (err) {
2121
+ console.error(err), this.toast({ style: "failure", title: this.t("somethingWentWrong"), message: err instanceof Error ? err.message : String(err) });
2122
+ }
2123
+ }
2124
+ }
2125
+ confirm(options) {
2126
+ let opts = typeof options == "string" ? { title: options } : options;
2127
+ return !this._open || !this.dom ? Promise.resolve(typeof window < "u" ? window.confirm(opts.message ? `${opts.title}
2128
+
2129
+ ${opts.message}` : opts.title) : !1) : (this.confirmState?.resolve(!1), new Promise((resolve) => {
2130
+ this.confirmState = {
2131
+ ...opts,
2132
+ resolve: (ok) => {
2133
+ this.confirmState = void 0, this.renderLayer(), this.focusInput(), resolve(ok);
2134
+ }
2135
+ }, this.renderLayer();
2136
+ }));
2137
+ }
2138
+ escape() {
2139
+ let frame = this.top;
2140
+ if (frame && !(frame.chat && this.stopChat(frame))) {
2141
+ if (frame.marked?.size) return this.clearMarks(frame);
2142
+ if (this.stack.length > 1) return this.pop();
2143
+ if (frame.query) return this.setQuery("");
2144
+ this.close();
2145
+ }
2146
+ }
2147
+ // ─── Action panel ────────────────────────────────────────────────────────
2148
+ openPanel() {
2149
+ let frame = this.top;
2150
+ if (!frame || !this.dom) return;
2151
+ if (this.panel) return this.closePanel();
2152
+ let item = frame.marked?.size ? void 0 : this.selectedItem(frame), actions = this.actionsFor(item, frame);
2153
+ actions.length && (this.panel = { item, actions, filter: "", selected: 0 }, this.renderPanel());
2154
+ }
2155
+ closePanel() {
2156
+ this.panel && (this.panel.el?.remove(), this.panel = void 0, this.focusInput());
2157
+ }
2158
+ panelActions() {
2159
+ let p = this.panel;
2160
+ return p.filter ? rank(p.actions, p.filter).map((r) => r.item) : p.actions;
2161
+ }
2162
+ onPanelKey(e) {
2163
+ let p = this.panel, list = this.panelActions();
2164
+ if (e.key === "Escape" || matchesHotkey(e, this.actionsHotkey))
2165
+ return this.closePanel(), !0;
2166
+ let emacs = e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey;
2167
+ if (e.key === "ArrowDown" || emacs && e.key === "n")
2168
+ return p.selected = (p.selected + 1) % Math.max(1, list.length), this.renderPanel(), !0;
2169
+ if (e.key === "ArrowUp" || emacs && e.key === "p")
2170
+ return p.selected = (p.selected - 1 + list.length) % Math.max(1, list.length), this.renderPanel(), !0;
2171
+ if (e.key === "Enter") {
2172
+ let act = list[p.selected];
2173
+ return act && this.runFromPanel(act), !0;
2174
+ }
2175
+ for (let act of p.actions)
2176
+ if (act.shortcut && matchesHotkey(e, act.shortcut))
2177
+ return this.runFromPanel(act), !0;
2178
+ return !1;
2179
+ }
2180
+ runFromPanel(act) {
2181
+ let item = this.panel?.item, frame = this.top;
2182
+ this.closePanel(), this.runAction(frame, item, act, void 0, "panel");
2183
+ }
2184
+ renderPanel() {
2185
+ let p = this.panel, dom = this.dom;
2186
+ if (!p || !dom) return;
2187
+ p.el || (p.list = h("div", { class: "qb-actions-list", role: "listbox", id: `${this.instanceId}-actions` }), p.input = h("input", {
2188
+ class: "qb-actions-input",
2189
+ placeholder: this.t("searchActions"),
2190
+ "aria-label": this.t("searchActions"),
2191
+ autocomplete: "off",
2192
+ spellcheck: "false",
2193
+ onInput: () => {
2194
+ p.filter = p.input.value, p.selected = 0, this.renderPanel();
2195
+ }
2196
+ }), p.el = h(
2197
+ "div",
2198
+ { class: this.cls("qb-actions", "actions"), role: "dialog", "aria-label": this.t("actions") },
2199
+ h("div", { class: "qb-actions-title" }, p.item?.title ?? (this.top?.marked?.size ? this.t("selected", { count: this.top.marked.size }) : this.t("actions"))),
2200
+ p.list,
2201
+ p.input
2202
+ ), p.el.addEventListener("pointerdown", (e) => {
2203
+ e.target !== p.input && e.preventDefault();
2204
+ }), dom.dialog.append(p.el), this.isTouch || p.input.focus());
2205
+ let list = this.panelActions();
2206
+ p.selected = Math.min(p.selected, Math.max(0, list.length - 1));
2207
+ let children = [], section;
2208
+ list.forEach((act, i) => {
2209
+ !p.filter && act.section && act.section !== section && children.push(h("div", { class: "qb-section" }, act.section)), section = act.section;
2210
+ let shortcut = act.shortcut ?? (i === 0 && !p.filter ? "enter" : i === 1 && !p.filter ? "mod+enter" : void 0), el = h(
2211
+ "div",
2212
+ {
2213
+ class: "qb-action",
2214
+ role: "option",
2215
+ id: `${this.instanceId}-action-${i}`,
2216
+ "aria-selected": i === p.selected ? "true" : "false",
2217
+ "data-style": act.style ?? "default",
2218
+ onClick: () => this.runFromPanel(act),
2219
+ onPointermove: () => {
2220
+ p.selected !== i && (p.selected = i, this.renderPanel());
2221
+ }
2222
+ },
2223
+ renderIcon(act.icon ?? "dot", 15),
2224
+ h("span", { class: "qb-action-title" }, this.actionTitle(act)),
2225
+ shortcut ? renderKbd(shortcut) : null
2226
+ );
2227
+ children.push(el);
2228
+ }), list.length || children.push(h("div", { class: "qb-empty-desc", style: "padding:10px 8px" }, this.t("noMatchingActions"))), p.list.replaceChildren(...children), p.input.setAttribute("aria-activedescendant", `${this.instanceId}-action-${p.selected}`), p.list.querySelector("[aria-selected=true]")?.scrollIntoView({ block: "nearest" });
2229
+ }
2230
+ // ─── DOM ─────────────────────────────────────────────────────────────────
2231
+ cls(base, slot) {
2232
+ let extra = this.config.classNames?.[slot];
2233
+ return extra ? `${base} ${extra}` : base;
2234
+ }
2235
+ injectStyles() {
2236
+ if (this.config.unstyled || typeof document > "u" || document.getElementById("qikbar-styles")) return;
2237
+ let style = document.createElement("style");
2238
+ style.id = "qikbar-styles", this.config.nonce && (style.nonce = this.config.nonce), style.textContent = css, document.head.append(style), this.styleEl = style;
2239
+ }
2240
+ mount() {
2241
+ if (this.dom || typeof document > "u") return;
2242
+ this.injectStyles();
2243
+ let id = this.instanceId, input = h("input", {
2244
+ class: this.cls("qb-input", "input"),
2245
+ type: "text",
2246
+ role: "combobox",
2247
+ autocomplete: "off",
2248
+ autocorrect: "off",
2249
+ autocapitalize: "off",
2250
+ spellcheck: "false",
2251
+ enterkeyhint: "go",
2252
+ "aria-autocomplete": "list",
2253
+ "aria-expanded": "true",
2254
+ "aria-controls": `${id}-list`,
2255
+ "aria-label": this.t("search")
2256
+ });
2257
+ input.addEventListener("input", () => {
2258
+ let frame = this.top;
2259
+ frame && this.onQueryChange(frame, input.value);
2260
+ });
2261
+ let back = h("button", { class: "qb-back", type: "button", "aria-label": this.t("back"), title: this.t("back"), html: "" });
2262
+ back.append(renderIcon("arrow-left", 15)), back.addEventListener("click", () => this.pop());
2263
+ let hint = h("button", { class: "qb-hint", type: "button" });
2264
+ hint.addEventListener("click", () => this.ask(this.top?.query));
2265
+ let progress = h("div", { class: "qb-progress", "aria-hidden": "true" }), header = h(
2266
+ "div",
2267
+ { class: this.cls("qb-header", "header") },
2268
+ back,
2269
+ h("div", { class: "qb-crumb" }),
2270
+ h("span", { class: "qb-header-icon" }, renderIcon("search", 18)),
2271
+ input,
2272
+ h("div", { class: "qb-args", style: "display:contents" }),
2273
+ h("div", { class: "qb-title" }),
2274
+ hint,
2275
+ progress
2276
+ ), body = h("div", { class: "qb-body" }), footerLeft = h("div", { class: "qb-footer-left", "aria-live": "polite" }), footerRight = h("div", { class: "qb-footer-right" }), footer = h("div", { class: this.cls("qb-footer", "footer") }, footerLeft, footerRight), layer = h("div", { style: "display:contents" }), dialog = h(
2277
+ "div",
2278
+ { class: this.cls("qb-dialog", "dialog"), role: "dialog", "aria-modal": this.isInline ? "false" : "true", "aria-label": this.t("commandBar"), tabindex: "-1", hidden: !0 },
2279
+ header,
2280
+ body,
2281
+ footer,
2282
+ layer
2283
+ ), overlay = h("div", { class: this.cls("qb-overlay", "overlay"), hidden: !0 });
2284
+ overlay.addEventListener("pointerdown", (e) => {
2285
+ e.preventDefault(), this.close();
2286
+ });
2287
+ let live = h("div", { class: "qb-sr-only", "aria-live": "polite" }), root = h("div", { class: this.cls("qb-root", "root"), "data-qb-state": "closed", id }, overlay, dialog, live);
2288
+ this.config.dir && (root.dir = this.config.dir), dialog.addEventListener("keydown", this.onDialogKeyDown), dialog.addEventListener("click", (e) => {
2289
+ let btn = e.target.closest?.("[data-qb-copy]");
2290
+ if (btn) {
2291
+ let code = btn.closest(".qb-code")?.querySelector("code")?.textContent ?? "";
2292
+ copyText(code).then((ok) => {
2293
+ btn.textContent = ok ? this.t("copiedShort") : this.t("failed"), setTimeout(() => btn.textContent = this.t("copy"), 1200);
2294
+ });
2295
+ }
2296
+ this.panel && !e.target.closest?.(".qb-actions") && !e.target.closest?.(".qb-footer-btn") && this.closePanel();
2297
+ });
2298
+ let inline = this.inlineTarget();
2299
+ inline ? (root.dataset.qbInline = "", inline.append(root)) : (this.config.container ?? document.body).append(root), this.dom = {
2300
+ root,
2301
+ overlay,
2302
+ dialog,
2303
+ header,
2304
+ back,
2305
+ crumb: header.querySelector(".qb-crumb"),
2306
+ searchIcon: header.querySelector(".qb-header-icon"),
2307
+ input,
2308
+ args: header.querySelector(".qb-args"),
2309
+ title: header.querySelector(".qb-title"),
2310
+ hint,
2311
+ progress,
2312
+ body,
2313
+ footer,
2314
+ footerLeft,
2315
+ footerRight,
2316
+ layer,
2317
+ live
2318
+ }, this.applyTheme(), this.applyTouch(), this.watchAppearance(), this.watchViewport(), this.listen(document, "focusin", ((e) => {
2319
+ this._open && !this.isInline && this.dom && !this.dom.root.contains(e.target) && this.focusInput();
2320
+ }));
2321
+ }
2322
+ applyClassNames() {
2323
+ let d = this.dom;
2324
+ d && (d.root.className = this.cls("qb-root", "root"), d.overlay.className = this.cls("qb-overlay", "overlay"), d.dialog.className = this.cls("qb-dialog", "dialog"), d.header.className = this.cls("qb-header", "header"), d.input.className = this.cls("qb-input", "input"), d.footer.className = this.cls("qb-footer", "footer"), this.renderer && (this.renderer.destroy(), this.renderer = void 0, this.flush()));
2325
+ }
2326
+ resolveAppearance() {
2327
+ let a = this.config.appearance ?? "auto";
2328
+ if (typeof a == "function") return a();
2329
+ if (a !== "auto") return a;
2330
+ let html = document.documentElement, body = document.body, darkAttr = (el) => !!el && (el.classList.contains("dark") || el.dataset.theme === "dark" || el.dataset.mode === "dark" || el.dataset.colorScheme === "dark" || el.dataset.bsTheme === "dark"), lightAttr = (el) => !!el && (el.classList.contains("light") || el.dataset.theme === "light" || el.dataset.mode === "light" || el.dataset.colorScheme === "light" || el.dataset.bsTheme === "light");
2331
+ if (darkAttr(html) || darkAttr(body)) return "dark";
2332
+ if (lightAttr(html) || lightAttr(body)) return "light";
2333
+ let scheme = html.style.colorScheme || getComputedStyle(html).colorScheme;
2334
+ return scheme === "dark" ? "dark" : scheme === "light" ? "light" : typeof matchMedia < "u" && matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
2335
+ }
2336
+ applyTheme() {
2337
+ let root = this.dom?.root;
2338
+ if (!root) return;
2339
+ let { vars, appearance } = resolveThemeVars(this.config.theme, this.resolveAppearance());
2340
+ root.dataset.qbAppearance = appearance;
2341
+ let preset = typeof this.config.theme == "string" ? this.config.theme : this.config.theme?.preset;
2342
+ preset ? root.dataset.qbTheme = preset : delete root.dataset.qbTheme;
2343
+ for (let name of this.appliedVars) root.style.removeProperty(name);
2344
+ this.appliedVars = [];
2345
+ for (let [k, v] of Object.entries(vars)) {
2346
+ if (v == null || v === "") continue;
2347
+ let name = cssVarName(k);
2348
+ root.style.setProperty(name, v), this.appliedVars.push(name);
2349
+ }
2350
+ }
2351
+ watchAppearance() {
2352
+ if (typeof MutationObserver > "u") return;
2353
+ let update = () => {
2354
+ this.dom && (this.config.appearance ?? "auto") === "auto" && this.applyTheme();
2355
+ }, mo = new MutationObserver(update);
2356
+ if (mo.observe(document.documentElement, { attributes: !0, attributeFilter: ["class", "data-theme", "data-mode", "data-color-scheme", "data-bs-theme", "style"] }), document.body && mo.observe(document.body, { attributes: !0, attributeFilter: ["class", "data-theme", "data-mode"] }), this.teardown.push(() => mo.disconnect()), typeof matchMedia < "u") {
2357
+ let mq = matchMedia("(prefers-color-scheme: dark)");
2358
+ mq.addEventListener?.("change", update), this.teardown.push(() => mq.removeEventListener?.("change", update));
2359
+ }
2360
+ }
2361
+ lockScroll() {
2362
+ let html = document.documentElement, scrollbar = window.innerWidth - html.clientWidth;
2363
+ this.scrollLock = { overflow: html.style.overflow, paddingRight: html.style.paddingRight }, html.style.overflow = "hidden", scrollbar > 0 && (html.style.paddingRight = `${scrollbar}px`);
2364
+ }
2365
+ unlockScroll() {
2366
+ if (!this.scrollLock) return;
2367
+ let html = document.documentElement;
2368
+ html.style.overflow = this.scrollLock.overflow, html.style.paddingRight = this.scrollLock.paddingRight, this.scrollLock = void 0;
2369
+ }
2370
+ focusInput() {
2371
+ if (!this.dom || !this._open) return;
2372
+ let target = this.renderer?.focusTarget?.() ?? (this.dom.input.hidden ? this.dom.dialog : this.dom.input);
2373
+ document.activeElement !== target && target.focus({ preventScroll: !0 });
2374
+ }
2375
+ // ─── Rendering ───────────────────────────────────────────────────────────
2376
+ invalidate() {
2377
+ this.scheduled || !this.dom || (this.scheduled = !0, queueMicrotask(() => {
2378
+ this.scheduled = !1, this.flush();
2379
+ }));
2380
+ }
2381
+ flush() {
2382
+ let dom = this.dom, frame = this.top;
2383
+ !dom || !frame || !this._open && !this.isInline || (!this.renderer || this.renderer.frame !== frame ? (this.renderer?.destroy(), this.renderer = this.createRenderer(frame), dom.body.replaceChildren(this.renderer.el), this.renderer.update(), frame.scrollTop && this.renderer.restoreScroll(frame.scrollTop), frame.selected > 0 && this.renderer.ensureVisible?.()) : this.renderer.update(), this.renderHeader(frame), this.renderFooter(frame), this.renderLayer(), this.panel && this.renderPanel());
2384
+ }
2385
+ createRenderer(frame) {
2386
+ switch (frame.view.type) {
2387
+ case "grid":
2388
+ return new GridRenderer(this, frame);
2389
+ case "detail":
2390
+ return new DetailRenderer(this, frame);
2391
+ case "form":
2392
+ return new FormRenderer(this, frame);
2393
+ case "chat":
2394
+ return new ChatRenderer(this, frame);
2395
+ default:
2396
+ return new ListRenderer(this, frame);
2397
+ }
2398
+ }
2399
+ renderHeader(frame) {
2400
+ let dom = this.dom, v = frame.view, depth = this.stack.length, hasInput = this.renderer?.hasInput ?? !0;
2401
+ dom.back.hidden = depth <= 1;
2402
+ let crumbTitle = depth > 1 ? v.title ?? (v.type === "chat" ? this.aiName : void 0) : void 0;
2403
+ if (dom.crumb.hidden = !crumbTitle || !hasInput, crumbTitle && hasInput && dom.crumb.replaceChildren(...[renderIcon(frame.ext?.ext.icon, 13), h("span", null, crumbTitle)].filter(Boolean)), dom.searchIcon.hidden = depth > 1 || !!this.argMode, this.argMode) {
2404
+ let m = this.argMode;
2405
+ if (dom.input.hidden = !0, dom.title.hidden = !0, dom.args.dataset.for !== this.idOf(m.item)) {
2406
+ dom.args.dataset.for = this.idOf(m.item);
2407
+ let fields = (m.item.arguments ?? []).map((a) => {
2408
+ if (a.type === "dropdown") {
2409
+ let sel = h(
2410
+ "select",
2411
+ { class: "qb-arg", name: a.name, "aria-label": a.placeholder ?? a.name },
2412
+ ...(a.options ?? []).map((o) => h("option", { value: o.value }, o.title))
2413
+ );
2414
+ return m.values[a.name] = sel.value, sel.addEventListener("change", () => m.values[a.name] = sel.value), sel;
2415
+ }
2416
+ let inp = h("input", {
2417
+ class: "qb-arg",
2418
+ name: a.name,
2419
+ type: a.type === "password" ? "password" : "text",
2420
+ placeholder: `${a.placeholder ?? a.name}${a.required ? "" : ` ${this.t("optional")}`}`,
2421
+ "aria-label": a.placeholder ?? a.name,
2422
+ autocomplete: "off",
2423
+ spellcheck: "false"
2424
+ });
2425
+ return inp.addEventListener("input", () => m.values[a.name] = inp.value), inp;
2426
+ });
2427
+ dom.args.replaceChildren(h("span", { class: "qb-arg-cmd" }, renderIcon(m.item.icon, 16), m.item.title), ...fields);
2428
+ }
2429
+ dom.args.hidden = !1;
2430
+ } else {
2431
+ dom.args.hidden = !0, delete dom.args.dataset.for, dom.args.replaceChildren(), dom.input.hidden = !hasInput, dom.title.hidden = hasInput, hasInput || (dom.title.textContent = v.title ?? "");
2432
+ let placeholder = this.renderer?.placeholder?.() ?? v.placeholder ?? (v.type === "root" ? this.config.placeholder ?? this.t("placeholder") : this.t("searchPlaceholder"));
2433
+ dom.input.placeholder !== placeholder && (dom.input.placeholder = placeholder), dom.input.value !== frame.query && (dom.input.value = frame.query);
2434
+ }
2435
+ let selected = frame.itemRows[frame.selected];
2436
+ selected && (v.type === "root" || v.type === "list" || v.type === "grid") ? dom.input.setAttribute("aria-activedescendant", `${this.instanceId}-opt-${selected.key.replace(/[^\w-]/g, "_")}`) : dom.input.removeAttribute("aria-activedescendant");
2437
+ let showHint = !!this.ai && v.type === "root" && !this.argMode && this.aiOptions?.fallback !== !1;
2438
+ dom.hint.hidden = !showHint, showHint && !dom.hint.childElementCount && dom.hint.append(h("span", null, this.t("askAi")), renderKbd("tab")), frame.loading > 0 ? dom.progress.dataset.active = "" : delete dom.progress.dataset.active;
2439
+ }
2440
+ renderFooter(frame) {
2441
+ let dom = this.dom;
2442
+ !this.toastState || !this._open ? this.renderFooterLeft(frame) : this.renderToast();
2443
+ let right = [], custom = this.renderer?.footerPrimary?.(), actions = this.actionsFor(this.selectedItem(frame), frame), primary = custom ?? (actions[0] ? { title: this.actionTitle(actions[0]), hotkey: "enter", run: () => this.runPrimary(frame) } : void 0);
2444
+ this.argMode ? right.push(this.footerButton(this.t("runItem", { title: this.argMode.item.title }), "enter", () => this.submitArgs(), !0)) : primary && right.push(this.footerButton(primary.title, primary.hotkey, primary.run, !0)), actions.length > (custom ? 0 : 1) && !this.argMode && right.push(h("span", { class: "qb-footer-sep" }), this.footerButton(this.t("actions"), this.actionsHotkey, () => this.openPanel())), dom.footerRight.replaceChildren(...right);
2445
+ }
2446
+ renderFooterLeft(frame) {
2447
+ let dom = this.dom, v = frame.view, left = [];
2448
+ if (frame.marked?.size)
2449
+ left.push(renderIcon("check-square", 14), h("span", null, this.t("selected", { count: frame.marked.size })));
2450
+ else if (this.stack.length > 1 && v.title) {
2451
+ let icon = renderIcon(frame.ext?.ext.icon ?? "layers", 14);
2452
+ icon && left.push(icon), left.push(h("span", null, v.title));
2453
+ } else if (this.config.footer) left.push(h("span", null, this.config.footer));
2454
+ else if (this.config.branding) {
2455
+ let a = h("a", { class: "qb-brand", href: "https://qikbar.com", target: "_blank", rel: "noopener" }, renderIcon("command", 13), "qikbar");
2456
+ left.push(a);
2457
+ }
2458
+ dom.footerLeft.replaceChildren(...left);
2459
+ }
2460
+ footerButton(title, hotkey, run, primary = !1) {
2461
+ let btn = h("button", { class: `qb-footer-btn${primary ? " qb-primary" : ""}`, type: "button" }, h("span", null, title), renderKbd(hotkey));
2462
+ return btn.addEventListener("pointerdown", (e) => e.preventDefault()), btn.addEventListener("click", run), btn;
2463
+ }
2464
+ renderToast() {
2465
+ let t = this.toastState, iconFor = (style) => style === "success" ? "check-circle" : style === "failure" ? "x-circle" : style === "loading" ? "loader" : "info", build = (cls) => {
2466
+ let icon = renderIcon(iconFor(t.style), 14);
2467
+ t.style === "loading" && icon.classList.add("qb-spin");
2468
+ let button = null;
2469
+ return t.act && (button = h("button", { class: "qb-toast-action", type: "button" }, h("span", null, t.act.title), t.act.shortcut ? renderKbd(t.act.shortcut) : null), button.addEventListener("pointerdown", (e) => e.preventDefault()), button.addEventListener("click", (e) => {
2470
+ e.stopPropagation(), this.runToastAction();
2471
+ })), h(
2472
+ "div",
2473
+ { class: this.cls(cls, "toast"), "data-style": t.style ?? "info", "data-action": t.act ? "" : null, role: "status" },
2474
+ icon,
2475
+ h("span", { class: "qb-toast-title" }, t.title),
2476
+ t.message ? h("span", { class: "qb-toast-msg" }, t.message) : null,
2477
+ button
2478
+ );
2479
+ };
2480
+ if (this._open && this.dom) {
2481
+ this.hud?.remove(), this.hud = void 0, t ? this.dom.footerLeft.replaceChildren(build("qb-toast")) : this.top && this.renderFooterLeft(this.top);
2482
+ return;
2483
+ }
2484
+ typeof document > "u" || (this.mount(), this.hud?.remove(), this.hud = void 0, !(!t || !this.dom) && (this.applyTheme(), this.hud = build("qb-hud"), this.dom.root.append(this.hud)));
2485
+ }
2486
+ renderLayer() {
2487
+ let dom = this.dom;
2488
+ if (!dom) return;
2489
+ let c = this.confirmState;
2490
+ if (!c) {
2491
+ dom.layer.replaceChildren();
2492
+ return;
2493
+ }
2494
+ if (dom.layer.firstChild) return;
2495
+ let cancel = h("button", { class: "qb-btn", type: "button" }, c.cancelLabel ?? this.t("cancel")), ok = h("button", { class: `qb-btn ${c.destructive ? "qb-btn-danger" : "qb-btn-primary"}`, type: "button" }, c.confirmLabel ?? this.t("confirm"), renderKbd("enter"));
2496
+ cancel.addEventListener("click", () => c.resolve(!1)), ok.addEventListener("click", () => c.resolve(!0)), ok.addEventListener("keydown", (e) => {
2497
+ e.key === "Enter" && (e.preventDefault(), c.resolve(!0));
2498
+ }), dom.layer.append(
2499
+ h(
2500
+ "div",
2501
+ { class: "qb-confirm-layer" },
2502
+ h(
2503
+ "div",
2504
+ { class: "qb-confirm", role: "alertdialog", "aria-modal": "true", "aria-label": c.title },
2505
+ h("div", { class: "qb-confirm-title" }, c.title),
2506
+ c.message ? h("div", { class: "qb-confirm-msg" }, c.message) : null,
2507
+ h("div", { class: "qb-confirm-buttons" }, cancel, ok)
2508
+ )
2509
+ )
2510
+ ), ok.focus();
2511
+ }
2512
+ /** Render Markdown with translated UI strings. */
2513
+ md(text) {
2514
+ return renderMarkdown(text, { copyLabel: this.t("copy") });
2515
+ }
2516
+ announce(text) {
2517
+ this.dom && (this.dom.live.textContent = text);
2518
+ }
2519
+ }, isFallback = (item) => !!item.id && (item.id.startsWith("fallback:") || item.id === "qikbar.ask-ai-fallback"), normalizeAlias = (alias) => alias.trim().toLowerCase().replace(/\s+/g, " ");
2520
+ function embedText(item) {
2521
+ return [item.title, item.subtitle, item.section, item.keywords?.join(", "), item.description].filter(Boolean).join(" \xB7 ");
2522
+ }
2523
+ function normalize(v) {
2524
+ let n = 0;
2525
+ for (let x of v) n += x * x;
2526
+ let len = Math.sqrt(n) || 1, out = new Float32Array(v.length);
2527
+ for (let i = 0; i < v.length; i++) out[i] = v[i] / len;
2528
+ return out;
2529
+ }
2530
+ function dot(a, b) {
2531
+ let s = 0, n = Math.min(a.length, b.length);
2532
+ for (let i = 0; i < n; i++) s += a[i] * b[i];
2533
+ return s;
2534
+ }
2535
+ function shallowEqual(a, b) {
2536
+ if (a === b) return !0;
2537
+ if (!a || !b) return !1;
2538
+ let ka = Object.keys(a);
2539
+ return ka.length !== Object.keys(b).length ? !1 : ka.every((k) => a[k] === b[k]);
2540
+ }
2541
+ async function withTimeout(p, ms) {
2542
+ let timer;
2543
+ try {
2544
+ return await Promise.race([Promise.resolve(p), new Promise((_, reject) => timer = setTimeout(() => reject(new Error("timeout")), ms))]);
2545
+ } finally {
2546
+ clearTimeout(timer);
2547
+ }
2548
+ }
2549
+ export {
2550
+ Bar,
2551
+ embedText,
2552
+ isView,
2553
+ normalizeAlias
2554
+ };
2555
+ //# sourceMappingURL=bar-P3SCR4SJ.js.map