@aparte/n8n-chat 0.2.0 → 0.3.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 (66) hide show
  1. package/README.md +98 -10
  2. package/dist/cdn/chunks/{chunk-IPWLCOPM.js → chunk-E55C7UF2.js} +2 -2
  3. package/dist/cdn/chunks/{chunk-IPWLCOPM.js.map → chunk-E55C7UF2.js.map} +1 -1
  4. package/dist/cdn/chunks/{chunk-VTTH7HGO.js → chunk-F2QIT4NR.js} +1 -1
  5. package/dist/cdn/chunks/{chunk-VTTH7HGO.js.map → chunk-F2QIT4NR.js.map} +1 -1
  6. package/dist/cdn/chunks/{chunk-CZ5742JA.js → chunk-F2TNPBN3.js} +1 -1
  7. package/dist/cdn/chunks/{chunk-CZ5742JA.js.map → chunk-F2TNPBN3.js.map} +1 -1
  8. package/dist/cdn/chunks/{chunk-OJFRNS5M.js → chunk-KY2H3HIJ.js} +2 -2
  9. package/dist/cdn/chunks/{chunk-OJFRNS5M.js.map → chunk-KY2H3HIJ.js.map} +1 -1
  10. package/dist/cdn/chunks/{chunk-IWAJFJNA.js → chunk-VLHCX6EH.js} +8 -5
  11. package/dist/cdn/chunks/chunk-VLHCX6EH.js.map +7 -0
  12. package/dist/cdn/chunks/{chunk-7JR7KL6J.js → chunk-XC2SVYFR.js} +2 -2
  13. package/dist/cdn/chunks/{chunk-7JR7KL6J.js.map → chunk-XC2SVYFR.js.map} +1 -1
  14. package/dist/cdn/chunks/{de-JS3CQEVR.js → de-M5OVUL5F.js} +1 -1
  15. package/dist/cdn/chunks/{de-JS3CQEVR.js.map → de-M5OVUL5F.js.map} +1 -1
  16. package/dist/cdn/chunks/{es-OHKGLFEF.js → es-JUSLSPF7.js} +1 -1
  17. package/dist/cdn/chunks/{es-OHKGLFEF.js.map → es-JUSLSPF7.js.map} +1 -1
  18. package/dist/cdn/chunks/{fr-6S44XMU5.js → fr-Z2Y3375Z.js} +1 -1
  19. package/dist/cdn/chunks/{fr-6S44XMU5.js.map → fr-Z2Y3375Z.js.map} +1 -1
  20. package/dist/cdn/chunks/{highlight-FGIKUPIF.js → highlight-ADUWBKTT.js} +2 -2
  21. package/dist/cdn/chunks/{highlight-FGIKUPIF.js.map → highlight-ADUWBKTT.js.map} +1 -1
  22. package/dist/cdn/chunks/{it-K4WYXXDJ.js → it-N53LIIX5.js} +1 -1
  23. package/dist/cdn/chunks/{it-K4WYXXDJ.js.map → it-N53LIIX5.js.map} +1 -1
  24. package/dist/cdn/chunks/{items-S4LF2DJA.js → items-GTJKLFZT.js} +3 -3
  25. package/dist/cdn/chunks/{items-S4LF2DJA.js.map → items-GTJKLFZT.js.map} +1 -1
  26. package/dist/cdn/chunks/{ja-BN7TZW62.js → ja-LJHMBKJ4.js} +1 -1
  27. package/dist/cdn/chunks/{ja-BN7TZW62.js.map → ja-LJHMBKJ4.js.map} +1 -1
  28. package/dist/cdn/chunks/{ko-ARHO7UI3.js → ko-XAQOC75B.js} +1 -1
  29. package/dist/cdn/chunks/{ko-ARHO7UI3.js.map → ko-XAQOC75B.js.map} +1 -1
  30. package/dist/cdn/chunks/{link-C46K5O7X.js → link-L4C4K5GE.js} +2 -2
  31. package/dist/cdn/chunks/{link-C46K5O7X.js.map → link-L4C4K5GE.js.map} +1 -1
  32. package/dist/cdn/chunks/{media-QI5BPERX.js → media-EOQEOMXK.js} +2 -2
  33. package/dist/cdn/chunks/{media-QI5BPERX.js.map → media-EOQEOMXK.js.map} +1 -1
  34. package/dist/cdn/chunks/{order-YISYH73K.js → order-T5L422AO.js} +2 -2
  35. package/dist/cdn/chunks/{order-YISYH73K.js.map → order-T5L422AO.js.map} +1 -1
  36. package/dist/cdn/chunks/{place-UFCH3NQE.js → place-UD2C3U5F.js} +2 -2
  37. package/dist/cdn/chunks/{place-UFCH3NQE.js.map → place-UD2C3U5F.js.map} +1 -1
  38. package/dist/cdn/chunks/{plan-KQWF73QI.js → plan-JJ3Z64NU.js} +2 -2
  39. package/dist/cdn/chunks/{plan-KQWF73QI.js.map → plan-JJ3Z64NU.js.map} +1 -1
  40. package/dist/cdn/chunks/{product-7UBLOMZ7.js → product-FNGKWEQP.js} +20 -4
  41. package/dist/cdn/chunks/product-FNGKWEQP.js.map +7 -0
  42. package/dist/cdn/chunks/{pt-BR-R7ZRM3GG.js → pt-BR-KMZM3WTU.js} +1 -1
  43. package/dist/cdn/chunks/{pt-BR-R7ZRM3GG.js.map → pt-BR-KMZM3WTU.js.map} +1 -1
  44. package/dist/cdn/chunks/{ru-FJNIMGMU.js → ru-3AG5HYY2.js} +1 -1
  45. package/dist/cdn/chunks/{ru-FJNIMGMU.js.map → ru-3AG5HYY2.js.map} +1 -1
  46. package/dist/cdn/chunks/{score-O2KEAYDS.js → score-3CGZEPWP.js} +2 -2
  47. package/dist/cdn/chunks/{score-O2KEAYDS.js.map → score-3CGZEPWP.js.map} +1 -1
  48. package/dist/cdn/chunks/{stats-GSXFRGYZ.js → stats-FGZCRFFK.js} +2 -2
  49. package/dist/cdn/chunks/{stats-GSXFRGYZ.js.map → stats-FGZCRFFK.js.map} +1 -1
  50. package/dist/cdn/chunks/{stock-53NVFLC3.js → stock-E72GAUMB.js} +2 -2
  51. package/dist/cdn/chunks/{stock-53NVFLC3.js.map → stock-E72GAUMB.js.map} +1 -1
  52. package/dist/cdn/chunks/{weather-VI2RCU4X.js → weather-5ZNWC2WM.js} +2 -2
  53. package/dist/cdn/chunks/{weather-VI2RCU4X.js.map → weather-5ZNWC2WM.js.map} +1 -1
  54. package/dist/cdn/chunks/{zh-CN-DUCWBXJP.js → zh-CN-DL6ZWLGA.js} +1 -1
  55. package/dist/cdn/chunks/{zh-CN-DUCWBXJP.js.map → zh-CN-DL6ZWLGA.js.map} +1 -1
  56. package/dist/cdn/n8n-chat.js +57 -57
  57. package/dist/cdn/n8n-chat.js.map +4 -4
  58. package/dist/create-chat.d.ts +27 -3
  59. package/dist/index.d.ts +2 -0
  60. package/dist/index.js +61 -40
  61. package/dist/index.js.map +1 -1
  62. package/dist/strings.d.ts +1 -1
  63. package/dist/style.css +1 -1
  64. package/package.json +7 -7
  65. package/dist/cdn/chunks/chunk-IWAJFJNA.js.map +0 -7
  66. package/dist/cdn/chunks/product-7UBLOMZ7.js.map +0 -7
package/README.md CHANGED
@@ -13,10 +13,11 @@ weather. [See it live](https://n8n-chat.apartejs.dev).
13
13
 
14
14
  - Rich cards your workflow writes as text: weather, order and booking, product, place, list, key
15
15
  figures, stock, plan, score, media, link. n8n's own chat shows the same answer as a code block.
16
+ - Extensible: your own cards, and aparté's plugins (maths, diagrams, charts) through `setup`.
16
17
  - Every option of `@n8n/chat` 1.43, the same defaults, the same session in the browser — and the
17
18
  Chat nodes' messages and buttons of a workflow that answers through response nodes.
18
19
  - Ten languages, keyboard and screen-reader access, readable contrast, a dark scheme.
19
- - About 100 KB (brotli) on the first load, against about 465 KB.
20
+ - About 143 KB compressed on the first load, against about 471 KB (measured 2026-10-31, `@n8n/chat` 1.44.7).
20
21
  - A handle to drive it from your page: `open`, `close`, `toggle`, `send`, `reset`, `setDisabled`,
21
22
  `destroy`.
22
23
  - MIT.
@@ -26,9 +27,9 @@ weather. [See it live](https://n8n-chat.apartejs.dev).
26
27
  ### From a CDN — no build step
27
28
 
28
29
  ```html
29
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/style.css">
30
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.3.0/dist/style.css">
30
31
  <script type="module">
31
- import { createChat } from 'https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/cdn/n8n-chat.js';
32
+ import { createChat } from 'https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.3.0/dist/cdn/n8n-chat.js';
32
33
 
33
34
  createChat({ webhookUrl: 'https://your-n8n.example.com/webhook/<id>/chat' });
34
35
  </script>
@@ -58,10 +59,10 @@ Replace the stylesheet and the import; the call stays as it is:
58
59
 
59
60
  ```diff
60
61
  - <link href="https://cdn.jsdelivr.net/npm/@n8n/chat/dist/style.css" rel="stylesheet" />
61
- + <link href="https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/style.css" rel="stylesheet" />
62
+ + <link href="https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.3.0/dist/style.css" rel="stylesheet" />
62
63
  <script type="module">
63
64
  - import { createChat } from 'https://cdn.jsdelivr.net/npm/@n8n/chat/dist/chat.bundle.es.js';
64
- + import { createChat } from 'https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/cdn/n8n-chat.js';
65
+ + import { createChat } from 'https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.3.0/dist/cdn/n8n-chat.js';
65
66
  createChat({ webhookUrl: 'https://your-n8n.example.com/webhook/<id>/chat' });
66
67
  </script>
67
68
  ```
@@ -108,7 +109,9 @@ memory on the agent only, n8n answers that request with an error.
108
109
  | `messageHistory` | a conversation to show when n8n has none (text, `type: 'component'`, `transparent`) | — |
109
110
  | `messageComponents` | functions that draw `type: 'component'` history messages | — |
110
111
  | `metadata` | sent with every message, as `metadata` in the trigger's output | — |
111
- | `allowFileUploads`, `allowedFilesMimeTypes` | let the person attach files, and which | `false`, any |
112
+ | `allowFileUploads`, `allowedFilesMimeTypes` | let the person attach files, and which (`'image/*,application/pdf'`, extensions too) | `false`, any |
113
+ | `cards` | draw the ` ```card-<name> ` blocks of an answer as [cards](#rich-cards) | `true` |
114
+ | `setup` | `(config) => stop?`: aparté's plugins and your own cards, on this chat ([below](#your-own-cards-and-apartés-plugins)) | — |
112
115
  | `enableMessageActions` | "Repost" and "Reuse" on the person's own messages | `false` |
113
116
  | `disabled` | block the input (`true`, or n8n's `{ value }`) | `false` |
114
117
  | `beforeMessageSent`, `afterMessageSent` | hooks around each message | — |
@@ -178,6 +181,91 @@ write JSON: it is exact every time, and a setting can turn it off for a chat tha
178
181
  cards. The [shop and booking workflows](https://n8n-chat.apartejs.dev/#workflows) do it that way.
179
182
  `cards: false` shows the blocks as code.
180
183
 
184
+ ## Your own cards, and aparté's plugins
185
+
186
+ The widget is built with [aparté](https://apartejs.dev), and `setup` hands you its config: anything
187
+ aparté does, this chat can do. A card of your own is a `defineCard`, and your workflow sends it as
188
+ ` ```card-<its name> `:
189
+
190
+ ```js
191
+ import { createChat, defineCard, el } from '@aparte/n8n-chat';
192
+
193
+ const ticket = defineCard({
194
+ name: 'ticket',
195
+ variants: ['card'],
196
+ // A card draws its own padding, from the kit's variable, as the shipped cards do.
197
+ styles: '.aparte-ticket-card { padding: var(--aparte-rich-card-padding) } .aparte-ticket-card .id { font-weight: 600 }',
198
+ icon: '<svg viewBox="0 0 24 24"><path d="M4 6h16v12H4z" fill="none" stroke="currentColor"/></svg>',
199
+ normalize: (raw) => (raw?.id ? { id: String(raw.id), subject: String(raw.subject ?? ''), status: raw.status } : null),
200
+ render: (t) => [el('span', { class: 'id', text: t.id }), el('p', { text: t.subject }), el('small', { text: t.status })],
201
+ skeleton: () => [],
202
+ label: (t) => `Ticket ${t?.id ?? ''}`,
203
+ fallback: (t) => `Ticket ${t.id}: ${t.subject}`,
204
+ });
205
+
206
+ createChat({
207
+ webhookUrl: '…',
208
+ setup: (config) => ticket.setup({ config }),
209
+ });
210
+ ```
211
+
212
+ Take `defineCard` from the widget's own module, as above, and from the same URL when you load
213
+ it from a CDN (`…/@aparte/n8n-chat@0.3.0/dist/cdn/n8n-chat.js`): the card and the chat then share
214
+ one copy of aparté. A kit loaded from another URL keeps its cards where the chat never looks.
215
+
216
+ ````md
217
+ Your ticket is open.
218
+
219
+ ```card-ticket
220
+ { "id": "T-42", "subject": "Refund for order 1001", "status": "Waiting for us" }
221
+ ```
222
+ ````
223
+
224
+ The same `setup` adds aparté's plugins — maths, diagrams, charts — each in one line:
225
+
226
+ ```js
227
+ import { setupKatex } from '@aparte/plugin-katex';
228
+ import 'katex/dist/katex.min.css'; // KaTeX's own sheet: without it a formula shows twice
229
+ import { setupMermaid } from '@aparte/plugin-mermaid';
230
+
231
+ createChat({
232
+ webhookUrl: '…',
233
+ setup: (config) => {
234
+ const stops = [setupKatex({}, config), setupMermaid({}, config)];
235
+ return () => stops.forEach((stop) => stop());
236
+ },
237
+ });
238
+ ```
239
+
240
+ What `setup` returns, if a function, runs on `destroy()`.
241
+
242
+ ### All of aparté, at three levels
243
+
244
+ The widget's options keep `@n8n/chat`'s names so a page switches without rewriting, but everything
245
+ underneath is aparté, and you can reach it:
246
+
247
+ - **The config** — `setup(config)` hands you the chat's own `AparteConfig`: plugins, cards, segment
248
+ and tool renderers, icons (`config.registerIcons`), the locale (`config.setLocale`), the actions on a
249
+ message (`config.registerAction`). See the [configuration guide](https://apartejs.dev/guides/customization/).
250
+ - **The elements** — `chat.element` is the widget's root; the chat inside it is aparté's
251
+ `<aparte-chat>`, its field `<aparte-composer>`, and their attributes are theirs to set:
252
+
253
+ ```js
254
+ const chat = createChat({ webhookUrl: '…' });
255
+ chat.element.querySelector('aparte-composer')?.setAttribute('placeholder', 'Ask about your order…');
256
+ ```
257
+ - **The look** — aparté's `--aparte-*` variables, beside n8n's `--chat--*` ones:
258
+
259
+ ```css
260
+ /* n8n's variables for what n8n's widget already styles; aparté's for the rest. */
261
+ .aparte-n8n { --chat--message--border-radius: 14px; --aparte-font-family: 'Inter', sans-serif; }
262
+ /* The theme maps some aparté tokens from n8n's on the chat itself: set those there. */
263
+ .aparte-n8n aparte-chat { --aparte-radius-input: 20px; }
264
+ ```
265
+
266
+ What does not apply here is what needs the agent's loop in the page — a tool run in the browser, an
267
+ approval of a tool call: an n8n workflow runs its tools itself, on n8n.
268
+
181
269
  ## The page the visitor is on
182
270
 
183
271
  `metadata` is sent with every message and reaches the workflow as `$json.metadata`. Send the page,
@@ -221,11 +309,11 @@ so the page puts a fresh token in `metadata` before every message.
221
309
  2. In the page:
222
310
 
223
311
  ```html
224
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/style.css">
312
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.3.0/dist/style.css">
225
313
  <script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"></script>
226
314
  <div id="turnstile"></div>
227
315
  <script type="module">
228
- import { createChat } from 'https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/cdn/n8n-chat.js';
316
+ import { createChat } from 'https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.3.0/dist/cdn/n8n-chat.js';
229
317
 
230
318
  // A Turnstile token is single-use and lasts five minutes: ask for a new one before each message.
231
319
  let widgetId;
@@ -304,7 +392,7 @@ or Angular components, inside an `.aparte-n8n` element.
304
392
 
305
393
  ## Compared with `@n8n/chat`
306
394
 
307
- | | `@n8n/chat` 1.43 | `@aparte/n8n-chat` |
395
+ | | `@n8n/chat` (options checked on 1.43.3, weight on 1.44.7) | `@aparte/n8n-chat` |
308
396
  | --- | --- | --- |
309
397
  | Drive it from the page | — | `open`, `close`, `toggle`, `send`, `reset`, `setDisabled`, `destroy` |
310
398
  | A new conversation | not until the browser's storage is cleared | `reset()` |
@@ -315,7 +403,7 @@ or Angular components, inside an `.aparte-n8n` element.
315
403
  | Contrast of the visitor's bubble | 2.55:1 | 4.7:1 (WCAG AA) |
316
404
  | Dark scheme | — | ✓ |
317
405
  | Rich cards | the JSON as text | drawn: order, booking, product, weather… |
318
- | Weight, first load (brotli) | ~465 KB | ~100 KB, +~103 KB with the first code block |
406
+ | Weight, first load (compressed) | ~471 KB | ~143 KB |
319
407
  | License | Sustainable Use License | MIT |
320
408
 
321
409
  ## Versions
@@ -1,2 +1,2 @@
1
- import{a as n}from"./chunk-IWAJFJNA.js";function p(a,{name:s,options:i,value:c,label:l}){if(!a.live||i.length===0)return null;let r=n("div",{class:"aparte-rich-card__segmented",attrs:{role:"group"}});l&&a.bind(r,l,"aria-label");for(let e of i){let d=e.value===c,t=n("button",{class:"aparte-rich-card__segment",attrs:{type:"button","aria-pressed":d?"true":"false","data-card-key":`${s}:${e.value}`}});typeof e.label=="function"?a.bind(t,e.label):t.textContent=e.label,t.addEventListener("click",()=>{if(t.getAttribute("aria-pressed")!=="true"){for(let u of r.querySelectorAll(".aparte-rich-card__segment"))u.setAttribute("aria-pressed",u===t?"true":"false");a.change(s,e.value)}}),r.append(t)}return r}export{p as a};
2
- //# sourceMappingURL=chunk-IPWLCOPM.js.map
1
+ import{a as n}from"./chunk-VLHCX6EH.js";function p(a,{name:s,options:i,value:c,label:l}){if(!a.live||i.length===0)return null;let r=n("div",{class:"aparte-rich-card__segmented",attrs:{role:"group"}});l&&a.bind(r,l,"aria-label");for(let e of i){let d=e.value===c,t=n("button",{class:"aparte-rich-card__segment",attrs:{type:"button","aria-pressed":d?"true":"false","data-card-key":`${s}:${e.value}`}});typeof e.label=="function"?a.bind(t,e.label):t.textContent=e.label,t.addEventListener("click",()=>{if(t.getAttribute("aria-pressed")!=="true"){for(let u of r.querySelectorAll(".aparte-rich-card__segment"))u.setAttribute("aria-pressed",u===t?"true":"false");a.change(s,e.value)}}),r.append(t)}return r}export{p as a};
2
+ //# sourceMappingURL=chunk-E55C7UF2.js.map
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../node_modules/.pnpm/@aparte+plugin-cards@0.29.2_@aparte+core@0.29.2/node_modules/@aparte/plugin-cards/src/kit/controls.ts"],
3
+ "sources": ["../../../node_modules/.pnpm/@aparte+plugin-cards@0.29.3_@aparte+core@0.29.3/node_modules/@aparte/plugin-cards/src/kit/controls.ts"],
4
4
  "sourcesContent": ["/**\n * Controls a card can carry: a row of choices, a switch, a slider. Each reports through\n * `ctx.change(name, value)`, so the card fires `aparte-card-change` and the app's\n * `onChange` answers with new data, drawn in place — a stock chart's range, a light's\n * brightness.\n *\n * A control is drawn only when something will answer it (`ctx.live`): without an\n * `onChange`, a button that does nothing would be a promise the card cannot keep\n * (ratified decision #8). Each control carries a `data-card-key`, so a redraw puts the\n * focus back on the control that was pressed.\n */\nimport type { CardContext } from './define.js';\nimport { el } from './dom.js';\n\nexport interface SegmentedOptions {\n /** The control's name in the change (`range`). */\n name: string;\n /** The choices; a label is a string or a function read again on a language switch. */\n options: Array<{ value: string; label: string | (() => string) }>;\n /** The choice in force. */\n value?: string;\n /** The group's accessible name. */\n label?: () => string;\n}\n\n/** A row of choices, one pressed (`aria-pressed`). `null` when nothing would answer it. */\nexport function segmented(ctx: CardContext, { name, options, value, label }: SegmentedOptions): HTMLElement | null {\n if (!ctx.live || options.length === 0) return null;\n const group = el('div', { class: 'aparte-rich-card__segmented', attrs: { role: 'group' } });\n if (label) ctx.bind(group, label, 'aria-label');\n for (const option of options) {\n const pressed = option.value === value;\n const button = el('button', {\n class: 'aparte-rich-card__segment',\n attrs: { type: 'button', 'aria-pressed': pressed ? 'true' : 'false', 'data-card-key': `${name}:${option.value}` },\n });\n if (typeof option.label === 'function') ctx.bind(button, option.label);\n else button.textContent = option.label;\n button.addEventListener('click', () => {\n if (button.getAttribute('aria-pressed') === 'true') return;\n // Pressed at once, before the app answers: a second press reads what was chosen.\n for (const other of group.querySelectorAll('.aparte-rich-card__segment')) other.setAttribute('aria-pressed', other === button ? 'true' : 'false');\n ctx.change(name, option.value);\n });\n group.append(button);\n }\n return group;\n}\n\nexport interface ToggleOptions {\n name: string;\n checked: boolean;\n /** What it switches (\"Living-room light\"). */\n label: () => string;\n}\n\n/** A switch (`role=\"switch\"`). `null` when nothing would answer it. */\nexport function toggle(ctx: CardContext, { name, checked, label }: ToggleOptions): HTMLElement | null {\n if (!ctx.live) return null;\n const button = el('button', {\n class: 'aparte-rich-card__toggle',\n attrs: { type: 'button', role: 'switch', 'aria-checked': checked ? 'true' : 'false', 'data-card-key': name },\n }, el('span', { class: 'aparte-rich-card__toggle-thumb', attrs: { 'aria-hidden': 'true' } }));\n ctx.bind(button, label, 'aria-label');\n button.addEventListener('click', () => {\n // Flipped at once, before the app answers: a second click before the answer flips it\n // back, rather than sending the same state twice.\n const next = button.getAttribute('aria-checked') !== 'true';\n button.setAttribute('aria-checked', next ? 'true' : 'false');\n ctx.change(name, next);\n });\n return button;\n}\n\nexport interface SliderOptions {\n name: string;\n value: number;\n min?: number;\n max?: number;\n step?: number;\n label: () => string;\n /** How the value reads beside it, and to a screen reader (\"60 %\"). */\n format?: (value: number) => string;\n}\n\n/**\n * A slider: the value beside it follows while it moves, the change is reported once it is\n * let go (`change`, not `input`) — one request for a drag, not one per pixel.\n */\nexport function slider(ctx: CardContext, { name, value, min = 0, max = 100, step = 1, label, format = String }: SliderOptions): HTMLElement | null {\n if (!ctx.live) return null;\n const input = el('input', {\n class: 'aparte-rich-card__slider-input',\n attrs: { type: 'range', min, max, step, value, 'data-card-key': name },\n });\n const shown = el('output', { class: 'aparte-rich-card__slider-value' });\n const name_ = el('span', { class: 'aparte-rich-card__slider-label' });\n ctx.bind(name_, label);\n ctx.bind(input, label, 'aria-label');\n const paint = (v: number) => {\n shown.textContent = format(v);\n input.setAttribute('aria-valuetext', format(v));\n };\n ctx.bind(shown, () => format(Number(input.value)));\n paint(value);\n input.addEventListener('input', () => paint(Number(input.value)));\n input.addEventListener('change', () => ctx.change(name, Number(input.value)));\n return el('label', { class: 'aparte-rich-card__slider' }, name_, input, shown);\n}\n"],
5
5
  "mappings": "wCA0BO,SAASA,EAAUC,EAAkB,CAAE,KAAAC,EAAM,QAAAC,EAAS,MAAAC,EAAO,MAAAC,CAAA,EAA+C,CAC/G,GAAI,CAACJ,EAAI,MAAQE,EAAQ,SAAW,EAAG,OAAO,KAC9C,IAAMG,EAAQC,EAAG,MAAO,CAAE,MAAO,8BAA+B,MAAO,CAAE,KAAM,OAAA,CAAA,CAAW,EACtFF,GAAOJ,EAAI,KAAKK,EAAOD,EAAO,YAAY,EAC9C,QAAWG,KAAUL,EAAS,CAC1B,IAAMM,EAAUD,EAAO,QAAUJ,EAC3BM,EAASH,EAAG,SAAU,CACxB,MAAO,4BACP,MAAO,CAAE,KAAM,SAAU,eAAgBE,EAAU,OAAS,QAAS,gBAAiB,GAAGP,CAAI,IAAIM,EAAO,KAAK,EAAA,CAAG,CACnH,EACG,OAAOA,EAAO,OAAU,WAAAP,EAAgB,KAAKS,EAAQF,EAAO,KAAK,EAChEE,EAAO,YAAcF,EAAO,MACjCE,EAAO,iBAAiB,QAAS,IAAM,CACnC,GAAIA,EAAO,aAAa,cAAc,IAAM,OAE5C,SAAWC,KAASL,EAAM,iBAAiB,4BAA4B,EAAGK,EAAM,aAAa,eAAgBA,IAAUD,EAAS,OAAS,OAAO,EAChJT,EAAI,OAAOC,EAAMM,EAAO,KAAK,EACjC,CAAC,EACDF,EAAM,OAAOI,CAAM,CACvB,CACA,OAAOJ,CACX",
6
6
  "names": ["segmented", "ctx", "name", "options", "value", "label", "group", "el", "option", "pressed", "button", "other"]
@@ -203,4 +203,4 @@ ${c}
203
203
  <button type="button" class="aparte-btn aparte-btn--sm aparte-btn--danger aparte-btn--solid" data-menu-action="confirm-delete">${i}</button>
204
204
  </div>
205
205
  </div>`}_openMenu(t,e){this._closeMenu();let s=t.dataset.convId,i=this._conversations.find(a=>a.id===s);if(!i)return;let r=document.createElement("div");r.className="aparte-menu aparte-conv-menu",r.setAttribute("role","menu"),r.setAttribute("aria-label",i.title||this._t("newChat")),r.innerHTML=this._menuMarkup(i),t.appendChild(r),e.setAttribute("aria-expanded","true"),this._open={id:s,row:t,button:e,menu:r},this._placeMenu(e,r),r.querySelector('[role="menuitem"]')?.focus(),document.addEventListener("pointerdown",this._onDocumentPointerDown,!0),document.addEventListener("pointerup",this._onDocumentPointerUp,!0),document.addEventListener("pointercancel",this._onDocumentPointerUp,!0),window.addEventListener("scroll",this._onWindowScroll,!0),window.addEventListener("resize",this._onWindowScroll)}_placeMenu(t,e){let s=t.getBoundingClientRect(),i=e.getBoundingClientRect(),r=s.bottom+hn;r+i.height>window.innerHeight-Te&&s.top-i.height-hn>=Te&&(r=s.top-i.height-hn);let o=getComputedStyle(this).direction==="rtl"?s.left:s.right-i.width;o=Math.max(Te,Math.min(o,window.innerWidth-i.width-Te)),e.style.top=`${r}px`,e.style.left=`${o}px`}_closeMenu(t=!1){let e=this._open;e&&(this._open=null,e.menu.remove(),e.button.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this._onDocumentPointerDown,!0),document.removeEventListener("pointerup",this._onDocumentPointerUp,!0),document.removeEventListener("pointercancel",this._onDocumentPointerUp,!0),this._pressInMenu=!1,window.removeEventListener("scroll",this._onWindowScroll,!0),window.removeEventListener("resize",this._onWindowScroll),t&&e.button.isConnected&&e.button.focus())}_pressInMenu=!1;_onDocumentPointerUp=()=>{this._pressInMenu=!1};_onDocumentPointerDown=t=>{let e=this._open;if(!e)return;let s=ht(t);this._pressInMenu=!!s&&e.menu.contains(s),!(e.menu.contains(s)||e.button.contains(s))&&this._closeMenu()};_onWindowScroll=()=>{this._closeMenu()};_onFocusOut=t=>{let e=this._open;if(!e)return;let s=t.relatedTarget;!s&&this._pressInMenu||s&&(e.menu.contains(s)||e.button.contains(s))||e.menu.contains(t.target)&&this._closeMenu()};_manage(t,e){if(!this.hasAttribute("manage")||t.defaultPrevented)return;let s=k(this).getConversationManager();if(!s){if(this._warnedNoManager)return;this._warnedNoManager=!0,console.warn("[aparte-conversation-list] `manage` is set but no conversation manager is registered, so the row menu writes nothing. Call setConversationManager(manager) on your config, or drop `manage` and handle the events yourself.");return}e(s).catch(i=>{console.warn("[aparte-conversation-list] the conversation manager refused the change:",i)})}_onMenuAction(t){let e=this._open;if(!e)return;let s=this._conversations.find(r=>r.id===e.id);if(!s){this._closeMenu();return}let i=s.id;switch(t){case"rename":this._closeMenu(),this._startRename(e.row,s);return;case"pin":if(this._closeMenu(!0),s.pinnedAt){let r=new CustomEvent("aparte-conversation-unpin",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.unpin(i))}else{let r=new CustomEvent("aparte-conversation-pin",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.pin(i))}return;case"archive":if(this._closeMenu(!0),s.archivedAt){let r=new CustomEvent("aparte-conversation-unarchive",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.unarchive(i))}else{let r=new CustomEvent("aparte-conversation-archive",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.archive(i))}return;case"delete":{let r=[...e.menu.childNodes],a=document.createElement("div");a.innerHTML=this._confirmMarkup(s),e.menu.append(...a.childNodes),e.menu.setAttribute("role","dialog"),e.menu.setAttribute("aria-label",this._confirmQuestion(s)),e.menu.querySelector('[data-menu-action="cancel"]')?.focus();for(let o of r)o.remove();this._placeMenu(e.button,e.menu);return}case"cancel":this._closeMenu(!0);return;case"confirm-delete":{this._closeMenu(!0);let r=new CustomEvent("aparte-conversation-delete",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.delete(i));return}}}_menuFocusables(){let t=this._open;return t?Array.from(t.menu.querySelectorAll('[role="menuitem"], [data-menu-action]')):[]}_onMenuKeydown(t){let e=this._menuFocusables(),s=e.indexOf(pt(this)),i=r=>{t.preventDefault(),e[(r+e.length)%e.length]?.focus()};switch(t.key){case"Escape":t.preventDefault(),this._closeMenu(!0);return;case"Tab":t.preventDefault(),this._closeMenu(!0);return;case"ArrowDown":i(s+1);return;case"ArrowUp":i(s-1);return;case"Home":i(0);return;case"End":i(e.length-1);return}}_startRename(t,e){let s=t.querySelector(".aparte-conv-item__select");if(!s)return;let i=document.createElement("input");i.type="text",i.className="aparte-field aparte-field--sm aparte-conv-item__input",i.value=e.title,i.setAttribute("aria-label",this._t("conversationTitle")),i.dataset.renameId=e.id,s.replaceWith(i),this._renaming={id:e.id,input:i,done:!1},i.addEventListener("blur",r=>{let a=r.relatedTarget;this._finishRename(!0,!a||this.contains(a))}),i.focus(),i.select()}_finishRename(t,e){let s=this._renaming;if(!s||s.done)return;s.done=!0;let i=this._conversations.find(a=>a.id===s.id),r=s.input.value.trim();if(this._render(),t&&i&&r&&r!==i.title){let a=new CustomEvent("aparte-conversation-rename",{detail:{id:i.id,title:r},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(a),this._manage(a,o=>o.updateTitle(i.id,r))}e&&this.querySelector(`[data-select-id="${z(s.id)}"]`)?.focus()}_onClick=t=>{let e=t.target,s=e.closest("[data-menu-action]");if(s&&this._open?.menu.contains(s)){t.stopPropagation(),this._onMenuAction(s.dataset.menuAction);return}let i=e.closest("[data-more-id]");if(i){t.stopPropagation(),this._open?.button===i?this._closeMenu(!0):this._openMenu(i.closest("[data-conv-id]"),i);return}if(e.closest("[data-rename-id]"))return;let r=e.closest("[data-select-id]");r&&(this._closeMenu(),this.dispatchEvent(new CustomEvent("aparte-conversation-select",{detail:{id:r.dataset.selectId},bubbles:!0,composed:!0})))};_onKeydown=t=>{let e=t.target;if(this._open?.menu.contains(e)){this._onMenuKeydown(t);return}if(e.matches("[data-rename-id]")){t.key==="Enter"?(t.preventDefault(),this._finishRename(!0,!0)):t.key==="Escape"&&(t.preventDefault(),this._finishRename(!1,!0));return}};_updateActiveState(){this.querySelectorAll("[data-conv-id]").forEach(e=>{let s=e.dataset.convId===this._activeId;e.classList.toggle("aparte-conv-item--active",s),e.querySelector("[data-select-id]")?.setAttribute("aria-current",s?"page":"false")})}};$(Ve);customElements.get("aparte-conversation-list")||customElements.define("aparte-conversation-list",Ve);var aa=n=>typeof n=="string"||typeof n=="object"&&n!==null&&typeof n.label=="string",Vr=n=>{try{let t=JSON.parse(n);return Array.isArray(t)?t.filter(aa):[]}catch{return console.warn('[aparte-suggestions] `suggestions` is not a JSON array. Use ["\u2026"] or [{"label": "\u2026", "prompt": "\u2026"}].'),[]}},Yr=n=>typeof n=="string"?n:n.label,Qr=n=>typeof n=="string"?n:n.prompt??n.label,Ye=class extends HTMLElement{static get observedAttributes(){return["suggestions","target","empty-only"]}_suggestions=[];_composer=null;_transcript=null;_transcriptObserver=null;_sent=!1;_wasEmpty=!0;_hidOwn=!1;_onSend=()=>{this.hasAttribute("empty-only")&&(this._transcript||this._watchTranscript(),this._sent=!0,this._applyEmptyOnly())};_applyEmptyOnly=()=>{let t=this._transcript?ia(this._transcript):!0;t&&!this._wasEmpty&&(this._sent=!1),this._wasEmpty=t,this._setHidden(!t||this._sent)};_onConfigChange=()=>{let t=this.querySelector(".aparte-suggestions");t&&t.setAttribute("aria-label",this._groupLabel())};get suggestions(){return this._suggestions}set suggestions(t){this._suggestions=typeof t=="string"?Vr(t):Array.isArray(t)?t.filter(aa):[],this.isConnected&&this._render()}connectedCallback(){this.hasAttribute("suggestions")&&this._readAttribute(),this._render(),this._watchComposer(),window.addEventListener("aparte-config-change",this._onConfigChange)}disconnectedCallback(){this._composer?.removeEventListener("aparte-send",this._onSend),this._composer=null,this._transcriptObserver?.disconnect(),this._transcriptObserver=null,this._transcript=null,window.removeEventListener("aparte-config-change",this._onConfigChange)}attributeChangedCallback(t){this.isConnected&&(t==="suggestions"?(this._readAttribute(),this._render()):t==="target"?this._watchComposer():t==="empty-only"&&(this._watchTranscript(),this.hasAttribute("empty-only")||(this._sent=!1,this._setHidden(!1))))}_groupLabel(){return k(this).t("suggestionsLabel")||"Suggested prompts"}_parsed=null;_readAttribute(){let t=this.getAttribute("suggestions");t===null||t===this._parsed||(this._parsed=t,this._suggestions=Vr(t))}_resolveComposer(){let t=this.closest("aparte-composer");if(t)return t;let e=this.getAttribute("target");if(e){let i=document.getElementById(e)?.querySelector("aparte-composer");if(i)return i;for(let r of document.querySelectorAll("aparte-composer[target]"))if(r.getAttribute("target")===e)return r}return document.querySelector("aparte-composer")}_watchComposer(){this._composer?.removeEventListener("aparte-send",this._onSend),this._composer=this._resolveComposer(),this._composer?.addEventListener("aparte-send",this._onSend),this._watchTranscript()}_resolveTranscript(){let t=this.getAttribute("target")??this._composer?.getAttribute("target")??null,e=Z(this._composer)??Z(this)??(t?document.getElementById(t):null);return e?e.matches("aparte-chat-viewport")?e:e.querySelector("aparte-chat-viewport"):null}_watchTranscript(){let t=this.hasAttribute("empty-only")?this._resolveTranscript():null;t!==this._transcript&&(this._transcriptObserver?.disconnect(),this._transcriptObserver=null,this._transcript=t,t&&(this._transcriptObserver=new MutationObserver(this._applyEmptyOnly),this._transcriptObserver.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["loading"]}))),this.hasAttribute("empty-only")&&this._applyEmptyOnly()}_setHidden(t){if(t){if(this.hidden)return;this.hidden=!0,this._hidOwn=!0}else this._hidOwn&&(this.hidden=!1,this._hidOwn=!1)}_render(){if(this.replaceChildren(),this._suggestions.length===0){this.setAttribute("data-empty","");return}this.removeAttribute("data-empty");let t=document.createElement("div");t.className="aparte-suggestions",t.setAttribute("role","group"),t.setAttribute("aria-label",this._groupLabel());for(let e of this._suggestions){let s=document.createElement("button");s.type="button",s.className="aparte-btn aparte-btn--surface aparte-btn--pill aparte-suggestion",s.textContent=Yr(e);let i=Qr(e);i!==s.textContent&&(s.title=i),s.addEventListener("click",()=>this._activate(e)),t.appendChild(s)}this.appendChild(t)}_activate(t){let e={label:Yr(t),prompt:Qr(t)};if(!this.dispatchEvent(new CustomEvent("aparte-suggestion",{detail:e,bubbles:!0,composed:!0,cancelable:!0})))return;let i=this._composer??this._resolveComposer();if(!i){console.warn("[aparte-suggestions] no <aparte-composer> to send through \u2014 put the element inside one, or point `target` at the chat it serves.");return}i!==this._composer&&this._watchComposer();let r=this.contains(document.activeElement);i.setValue(e.prompt),this.getAttribute("mode")==="fill"?i.focus():(i.submit(),r&&i.focus())}};$(Ye);customElements.get("aparte-suggestions")||customElements.define("aparte-suggestions",Ye);var Xr=(n,t)=>{let e=Number(n);return n!==null&&Number.isFinite(e)&&e>0&&e<=1?e:t},Xl=n=>(n instanceof Element?n.closest("aparte-chat, [data-aparte-chat]"):null)?.id||void 0,U=(n,t,e)=>{let s=document.createElement(n);return s.className=t,e!==void 0&&(s.textContent=e),s},Jr="http://www.w3.org/2000/svg",Jl=()=>{let n=document.createElementNS(Jr,"svg");n.setAttribute("class","aparte-context__ring"),n.setAttribute("viewBox","0 0 36 36");for(let t of["track","value"]){let e=document.createElementNS(Jr,"circle");e.setAttribute("class",`aparte-context__${t}`),e.setAttribute("cx","18"),e.setAttribute("cy","18"),e.setAttribute("r","15.5"),t==="value"&&e.setAttribute("pathLength","100"),n.appendChild(e)}return n},Zr=n=>!!n&&typeof n.getMessages=="function",Zl=n=>{if(!n)return null;if(Zr(n))return n;let t=n.viewport??n.querySelector("aparte-chat-viewport");return Zr(t)?t:null},tc=0,ec={system:0,tools:0,summary:0,messages:0},Qe=class extends HTMLElement{static get observedAttributes(){return["window","warn","danger","target","variant","used"]}_used=null;_level=null;_compactRequested=!1;_lastDone=null;_viewChanged=!1;_blank=!1;_overflow=!1;_compact=null;_failure="";_open=!1;_measured=null;_seen=null;_panelSignature="";_remember(t){let e=t instanceof Element?Z(t):null;e&&(this._seen=e)}_onDone=t=>{let e=t.detail;!e?.usage||!this._isMine(e.targetId)||(this._remember(t.target),this._used=Me(e.usage),this._lastDone={messageId:e.messageId,usage:e.usage},this._viewChanged=!1,this._blank=!1,this._overflow=!1,this._render(!0))};_onReset=t=>{this._isMine(Xl(t.target))&&(this._remember(t.target),this._used=null,this._lastDone=null,this._viewChanged=!1,this._overflow=!1,this._compact=null,this._blank=!0,this._render())};_onLoaded=t=>{let e=t.detail;if(!this._isMine(e?.targetId))return;this._remember(t.target),this._blank=!1,this._lastDone=null,this._viewChanged=!1,this._overflow=!1,this._compact=null;let r=[...t.target?.getMessages?.()??[]].reverse().find(a=>a.role==="assistant"&&a.usage);this._used=r?.usage?Me(r.usage):null,this._render()};_onCompactStart=t=>{let e=t.detail;this._isMine(e?.targetId)&&(this._compact="running",this._failure="",this._render())};_onCompacted=t=>{let e=t.detail;if(this._isMine(e?.targetId)){if(this._compactRequested=!1,this._compact=null,e?.skipped){this._render();return}this._viewChanged=!0,this._overflow=!1,this._messages()||(this._used=null),this._render()}};_onCompactError=t=>{let e=t.detail;this._isMine(e?.targetId)&&(this._compactRequested=!1,this._compact=e?.aborted?null:"failed",this._failure=e?.aborted?"":typeof e?.error=="string"?e.error:"",this._render())};_onMessageError=t=>{let e=t.detail;this._isMine(e?.targetId)&&e?.error?.code===H.USAGE_CONTEXT_EXCEEDED&&(this._remember(t.target),this._overflow=!0,this._render())};_onRerender=()=>this._render();get used(){return this._measured?.used??this._used}set used(t){t==null?this.removeAttribute("used"):this.setAttribute("used",String(t))}get window(){return this._window()}set window(t){t==null?this.removeAttribute("window"):this.setAttribute("window",String(t))}get level(){return this._level}get measure(){return this._measured}connectedCallback(){window.addEventListener("aparte-message-done",this._onDone),window.addEventListener("aparte-message-error",this._onMessageError),window.addEventListener("aparte-compact-start",this._onCompactStart),window.addEventListener("aparte-compact-done",this._onCompacted),window.addEventListener("aparte-compact-error",this._onCompactError),window.addEventListener("aparte-reset-done",this._onReset),window.addEventListener("aparte-conversation-loaded",this._onLoaded),window.addEventListener("aparte-config-change",this._onRerender),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),this._render()}disconnectedCallback(){window.removeEventListener("aparte-message-done",this._onDone),window.removeEventListener("aparte-message-error",this._onMessageError),window.removeEventListener("aparte-compact-start",this._onCompactStart),window.removeEventListener("aparte-compact-done",this._onCompacted),window.removeEventListener("aparte-compact-error",this._onCompactError),window.removeEventListener("aparte-reset-done",this._onReset),window.removeEventListener("aparte-conversation-loaded",this._onLoaded),window.removeEventListener("aparte-config-change",this._onRerender),this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),this._stopListeningWhileOpen()}attributeChangedCallback(t){if(t==="used"){let e=Number(this.getAttribute("used"));this._used=this.hasAttribute("used")&&Number.isFinite(e)&&e>=0?e:null}this.isConnected&&this._render()}_cfg(){return k(this._chat()??this)}_window(){let t=Number(this.getAttribute("window"));if(this.hasAttribute("window")&&Number.isFinite(t)&&t>0)return t;let e=this._cfg().getCurrentModel();return e?.contextWindow&&e.contextWindow>0?e.contextWindow:null}_ownTargetId(){let t=this.getAttribute("target");if(t)return t;let e=this.parentElement;for(;e;){if((e.tagName.toLowerCase()==="aparte-chat"||e.hasAttribute("data-aparte-chat"))&&e.id)return e.id;e=e.parentElement}}_isMine(t){let e=this._ownTargetId();return!t||!e||t===e}_chat(){let t=this.getAttribute("target");if(t){let i=this.getRootNode().getElementById?.(t)??document.getElementById(t);if(i)return i}let e=Z(this);return e||(this._seen?.isConnected?this._seen:null)}_messages(){let t=Zl(this._chat());if(!t)return null;try{return t.getMessages()}catch{return null}}_measure(t){let e=this._messages(),s=this._lastDone,i=e&&s?.messageId?e.map(a=>a.id===s.messageId&&!a.usage?{...a,usage:s.usage}:a):e,r=!!i?.some(a=>a.role==="assistant"&&a.usage);return i&&(r&&!this._blank||this._overflow&&i.length>0)?Or({messages:i,config:this._cfg(),windowOverride:t,viewChanged:this._viewChanged}):this._used===null?null:{window:t,used:this._used,estimated:!1,parts:{...ec},other:this._used}}_render(t=!1){let e=this._window(),s=e===null?null:this._measure(e);if(this._compact?this.setAttribute("data-compact",this._compact):this.removeAttribute("data-compact"),e===null||s===null){this._measured=null,this.setAttribute("data-empty",""),this.removeAttribute("data-level"),this._open=!1,this._stopListeningWhileOpen(),this._panelSignature="",this.replaceChildren(),this._level=null;return}this._measured=s,this.removeAttribute("data-empty");let i=s.used,r=Math.min(1,i/e),a=Xr(this.getAttribute("warn"),.75),o=Xr(this.getAttribute("danger"),.9),l=this._overflow||r>=o?"danger":r>=a?"warn":"ok";this.setAttribute("data-level",l);let c=this.getAttribute("variant")==="ring",d=this.querySelector(".aparte-context");d&&d.classList.contains("aparte-context--ring")!==c&&(this.replaceChildren(),d=null,this._panelSignature="");let u=this.querySelector('[role="meter"]'),h=this.querySelector(".aparte-context__text"),f=this.querySelector(".aparte-context__toggle"),_=this.querySelector(".aparte-context__name"),p=this.querySelector(".aparte-context__panel");(!d||!u||!h||!f||!_||!p)&&(d=U("div",c?"aparte-context aparte-context--ring":"aparte-context"),u=c?Jl():U("div","aparte-progress"),u.setAttribute("role","meter"),c||u.appendChild(U("div","aparte-progress__bar")),f=U("button","aparte-btn aparte-btn--ghost aparte-btn--sm aparte-context__toggle"),f.type="button",_=U("span","aparte-sr-only"),_.classList.add("aparte-context__name"),h=U("span","aparte-context__text"),f.append(_,h),p=U("div","aparte-context__panel aparte-popover"),p.id=`aparte-context-panel-${++tc}`,p.setAttribute("role","group"),p.hidden=!0,f.setAttribute("aria-controls",p.id),d.append(u,f,p),this.replaceChildren(d),this._panelSignature="");let m=this._cfg(),T=m.getLocale().tag||void 0,x=new Intl.NumberFormat(T,{notation:"compact",maximumFractionDigits:1}),R=s.estimated?"~":"",b=`${R}${x.format(i)} / ${x.format(e)}`,y=Math.round(r*100),g=m.t("contextLabel")||"Context window";if(c){let w=u.querySelector(".aparte-context__value");w?.style.setProperty("--aparte-context-ratio",String(y)),w?.classList.toggle("aparte-context__value--empty",y===0),d.title=b}else u.style.setProperty("--aparte-progress-value",String(y));if(u.setAttribute("aria-valuemin","0"),u.setAttribute("aria-valuemax",String(e)),u.setAttribute("aria-valuenow",String(i)),u.setAttribute("aria-label",`${g}: ${b}`),_.textContent=`${g}: `,f.setAttribute("aria-expanded",String(this._open)),h.textContent=c?`${R}${new Intl.NumberFormat(T,{style:"percent",maximumFractionDigits:0}).format(y/100)}`:b,p.setAttribute("aria-label",g),p.hidden=!this._open,this._open?this._renderPanel(p,s,e,x):this._panelSignature="",l!==this._level){this._level=l;let w=this._ownTargetId(),E={level:l,used:i,window:e,ratio:r,targetId:w};this.dispatchEvent(new CustomEvent("aparte-context-threshold",{detail:E,bubbles:!0,composed:!0})),l!=="danger"&&(this._compactRequested=!1)}t&&l==="danger"&&this.hasAttribute("auto-compact")&&!this._compactRequested&&(this._compactRequested=!0,window.dispatchEvent(new CustomEvent("aparte-compact",{detail:{targetId:this._ownTargetId(),auto:!0,window:e}})))}_renderPanel(t,e,s,i){let r=this._cfg(),a=r.getCompactor(),o=this._chat(),l=this._ownTargetId(),c=null;try{c=a?.preview?.({target:o,...l?{targetId:l}:{}})??null}catch{c=null}let{parts:d,used:u}=e,h=d.system+d.tools+d.summary+d.messages,f=h>u&&h>0?u/h:1,_=e.estimated?"~":"",p=[{key:"system",label:r.t("contextSystem")||"System prompt",tokens:d.system*f,approx:"~"},{key:"tools",label:r.t("contextTools")||"Tools",tokens:d.tools*f,approx:"~"},{key:"summary",label:r.t("contextSummary")||"Summary",tokens:d.summary*f,approx:"~"},{key:"messages",label:r.t("contextMessages")||"Messages",tokens:d.messages*f,approx:"~"},{key:"other",label:r.t("contextOther")||"Other",tokens:f<1?0:e.other,approx:"~"},{key:"free",label:r.t("contextFree")||"Free",tokens:Math.max(0,s-u),approx:_}],m=`${_}${i.format(u)} / ${i.format(s)}`,T=c&&c.tokens>0?(r.t("contextReclaim")||"Compacting now would free ~{n} tokens").replace("{n}",()=>i.format(Math.round(c.tokens))):"",x=!!a&&!!c&&this._compact===null,R=U("ul","aparte-context__rows");for(let v of p){let S=U("li","aparte-context__row");S.setAttribute("data-part",v.key),S.append(U("span","aparte-context__row-label",v.label)),S.append(U("span","aparte-context__row-value",`${v.approx}${i.format(Math.round(v.tokens))}`));let L=U("div","aparte-progress aparte-context__row-bar");L.setAttribute("aria-hidden","true"),L.style.setProperty("--aparte-progress-value",String(Math.round(Math.min(1,v.tokens/s)*100))),L.appendChild(U("div","aparte-progress__bar")),S.append(L),R.append(S)}let b=U("li","aparte-context__row aparte-context__row--total");b.setAttribute("data-part","total"),b.append(U("span","aparte-context__row-label",r.t("contextTotal")||"Total"),U("span","aparte-context__row-value",m)),R.append(b);let y=[R];if(this._compact==="running"){let v=U("p","aparte-context__status aparte-shimmer",r.t("checkpointPending")||"Summarising the context\u2026");v.setAttribute("role","status"),y.push(v)}else if(this._compact==="failed"){let v=U("p","aparte-context__status aparte-context__status--failed",r.t("checkpointFailed")||"Couldn't summarise the context");v.setAttribute("role","status"),this._failure&&(v.title=this._failure,v.appendChild(U("span","aparte-sr-only",`: ${this._failure}`))),y.push(v,this._action("retry",r.t("retry")||"Retry"))}T&&y.push(U("p","aparte-context__reclaim",T)),x&&y.push(this._action("compact",r.t("contextCompactNow")||"Compact now"));let g=U("div","aparte-context__content");if(g.append(...y),g.innerHTML===this._panelSignature)return;this._panelSignature=g.innerHTML;let w=document.activeElement,E=w&&t.contains(w)?w.getAttribute("data-context-action")??"":null;t.replaceChildren(...Array.from(g.childNodes)),E!==null&&((E?t.querySelector(`[data-context-action="${z(E)}"]`):null)??this.querySelector(".aparte-context__toggle"))?.focus()}_action(t,e){let s=U("button","aparte-btn aparte-btn--sm aparte-btn--surface aparte-context__action",e);return s.type="button",s.setAttribute("data-context-action",t),s}async _compactNow(t){let e=this._cfg().getCompactor(),s=this._ownTargetId();if(!e){window.dispatchEvent(new CustomEvent("aparte-compact",{detail:{targetId:s}}));return}this._compact="running",this._failure="",this._render();let i=null;try{let r=await e.compact({target:this._chat(),...s?{targetId:s}:{},force:!0,reason:t});r.ok?r.skipped||(this._viewChanged=!0):i=r.error}catch(r){i=r instanceof Error?r.message:String(r)}this._compact==="running"&&(this._compact=i===null?null:"failed",this._failure=i??""),this.isConnected&&this._render()}_onClick=t=>{let e=t.target,s=e?.closest?.("[data-context-action]");if(s){this._compactNow(s.getAttribute("data-context-action")==="retry"?"retry":"manual");return}e?.closest?.(".aparte-context__panel")||e?.closest?.(".aparte-context")&&this._setOpen(!this._open)};_setOpen(t,e=!1){t!==this._open&&(this._open=t,t?this._listenWhileOpen():this._stopListeningWhileOpen(),this._render(),t?this._place():e&&this.querySelector(".aparte-context__toggle")?.focus())}_onDocumentClick=t=>{t.composedPath().includes(this)||this._setOpen(!1)};_onKeydown=t=>{!this._open||t.key!=="Escape"||(t.preventDefault(),t.stopPropagation(),this._setOpen(!1,!0))};_onDocumentKeydown=t=>{t.key==="Escape"&&this._setOpen(!1,this.contains(document.activeElement))};_listenWhileOpen(){document.addEventListener("click",this._onDocumentClick),document.addEventListener("keydown",this._onDocumentKeydown)}_stopListeningWhileOpen(){document.removeEventListener("click",this._onDocumentClick),document.removeEventListener("keydown",this._onDocumentKeydown)}_place(){let t=this.querySelector(".aparte-context__panel");if(!t)return;t.removeAttribute("data-placement"),t.removeAttribute("data-align");let e=this.getBoundingClientRect(),s=t.getBoundingClientRect();s.height>0&&e.top<s.height&&t.setAttribute("data-placement","below"),s.width>0&&s.right>document.documentElement.clientWidth&&t.setAttribute("data-align","end")}};$(Qe);customElements.get("aparte-context")||customElements.define("aparte-context",Qe);var ta=60,sc=6,nc=150,ic=4,rc=1,Xe=class extends HTMLElement{static get observedAttributes(){return["target","every"]}_host=null;_mutations=null;_resizes=null;_intersections=null;_observedBubbles=[];_observedSurface=null;_rebuildQueued=!1;_pickQueued=!1;_currentId=null;_visible=new Map;_onScreen=new Set;_onScreenObserver=null;_held=null;_settleTimer=null;_settleSurface=null;_alignPasses=0;_written=new Map;_onConfigChange=()=>this._rebuild();_onSurfaceScroll=()=>this._bumpSettle();get currentMessageId(){return this._currentId}connectedCallback(){this.classList.contains("aparte-scroll-rail")||this.classList.add("aparte-scroll-rail"),this.getAttribute("role")||this.setAttribute("role","navigation"),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),window.addEventListener("aparte-config-change",this._onConfigChange),this._attach()}disconnectedCallback(){this._detach(),this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),window.removeEventListener("aparte-config-change",this._onConfigChange)}attributeChangedCallback(t){this.isConnected&&(t==="target"?this._attach():this._rebuild())}_findHost(){let t=this.getAttribute("target");if(t)return document.getElementById(t);let e=this.parentElement;for(;e;){if(e.tagName.toLowerCase()==="aparte-chat"||e.hasAttribute("data-aparte-chat"))return e;e=e.parentElement}return null}_attach(){if(this._detach(),this._host=this._findHost(),!this._host){this._rebuild();return}if(typeof MutationObserver<"u"&&(this._mutations=new MutationObserver(t=>{t.some(e=>!this.contains(e.target))&&this._queueRebuild()}),this._mutations.observe(this._host,{childList:!0,subtree:!0,characterData:!0})),typeof ResizeObserver<"u"){this._resizes=new ResizeObserver(()=>this._layout()),this._resizes.observe(this._host);let t=this._viewport();t&&this._resizes.observe(t)}this._rebuild()}_detach(){this._mutations?.disconnect(),this._mutations=null,this._resizes?.disconnect(),this._resizes=null,this._unobserve(),this._release(),this._host=null}_queueRebuild(){this._rebuildQueued||(this._rebuildQueued=!0,requestAnimationFrame(()=>{this._rebuildQueued=!1,this._rebuild()}))}_viewport(){return this._host?.querySelector("aparte-chat-viewport")??null}_scrollSurface(){let t=this._viewport();return t?t.querySelector(".aparte-viewport-container")??t:null}_bubbles(){let t=this._viewport();if(!t)return[];let e=this.getAttribute("every")==="message"?"message":"user",s=Array.from(t.querySelectorAll("aparte-chat-bubble[message-id]"));return e==="message"?s:s.filter(i=>i.getAttribute("data-role")==="user")}_excerpt(t){let s=((t.querySelector(".aparte-message-content")??t).textContent??"").replace(/\s+/g," ").trim();return s.length>ta?`${s.slice(0,ta-1).trimEnd()}\u2026`:s}_tickLabel(t){let e=k(this).getLocale(),s=t.getAttribute("data-role")==="user"?e.roleNameUser??"You":e.roleNameAssistant??"Assistant",i=this._excerpt(t);return i?`${s}: ${i}`:s}_list(){return this.querySelector(":scope > .aparte-scroll-rail__list")}_rebuild(){let t=this._bubbles(),s=k(this).getLocale().scrollRailLabel??"Conversation outline";if(this.getAttribute("aria-label")!==s&&this.setAttribute("aria-label",s),t.length<2){this.setAttribute("data-empty",""),this.replaceChildren(),this._unobserve(),this._currentId=null,this._write("--aparte-scroll-rail-hit-size","");return}this.removeAttribute("data-empty");let i=this._list();i||(i=document.createElement("ol"),i.className="aparte-scroll-rail__list",this.replaceChildren(i));let r=new Map;for(let l of Array.from(i.children)){let c=l.firstElementChild instanceof HTMLElement?l.firstElementChild.dataset.messageId:void 0;c&&r.set(c,l)}let a=new Set,o=0;for(let l of t){let c=l.getAttribute("message-id");a.add(c);let d=r.get(c);if(d)r.delete(c);else{d=document.createElement("li");let _=document.createElement("button");_.type="button",_.className="aparte-scroll-rail__tick",_.dataset.messageId=c,d.appendChild(_)}let u=d.firstElementChild,h=this._tickLabel(l);u.getAttribute("aria-label")!==h&&(u.setAttribute("aria-label",h),u.title=h),c===this._currentId?u.getAttribute("aria-current")!=="true"&&u.setAttribute("aria-current","true"):u.removeAttribute("aria-current");let f=i.children[o]??null;f!==d&&i.insertBefore(d,f),o++}for(let l of r.values())l.remove();this._currentId&&!a.has(this._currentId)&&(this._currentId=null),ac(this._observedBubbles,t)||this._observe(t),this._layout()}_observe(t){if(this._unobserve(),this._observedBubbles=t,typeof IntersectionObserver>"u")return;let e=this._scrollSurface();if(e){this._intersections=new IntersectionObserver(s=>{for(let i of s){let r=i.target.getAttribute("message-id");r&&this._visible.set(r,i.isIntersecting?i.intersectionRatio:0)}this._pickCurrent()},{root:e,rootMargin:"0px 0px -70% 0px",threshold:[0,.1,.25,.5,.75,1]}),this._onScreenObserver=new IntersectionObserver(s=>{for(let i of s){let r=i.target.getAttribute("message-id");r&&(i.isIntersecting?this._onScreen.add(r):this._onScreen.delete(r))}this._pickCurrent()},{root:e,threshold:[0]});for(let s of t)this._intersections.observe(s),this._onScreenObserver.observe(s);this._observedSurface=e,e.addEventListener("scroll",this._onRootScroll,{passive:!0})}}_unobserve(){this._intersections?.disconnect(),this._intersections=null,this._onScreenObserver?.disconnect(),this._onScreenObserver=null,this._observedSurface?.removeEventListener("scroll",this._onRootScroll),this._observedSurface=null,this._observedBubbles=[],this._visible.clear(),this._onScreen.clear()}_onRootScroll=()=>{this._pickQueued||(this._pickQueued=!0,requestAnimationFrame(()=>{this._pickQueued=!1,this._pickCurrent()}))};_atBottom(){let t=this._observedSurface;if(!t)return!1;let e=t.scrollHeight-t.clientHeight;return e>0&&e-t.scrollTop<=2}_pickCurrent(){if(this._held)return;let t=this._observedBubbles;if(t.length===0)return;let e=t[t.length-1].getAttribute("message-id");if(this._atBottom()||this._onScreen.has(e)){this._setCurrent(e);return}let s=null;for(let i of t){let r=i.getAttribute("message-id");(this._visible.get(r)??0)>0&&(s=r)}s!==null&&this._setCurrent(s)}_setCurrent(t){if(this._currentId!==t){this._currentId=t;for(let e of this.querySelectorAll(".aparte-scroll-rail__tick"))e.dataset.messageId===t?(e.setAttribute("aria-current","true"),this._reveal(e)):e.removeAttribute("aria-current")}}_reveal(t){let e=this.clientHeight;if(!e)return;let s=t.offsetTop,i=s+t.offsetHeight;s<this.scrollTop?this.scrollTop=s:i>this.scrollTop+e&&(this.scrollTop=i-e)}_write(t,e){this._written.get(t)!==e&&(this._written.set(t,e),e?this.style.setProperty(t,e):this.style.removeProperty(t))}_layout(){let t=this._host,e=this._viewport(),s=this._scrollSurface();if(t&&s&&this._write("--aparte-scroll-rail-bar",`${Math.max(0,s.offsetWidth-s.clientWidth)}px`),t&&e){let u=e.getBoundingClientRect(),h=t.getBoundingClientRect();u.height>0&&h.height>0&&(this._write("--aparte-scroll-rail-block-start",`${Math.max(0,Math.round(u.top-h.top))}px`),this._write("--aparte-scroll-rail-block-end",`${Math.max(0,Math.round(h.bottom-u.bottom))}px`))}let i=this._list()?.children.length??0,r=this.clientHeight;if(!i||!r){this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap","");return}let a=t??document.documentElement,o=getComputedStyle(a),l=parseFloat(o.getPropertyValue("--aparte-scroll-rail-hit-size"))||24,c=parseFloat(o.getPropertyValue("--aparte-scroll-rail-tick-thickness"))||2;if(i*l<=r){this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap","");return}let d=Math.max(sc,Math.floor(r/i));this._write("--aparte-scroll-rail-hit-size",`${d}px`),this._write("--aparte-scroll-rail-gap",`${Math.max(0,d-c)}px`)}_onClick=t=>{let e=t.target.closest(".aparte-scroll-rail__tick");if(!e||!this.contains(e))return;let s=e.dataset.messageId;s&&this.jumpTo(s)};_onKeydown=t=>{if(t.key!=="ArrowDown"&&t.key!=="ArrowUp"&&t.key!=="Home"&&t.key!=="End")return;let e=Array.from(this.querySelectorAll(".aparte-scroll-rail__tick")),s=e.indexOf(pt(this));if(s===-1)return;t.preventDefault();let i=t.key==="Home"?0:t.key==="End"?e.length-1:t.key==="ArrowDown"?Math.min(e.length-1,s+1):Math.max(0,s-1);e[i]?.focus()};jumpTo(t){if(!this.dispatchEvent(new CustomEvent("aparte-scroll-rail-jump",{detail:{messageId:t},bubbles:!0,composed:!0,cancelable:!0})))return;let s=this._bubbleOf(t);s&&(this._viewport()?.setAutoScroll?.(!1),this._scrollTo(s),this._setCurrent(t),this._hold(t))}_bubbleOf(t){return this._viewport()?.querySelector(`aparte-chat-bubble[message-id="${z(t)}"]`)??null}_scrollTo(t){let e=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches;t.scrollIntoView({block:"start",behavior:e?"auto":"smooth"})}_hold(t){this._release(),this._held=t,this._alignPasses=0,this._settleSurface=this._scrollSurface(),this._settleSurface?.addEventListener("scroll",this._onSurfaceScroll),this._bumpSettle()}_bumpSettle(){this._settleTimer!==null&&clearTimeout(this._settleTimer),this._settleTimer=setTimeout(()=>this._settle(),nc)}_settle(){let t=this._held,e=this._settleSurface,s=t?this._bubbleOf(t):null;if(t&&s&&e&&this._alignPasses<ic){let i=e.getBoundingClientRect().top+(parseFloat(getComputedStyle(e).scrollPaddingTop)||0),r=s.getBoundingClientRect().top-i;if(Math.abs(r)>rc){this._alignPasses++,this._scrollTo(s),this._bumpSettle();return}}this._release(),t&&this._setCurrent(t)}_release(){this._settleTimer!==null&&clearTimeout(this._settleTimer),this._settleTimer=null,this._settleSurface?.removeEventListener("scroll",this._onSurfaceScroll),this._settleSurface=null,this._held=null}};function ac(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}$(Xe);customElements.get("aparte-scroll-rail")||customElements.define("aparte-scroll-rail",Xe);var oc="(max-width: 48rem)",Je=class extends HTMLElement{static get observedAttributes(){return["collapsed","breakpoint"]}_media=null;_scrim=null;_opener=null;_lastCollapsed=null;_ready=!1;_closedByHost=!1;_hostIntentSeeded=!1;_auto=!1;_ownHidden=!1;_query="";_listWatch=null;get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",K(t))}get drawer(){return this.hasAttribute("data-drawer")}connectedCallback(){this.classList.contains("aparte-sidebar")||this.classList.add("aparte-sidebar"),this.getAttribute("role")||this.setAttribute("role","complementary"),this._relabel(),this._hostIntentSeeded||(this._closedByHost=this.collapsed,this._hostIntentSeeded=!0),this.addEventListener("input",this._onInput),typeof MutationObserver=="function"&&(this._listWatch=new MutationObserver(t=>{t.some(e=>e.target!==this)&&this._syncNoMatch()}),this._listWatch.observe(this,{subtree:!0,attributes:!0,attributeFilter:["data-no-match","loading"]})),document.addEventListener("keydown",this._onKeydown),document.addEventListener("click",this._onDocumentClick),window.addEventListener("aparte-config-change",this._onConfigChange),this._watchBreakpoint(),this._syncHidden(),this._lastCollapsed=this.collapsed,this.id||(this.id=`aparte-sidebar-${++lc}`),this._syncToggles(),this._ready=!0}_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t==="none"){this._applyDrawer(!1);return}if(typeof matchMedia!="function")return;let e=t?`(max-width: ${t})`:oc;this._media=matchMedia(e),this._media.addEventListener("change",this._onMediaChange),this._applyDrawer(this._media.matches)}disconnectedCallback(){this.removeEventListener("input",this._onInput),this._listWatch?.disconnect(),this._listWatch=null,document.removeEventListener("keydown",this._onKeydown),document.removeEventListener("click",this._onDocumentClick),window.removeEventListener("aparte-config-change",this._onConfigChange),this._media?.removeEventListener("change",this._onMediaChange),this._media=null,this._ready=!1}attributeChangedCallback(t){if(!this._ready)return;if(t==="breakpoint"){this._watchBreakpoint();return}if(t!=="collapsed")return;let e=this.collapsed;e!==this._lastCollapsed&&(this._lastCollapsed=e,!this._auto&&!this.drawer&&(this._closedByHost=e),this._syncScrim(),this._syncHidden(),this._syncToggles(),e&&this.drawer&&this._opener?.isConnected?(this._opener.focus(),this._opener=null):!e&&this.drawer&&this._focusFirst(),this.dispatchEvent(new CustomEvent("aparte-sidebar-toggle",{detail:{collapsed:e,drawer:this.drawer},bubbles:!0,composed:!0})))}open(t){t&&(this._opener=t),this.collapsed=!1}close(){this.collapsed=!0}toggle(t){this.collapsed?this.open(t):this.close()}_onMediaChange=t=>this._applyDrawer(t.matches);_applyDrawer(t){let e=this.drawer;this.toggleAttribute("data-drawer",t),this._auto=!0;try{t&&!e?this.collapsed=!0:!t&&e&&!this._closedByHost&&(this.collapsed=!1)}finally{this._auto=!1}this._syncScrim(),this._syncHidden(),this._syncToggles()}_syncToggles(){let t="[data-aparte-sidebar-toggle]",e=yt(this),s=e===document?Array.from(document.querySelectorAll(t)):[...e.querySelectorAll(t),...document.querySelectorAll(t)];for(let i of s)this._drives(i)&&(i.setAttribute("aria-expanded",String(!this.collapsed)),i.setAttribute("aria-controls",this.id))}_drives(t){let e=t.getAttribute("data-aparte-sidebar-toggle");return e?e===this.id:dc(t)===this}_syncHidden(){this.collapsed?(this.toggleAttribute("inert",!0),this.setAttribute("aria-hidden","true"),this._ownHidden=!0):this._ownHidden&&(this.removeAttribute("inert"),this.removeAttribute("aria-hidden"),this._ownHidden=!1)}_focusFirst(){ea(this)[0]?.focus()}_syncScrim(){let t=this.drawer&&!this.collapsed;t&&!this._scrim?(this._scrim=document.createElement("div"),this._scrim.className="aparte-sidebar__scrim",this._scrim.setAttribute("aria-hidden","true"),this._scrim.addEventListener("click",()=>this.close()),this.appendChild(this._scrim)):!t&&this._scrim&&(this._scrim.remove(),this._scrim=null)}_onKeydown=t=>{if(!(!this.drawer||this.collapsed)){if(t.key==="Escape"){t.preventDefault(),this.close();return}if(t.key==="Tab"){let e=ea(this);if(e.length===0)return;let s=e[0],i=e[e.length-1],r=pt(this);this.contains(r)?t.shiftKey&&r===s?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),s.focus()):(t.preventDefault(),s.focus())}}};_onDocumentClick=t=>{let e=ht(t)?.closest?.("[data-aparte-sidebar-toggle]");e&&this._drives(e)&&this.toggle(e)};_onInput=t=>{let e=t.target;e?.matches?.("[data-aparte-sidebar-search]")&&this.filter(e.value)};filter(t){this._query=t;let e=0,s=!1;for(let i of this._lists())typeof i.filter=="function"?e+=i.filter(t):(e+=fn(i,Ke(t)),s=!0);return s&&typeof customElements<"u"&&customElements.whenDefined("aparte-conversation-list").then(()=>{if(this._query===t)for(let i of this._lists())i.filter?.(t);this._syncNoMatch()}),this._syncNoMatch(),e}_lists(){return Array.from(this.querySelectorAll("aparte-conversation-list"))}_syncNoMatch(){let t=Ke(this._query),e=t!==""&&this._lists().every(s=>typeof s.filter=="function"?s.hasAttribute("data-no-match"):!s.hasAttribute("loading")&&fn(s,t)===0);this.toggleAttribute("data-no-match",e)}_onConfigChange=()=>this._relabel();_relabel(){if(this.hasAttribute("aria-label")&&this.dataset.ownLabel!=="locale")return;let t=k(this).getLocale();this.setAttribute("aria-label",t.sidebarLabel??"Conversations"),this.dataset.ownLabel="locale"}},lc=0,cc=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function ea(n){return Array.from(n.querySelectorAll(cc)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}function dc(n){return n.closest("aparte-sidebar")??yt(n).querySelector("aparte-sidebar")??document.querySelector("aparte-sidebar")}$(Je);customElements.get("aparte-sidebar")||customElements.define("aparte-sidebar",Je);function sa(n,t,e){return Number.isFinite(n)?n<t?t:n>e?e:n:t}function uc(n){let t=Number.isFinite(n.startPercent)?n.startPercent:0;if(!Number.isFinite(n.containerPx)||n.containerPx<=0)return sa(t,0,100);let i=((!n.vertical&&n.rtl)!==(n.primaryEnd===!0)?-1:1)*n.deltaPx*100/n.containerPx;return sa(t+i,0,100)}function na(n,t,e,s,i=!1){if(n==="Home")return-100;if(n==="End")return 100;let r=(t?10:1)*(i?-1:1);return s?n==="ArrowUp"?-r:n==="ArrowDown"?r:null:n==="ArrowLeft"?e?r:-r:n==="ArrowRight"?e?-r:r:null}var hc="(max-width: 48rem)",Xt=38,pc=300;function Jt(n,t){let e=Number.parseFloat(n??"");return Number.isFinite(e)?e<0?0:e>100?100:e:t}var Ze=class n extends HTMLElement{static get observedAttributes(){return["position","orientation","primary","collapsed","breakpoint","pane","disabled","label","single"]}_handle=null;_scrim=null;_media=null;_observer=null;_measureRafId=null;_observedPx=0;static _paneIdSeq=0;_position=Xt;_initialPosition=Xt;_initialCaptured=!1;_preCollapsePosition=null;_lastPosition=null;_lastCollapsed=null;_lastPane=null;_source="api";_ready=!1;_dragging=!1;_captured=!1;_moved=!1;_pointerId=null;_dragStartPercent=Xt;_dragOriginPx=0;_dragContainerPx=0;_keying=!1;get position(){return this._position}set position(t){let e=Jt(String(t),this._position);this.isConnected&&e===this._lastPosition||(this._position=e,this._setLive(e),this.isConnected&&this._commit("api"))}get orientation(){return this.getAttribute("orientation")==="vertical"?"vertical":"horizontal"}set orientation(t){this.setAttribute("orientation",t)}get primary(){return this.getAttribute("primary")==="end"?"end":"start"}set primary(t){this.setAttribute("primary",t)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",K(t))}get pane(){return this.getAttribute("pane")==="end"?"end":"start"}set pane(t){this.setAttribute("pane",t)}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",K(t))}get stacked(){return this.hasAttribute("data-stacked")||this.hasAttribute("single")||this.classList.contains("aparte-split--only-start")||this.classList.contains("aparte-split--only-end")}get single(){return this.hasAttribute("single")}set single(t){this.toggleAttribute("single",K(t))}collapse(){this.collapsed=!0}expand(){this.collapsed=!1}toggleCollapse(){this.collapsed=!this.collapsed}showPane(t){this.pane=t}reset(){this._position=this._initialPosition,this._setLive(this._position),this.isConnected&&this._commit("api")}connectedCallback(){this.classList.contains("aparte-split")||this.classList.add("aparte-split"),this._handle=this._ensureHandle();let t=this.getAttribute("position");t!==null?(this._position=Jt(t,Xt),this._setLive(this._position)):this._position=Jt(getComputedStyle(this).getPropertyValue("--aparte-split-position"),Xt),this._initialCaptured||(this._initialPosition=this._position,this._initialCaptured=!0),this.collapsed&&(this._lastCollapsed!==!0&&(this._preCollapsePosition=this._position),this._position=0,this._setLive(0)),this._lastPosition=this._position,this._lastCollapsed=this.collapsed,this._lastPane=this.pane,this._stampHandle(),this._relabel(),this._measureBounds(),this._handle.addEventListener("pointerdown",this._onPointerDown),this._handle.addEventListener("dblclick",this._onDoubleClick),this._handle.addEventListener("focusout",this._onFocusOut),this.addEventListener("keydown",this._onKeydown),this.addEventListener("keyup",this._onKeyup),document.addEventListener("click",this._onDocumentClick),window.addEventListener("aparte-config-change",this._onConfigChange),this._watchBreakpoint(),this._watchSize(),this._ready=!0,this._syncPaneControls()}disconnectedCallback(){this._handle?.removeEventListener("pointerdown",this._onPointerDown),this._handle?.removeEventListener("dblclick",this._onDoubleClick),this._handle?.removeEventListener("focusout",this._onFocusOut),this.removeEventListener("keydown",this._onKeydown),this.removeEventListener("keyup",this._onKeyup),document.removeEventListener("click",this._onDocumentClick),window.removeEventListener("aparte-config-change",this._onConfigChange),this._releasePointer(),this._media?.removeEventListener("change",this._onMediaChange),this._media=null,this._observer?.disconnect(),this._observer=null,this._measureRafId!==null&&(cancelAnimationFrame(this._measureRafId),this._measureRafId=null),this._removeScrim(),this._handle?.removeAttribute("data-dragging"),this._dragging=!1,this._keying=!1,this._ready=!1}attributeChangedCallback(t){if(this._ready)switch(t){case"position":{let e=Jt(this.getAttribute("position"),this._position);if(e===this._lastPosition)return;this._position=e,this._setLive(e),this._commit();return}case"collapsed":{let e=this.collapsed;if(e===this._lastCollapsed)return;this._lastCollapsed=e,e?(this._preCollapsePosition=this._position,this._position=0):this._position=this._preCollapsePosition??this._initialPosition,this._setLive(this._position),this._commit();return}case"pane":{let e=this.pane;if(this._syncPaneControls(),e===this._lastPane)return;this._lastPane=e,this._commit();return}case"orientation":case"primary":this._stampHandle(),this._measureBounds();return;case"disabled":this.disabled&&this._dragging&&this._endDrag("pointer",this._dragStartPercent),this._stampHandle();return;case"single":this.single&&this._dragging&&this._endDrag("pointer",this._dragStartPercent),this._stampHandle(),this._syncPaneControls();return;case"breakpoint":this._watchBreakpoint();return;case"label":this._relabel()}}_ensureHandle(){let t=Array.from(this.children).find(i=>i instanceof HTMLElement&&i.classList.contains("aparte-split__handle"));if(t){if(this.children[1]!==t){let i=Array.from(this.children).filter(r=>r!==t)[1]??null;this.insertBefore(t,i)}return t}let e=document.createElement("div");e.className="aparte-split__handle";let s=this.children[1]??null;return s?this.insertBefore(e,s):this.appendChild(e),e}_panes(){return Array.from(this.children).filter(t=>t instanceof HTMLElement&&!t.classList.contains("aparte-split__handle"))}_primaryPane(){let t=this._panes();return(this.primary==="end"?t[t.length-1]:t[0])??null}_stampHandle(){let t=this._handle;if(!t)return;t.setAttribute("role","separator"),t.setAttribute("aria-orientation",this.orientation==="vertical"?"horizontal":"vertical"),this.disabled||this.stacked?t.removeAttribute("tabindex"):t.setAttribute("tabindex","0"),t.setAttribute("aria-valuenow",String(Math.round(this._achievedPercent())));let e=this._primaryPane();e&&(e.id||(e.id=`aparte-split-pane-${++n._paneIdSeq}`),t.setAttribute("aria-controls",e.id))}_measure(t){let e=t.getBoundingClientRect();return this.orientation==="vertical"?e.height:e.width}_achievedPercent(){if(this.stacked)return this._position;let t=this._measure(this),e=this._primaryPane();return!e||!(t>0)?this._position:Math.max(0,Math.min(100,this._measure(e)/t*100))}_measureBounds(){let t=this._handle;if(!t||this._dragging||this.stacked)return;let e=this._primaryPane(),s=this._measure(this);if(!e||!(s>0)){t.setAttribute("aria-valuemin","0"),t.setAttribute("aria-valuemax","100");return}let i=this.style.getPropertyValue("--aparte-split-position");this.style.setProperty("--aparte-split-position","0%");let r=this._measure(e)/s*100;this.style.setProperty("--aparte-split-position","100%");let a=this._measure(e)/s*100;i?this.style.setProperty("--aparte-split-position",i):this.style.removeProperty("--aparte-split-position"),t.setAttribute("aria-valuemin",String(Math.round(r))),t.setAttribute("aria-valuemax",String(Math.round(a))),t.setAttribute("aria-valuenow",String(Math.round(this._achievedPercent())))}_watchSize(){typeof ResizeObserver=="function"&&(this._observer=new ResizeObserver(()=>{let t=this._measure(this);Math.abs(t-this._observedPx)<=1||(this._observedPx=t,this._measureRafId===null&&(this._measureRafId=requestAnimationFrame(()=>{this._measureRafId=null,this._measureBounds()})))}),this._observer.observe(this))}_setLive(t){this.style.setProperty("--aparte-split-position",`${Math.round(t*1e3)/1e3}%`)}_commit(t=this._source){let e=Math.round(this._achievedPercent());this._position=e,this._setLive(e),this._lastPosition=e,this.getAttribute("position")!==String(e)&&this.setAttribute("position",String(e)),this._handle?.setAttribute("aria-valuenow",String(e)),this.dispatchEvent(new CustomEvent("aparte-split-resize",{detail:{position:e,collapsed:this.collapsed,stacked:this.stacked,pane:this.pane,orientation:this.orientation,source:t},bubbles:!0,composed:!0}))}_rtl(){return getComputedStyle(this).direction==="rtl"}_onPointerDown=t=>{this.disabled||this.stacked||this._dragging||t.button>0||(t.preventDefault(),this._handle?.focus(),this._dragging=!0,this._captured=!1,this._moved=!1,this._pointerId=t.pointerId,this._dragStartPercent=this._position,this._dragOriginPx=this.orientation==="vertical"?t.clientY:t.clientX,this._dragContainerPx=this._measure(this),this._handle?.setAttribute("data-dragging",""),this._addScrim(),window.addEventListener("pointermove",this._onPointerMove),window.addEventListener("pointerup",this._onPointerUp),window.addEventListener("pointercancel",this._onPointerCancel))};_isOurPointer(t){return this._pointerId===null||t.pointerId===this._pointerId}_onPointerMove=t=>{if(!this._dragging||!this._isOurPointer(t))return;if(t.buttons===0){this._endDrag("pointer");return}if(!this._captured&&this._pointerId!==null){this._captured=!0;try{this._handle?.setPointerCapture(this._pointerId)}catch{}}let e=this.orientation==="vertical"?t.clientY:t.clientX;this._position=uc({startPercent:this._dragStartPercent,deltaPx:e-this._dragOriginPx,containerPx:this._dragContainerPx,rtl:this._rtl(),vertical:this.orientation==="vertical",primaryEnd:this.primary==="end"}),this._moved=!0,this._setLive(this._position)};_onPointerUp=t=>{this._isOurPointer(t)&&this._endDrag("pointer")};_onPointerCancel=t=>{this._isOurPointer(t)&&this._endDrag("pointer")};_endDrag(t,e){if(!this._dragging)return;let s=this._moved;this._dragging=!1,this._moved=!1,this._releasePointer(),this._handle?.removeAttribute("data-dragging"),this._removeScrim(!s),e!==void 0&&(this._position=e,this._setLive(e)),!(!s&&e===void 0)&&(this._measureBounds(),this._commit(t))}_releasePointer(){if(window.removeEventListener("pointermove",this._onPointerMove),window.removeEventListener("pointerup",this._onPointerUp),window.removeEventListener("pointercancel",this._onPointerCancel),this._captured&&this._pointerId!==null)try{this._handle?.releasePointerCapture(this._pointerId)}catch{}this._captured=!1,this._pointerId=null}_addScrim(){if(this._scrim||!this._handle)return;let t=document.createElement("div");t.className="aparte-split__scrim",t.setAttribute("aria-hidden","true"),this._handle.appendChild(t),this._scrim=t}_removeScrim(t=!1){let e=this._scrim;if(this._scrim=null,!!e){if(!t){e.remove();return}e.style.pointerEvents="none",setTimeout(()=>e.remove(),pc)}}_onDoubleClick=()=>{this.disabled||this.stacked||this.reset()};_onKeydown=t=>{if(this._dragging&&t.key==="Escape"){t.preventDefault(),this._endDrag("pointer",this._dragStartPercent);return}if(this.disabled||this.stacked||t.target!==this._handle)return;if(t.key==="Enter"){t.preventDefault(),this._source="keyboard";try{this.toggleCollapse()}finally{this._source="api"}return}let e=na(t.key,t.shiftKey,this._rtl(),this.orientation==="vertical",this.primary==="end");e!==null&&(t.preventDefault(),this._keying=!0,this._position=Jt(String(this._position+e),this._position),this._setLive(this._position))};_onKeyup=t=>{!this._keying||t.target!==this._handle||na(t.key,t.shiftKey,this._rtl(),this.orientation==="vertical")!==null&&(this._keying=!1,this._commit("keyboard"))};_onFocusOut=()=>{this._keying&&(this._keying=!1,this._commit("keyboard"))};_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t==="none"){this._applyStacked(!1);return}if(typeof matchMedia!="function")return;let e=t?`(max-width: ${t})`:hc;this._media=matchMedia(e),this._media.addEventListener("change",this._onMediaChange),this._applyStacked(this._media.matches)}_onMediaChange=t=>this._applyStacked(t.matches);_applyStacked(t){let e=this.hasAttribute("data-stacked");t&&!e&&this._dragging&&this._endDrag("pointer",this._dragStartPercent),this.toggleAttribute("data-stacked",t),t!==e&&this._syncPaneControls(),t&&!e?this.hasAttribute("pane")||this.showPane("start"):!t&&e&&this.removeAttribute("pane"),this._lastPane=this.pane,this._stampHandle(),t!==e&&this._measureBounds()}_onDocumentClick=t=>{let e=ht(t)?.closest?.("[data-aparte-split-pane]");if(!e)return;let s=(e.getAttribute("data-aparte-split-pane")??"").trim(),i=s==="start"||s==="end"?s:null,r=i?"":s;if(r){if(r!==this.id)return}else if((e.closest("aparte-split")??yt(e).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this)return;this.showPane(i??(this.pane==="start"?"end":"start"))};_syncPaneControls(){let t=new Set([yt(this),document]);for(let e of t)for(let s of e.querySelectorAll("[data-aparte-split-pane]")){let i=(s.getAttribute("data-aparte-split-pane")??"").trim();i!=="start"&&i!=="end"||s.localName!=="button"&&s.getAttribute("role")!=="button"||(s.closest("aparte-split")??yt(s).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this||(this.stacked?s.setAttribute("aria-pressed",String(i===this.pane)):s.removeAttribute("aria-pressed"))}}_onConfigChange=()=>this._relabel();_relabel(){let t=this._handle;if(!t||t.hasAttribute("aria-labelledby")||t.hasAttribute("aria-label")&&t.dataset.ownLabel!=="locale")return;let e=k(this).getLocale();t.setAttribute("aria-label",this.getAttribute("label")??e.splitHandleLabel??"Resize the panes"),t.dataset.ownLabel="locale"}};$(Ze);customElements.get("aparte-split")||customElements.define("aparte-split",Ze);var fc="(max-width: 30rem), (max-height: 30rem)",_c=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),ts=class extends HTMLElement{static get observedAttributes(){return["open","label","breakpoint"]}_button=null;_childWatch=null;_hostWatch=null;_media=null;_lastOpen=null;_ready=!1;get open(){return this.hasAttribute("open")}set open(t){this.toggleAttribute("open",K(t))}get sheet(){return this.hasAttribute("data-sheet")}connectedCallback(){this.classList.contains("aparte-launcher")||this.classList.add("aparte-launcher"),this._button||(this._button=document.createElement("button"),this._button.type="button",this._button.addEventListener("click",this._onButtonClick)),this.appendChild(this._button),typeof MutationObserver=="function"&&(this._childWatch??=new MutationObserver(()=>this._keepButton()),this._childWatch.observe(this,{childList:!0}),this._hostWatch??=new MutationObserver(()=>this._renderButton()),this._hostWatch.observe(this,{attributes:!0,attributeFilter:[Kt],subtree:!0})),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),window.addEventListener("aparte-config-change",this._onConfigChange),this._watchBreakpoint(),this._lastOpen=this.open,this._renderButton(),this._ready=!0}disconnectedCallback(){this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),window.removeEventListener("aparte-config-change",this._onConfigChange),this._childWatch?.disconnect(),this._hostWatch?.disconnect(),this._media?.removeEventListener("change",this._onMediaChange),this._media=null,this._ready=!1}attributeChangedCallback(t){if(!this._ready)return;if(t==="breakpoint"){this._watchBreakpoint();return}if(this._renderButton(),t!=="open")return;let e=this.open;e!==this._lastOpen&&(this._lastOpen=e,!e&&this._button&&this.contains(pt(this))&&this._button.focus(),this._announce())}_announce(){this.dispatchEvent(new CustomEvent("aparte-launcher-toggle",{detail:{open:this.open,sheet:this.sheet},bubbles:!0,composed:!0}))}show(){this.open=!0}close(){this.open=!1}toggle(){this.open=!this.open}_onButtonClick=()=>{let t=!this.open;this.toggle(),t&&this._focusChat()};_onConfigChange=()=>this._renderButton();_config(){return k(this.querySelector(`[${Kt}]`)??this)}_keepButton(){this._button&&this._button.parentNode!==this&&this.appendChild(this._button)}_renderButton(){let t=this._button;if(!t)return;this._keepButton();let e=this._config(),s=e.getLocale(),i=this.open,r=i?"":(this.getAttribute("label")??"").trim(),a=r?"aparte-btn--pill":"aparte-btn--circle";t.className=["aparte-btn","aparte-btn--primary","aparte-btn--solid","aparte-btn--lg",a,"aparte-launcher__button"].join(" "),t.setAttribute("aria-expanded",String(i)),r?t.removeAttribute("aria-label"):t.setAttribute("aria-label",i?s.launcherClose??"Close the chat":s.launcherOpen??"Open the chat");let o=document.createElement("span");o.className="aparte-launcher__icon",o.setAttribute("aria-hidden","true"),o.innerHTML=i?e.getIcon("launcherClose")??e.getIcon("close"):e.getIcon("launcherOpen")??e.getIcon("messageSquare");let l=[o];if(r){let c=document.createElement("span");c.className="aparte-launcher__label",c.textContent=r,l.push(c)}t.replaceChildren(...l)}_onMediaChange=t=>this._applySheet(t.matches);_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t==="none"||typeof matchMedia!="function"){this._applySheet(!1);return}this._media=matchMedia(t?`(max-width: ${t})`:fc),this._media.addEventListener("change",this._onMediaChange),this._applySheet(this._media.matches)}_applySheet(t){t!==this.sheet&&(this.toggleAttribute("data-sheet",t),this._ready&&this.open&&this._announce())}_focusables(){return Array.from(this.querySelectorAll(_c)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}_focusChat(){(Array.from(this.querySelectorAll('[role="textbox"]:not([aria-disabled="true"])')).find(s=>!s.closest("[hidden]")&&s.checkVisibility?.()!==!1)??this._focusables().find(s=>s!==this._button))?.focus()}_onClick=t=>{let e=ht(t)?.closest?.("[data-aparte-launcher-close]");e&&this.contains(e)&&this.close()};_inModalDialog(t){let e=ht(t)?.closest?.("dialog[open]");if(!e||!this.contains(e))return!1;try{return e.matches(":modal")}catch{return!0}}_onKeydown=t=>{if(!this.open)return;if(t.key==="Escape"){if(t.defaultPrevented||t.isComposing||t.keyCode===229||this._inModalDialog(t))return;t.preventDefault(),this.close();return}if(t.key!=="Tab"||!this.sheet)return;let e=this._focusables();if(e.length===0)return;let s=e[0],i=e[e.length-1],r=pt(this);t.shiftKey&&r===s?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),s.focus())}};$(ts);customElements.get("aparte-launcher")||customElements.define("aparte-launcher",ts);typeof document<"u"&&$r();export{H as a,Y as b,G as c,to as d,k as e,M as f,qt as g,Q as h,Ht as i,yl as j,z as k,Br as l,Ns as m};
206
- //# sourceMappingURL=chunk-VTTH7HGO.js.map
206
+ //# sourceMappingURL=chunk-F2QIT4NR.js.map