@aparte/core 0.32.0 → 1.0.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 (71) hide show
  1. package/README.md +30 -19
  2. package/dist/client/agent-runner.d.ts.map +1 -1
  3. package/dist/components/bubble/aparte-chat-bubble.d.ts +12 -0
  4. package/dist/components/bubble/aparte-chat-bubble.d.ts.map +1 -1
  5. package/dist/components/composer/aparte-composer-send.d.ts.map +1 -1
  6. package/dist/components/context/aparte-context.d.ts +4 -11
  7. package/dist/components/context/aparte-context.d.ts.map +1 -1
  8. package/dist/components/launcher/aparte-launcher.d.ts.map +1 -1
  9. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts +77 -5
  10. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts.map +1 -1
  11. package/dist/components/sidebar/aparte-sidebar.d.ts.map +1 -1
  12. package/dist/components/split/aparte-split.d.ts.map +1 -1
  13. package/dist/components/suggestions/aparte-suggestions.d.ts +15 -1
  14. package/dist/components/suggestions/aparte-suggestions.d.ts.map +1 -1
  15. package/dist/components/suggestions/suggestion-blocks.d.ts +21 -1
  16. package/dist/components/suggestions/suggestion-blocks.d.ts.map +1 -1
  17. package/dist/components/viewport/aparte-chat-viewport.d.ts +7 -6
  18. package/dist/components/viewport/aparte-chat-viewport.d.ts.map +1 -1
  19. package/dist/config/aparte-config.d.ts +56 -4
  20. package/dist/config/aparte-config.d.ts.map +1 -1
  21. package/dist/config/config-context.d.ts.map +1 -1
  22. package/dist/config/image-policy.d.ts +104 -0
  23. package/dist/config/image-policy.d.ts.map +1 -0
  24. package/dist/config/index.d.ts +1 -0
  25. package/dist/config/index.d.ts.map +1 -1
  26. package/dist/config/locale.d.ts +8 -10
  27. package/dist/config/locale.d.ts.map +1 -1
  28. package/dist/config/sanitize.d.ts +36 -0
  29. package/dist/config/sanitize.d.ts.map +1 -1
  30. package/dist/custom-elements.json +1236 -122
  31. package/dist/{defer-hydration-ggxlbvL9.js → defer-hydration-Dw5D80FC.js} +831 -68
  32. package/dist/defer-hydration-Dw5D80FC.js.map +1 -0
  33. package/dist/elicitation/panel.d.ts.map +1 -1
  34. package/dist/generated/element-attributes.d.ts +1 -3
  35. package/dist/generated/element-attributes.d.ts.map +1 -1
  36. package/dist/index.css +1 -1
  37. package/dist/index.d.ts +2 -2
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +473 -122
  40. package/dist/index.js.map +1 -1
  41. package/dist/index.node.d.ts +2 -2
  42. package/dist/index.node.d.ts.map +1 -1
  43. package/dist/index.node.js +1 -1
  44. package/dist/index.node.js.map +1 -1
  45. package/dist/interop/dialog-triggers.d.ts.map +1 -1
  46. package/dist/interop/image-holds.d.ts +20 -0
  47. package/dist/interop/image-holds.d.ts.map +1 -0
  48. package/dist/renderers/citations.d.ts.map +1 -1
  49. package/dist/transport/agent-handler.d.ts +10 -0
  50. package/dist/transport/agent-handler.d.ts.map +1 -1
  51. package/dist/transport/agent-ticket.d.ts.map +1 -1
  52. package/dist/transport/backend-handler.d.ts +8 -0
  53. package/dist/transport/backend-handler.d.ts.map +1 -1
  54. package/dist/transport/backend-transport.d.ts.map +1 -1
  55. package/dist/transport/json-headers.d.ts +10 -0
  56. package/dist/transport/json-headers.d.ts.map +1 -0
  57. package/dist/transport/request-guard.d.ts +14 -0
  58. package/dist/transport/request-guard.d.ts.map +1 -0
  59. package/dist/types/events.d.ts +6 -13
  60. package/dist/types/events.d.ts.map +1 -1
  61. package/dist/types/index.d.ts +1 -1
  62. package/dist/types/index.d.ts.map +1 -1
  63. package/dist/types/models.d.ts +0 -34
  64. package/dist/types/models.d.ts.map +1 -1
  65. package/dist/types/segments.d.ts +0 -11
  66. package/dist/types/segments.d.ts.map +1 -1
  67. package/dist/utils/rendered-content.d.ts +3 -0
  68. package/dist/utils/rendered-content.d.ts.map +1 -0
  69. package/llms.txt +13 -0
  70. package/package.json +11 -4
  71. package/dist/defer-hydration-ggxlbvL9.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { K as deferHydrationOf, ad as resolveConfig, ao as eventOrigin, ap as activeElementIn, aj as subscribeConfigChange, af as runWithConfig, o as AparteElicitationAbortError, w as buildApprovalPanel, x as buildElicitationPanel, aq as gateGlide, O as escapeAttr, ar as chatBoundaryOf, as as relabelCodeLanguages, at as relabelCitations, au as toolCallRenderer, av as toolRendererThatDrew, t as aparteGlobalConfig, aw as isMountedRenderer, ax as renderingVersionOf, H as cssEscape, ay as onRenderersChange, az as renderSourceList, aA as mergeSegmentUpdate, P as escapeHtml, a0 as isSegmentSettled, aB as writeStreamedMarkdown, aC as replaceHighlighted, $ as isSafeUrl, C as copyText, V as getSegmentRenderer, X as installDefaultRenderersOnce, r as AparteMessageRepository, aD as CheckpointStateWatcher, aE as chatIdOf, aF as stampSegmentActivity, aG as stampSegmentOnInsert, aH as stampSegmentOnUpdate, aI as renumberSegments, aJ as openSegmentIds, aK as isTerminalStatus, aL as adoptMessageSegments, Z as isAwaitingReply, a5 as populateBubbleFromMessage, an as uuid, ae as revokeAttachmentUrls, a4 as parseMarkdownToSegments, aM as APARTE_DERIVED_SEGMENTS, aN as rememberConversationStatus, aO as tellConversationStatus, aP as conversationStatusOf, e as APARTE_DEFAULT_LOCALE, aQ as usageTokens, q as AparteErrorCode, a1 as measureContext, aR as rootOf, g as APARTE_HOST_ATTR, Y as installDialogTriggersOnce } from "./defer-hydration-ggxlbvL9.js";
2
- import { A, a, b, c, d, f, h, i, j, k, l, m, n, p, s, S, u, v, y, z, B, D, E, F, G, I, J, L, M, N, Q, R, T, U, W, _, a2, a3, a6, a7, a8, a9, aa, ab, ac, ag, ah, ai, ak, al, am } from "./defer-hydration-ggxlbvL9.js";
1
+ import { K as deferHydrationOf, ad as resolveConfig, ao as eventOrigin, ap as activeElementIn, aj as subscribeConfigChange, af as runWithConfig, o as AparteElicitationAbortError, w as buildApprovalPanel, x as buildElicitationPanel, aq as gateGlide, O as escapeAttr, ar as chatBoundaryOf, as as relabelCodeLanguages, at as relabelCitations, au as toolCallRenderer, av as toolRendererThatDrew, t as aparteGlobalConfig, aw as isMountedRenderer, ax as renderingVersionOf, H as cssEscape, ay as onRenderersChange, az as renderSourceList, aA as mergeSegmentUpdate, P as escapeHtml, a0 as isSegmentSettled, aB as writeStreamedMarkdown, aC as replaceHighlighted, $ as isSafeUrl, C as copyText, V as getSegmentRenderer, X as installDefaultRenderersOnce, r as AparteMessageRepository, aD as CheckpointStateWatcher, aE as chatIdOf, aF as stampSegmentActivity, aG as stampSegmentOnInsert, aH as stampSegmentOnUpdate, aI as renumberSegments, aJ as openSegmentIds, aK as isTerminalStatus, aL as adoptMessageSegments, Z as isAwaitingReply, a5 as populateBubbleFromMessage, an as uuid, ae as revokeAttachmentUrls, a4 as parseMarkdownToSegments, aM as APARTE_DERIVED_SEGMENTS, aN as rememberConversationStatus, aO as tellConversationStatus, aP as conversationStatusOf, e as APARTE_DEFAULT_LOCALE, aQ as visibleReply, aR as usageTokens, q as AparteErrorCode, a1 as measureContext, aS as rootOf, aT as inRenderedContent, g as APARTE_HOST_ATTR, Y as installDialogTriggersOnce } from "./defer-hydration-Dw5D80FC.js";
2
+ import { A, a, b, c, d, f, h, i, j, k, l, m, n, p, s, S, u, v, y, z, B, D, E, F, G, I, J, L, M, N, Q, R, T, U, W, _, a2, a3, a6, a7, a8, a9, aa, ab, ac, ag, ah, ai, ak, al, am } from "./defer-hydration-Dw5D80FC.js";
3
3
  function presenceOn(value) {
4
4
  return value === "" ? true : Boolean(value);
5
5
  }
@@ -1538,6 +1538,8 @@ class AparteChatBubble extends HTMLElement {
1538
1538
  _drawnWithVersion = 0;
1539
1539
  /** Every segment on screen, by id: see {@link DrawnSegment}. */
1540
1540
  _drawn = /* @__PURE__ */ new Map();
1541
+ /** Segments written to with no `isStreaming: false` yet: settled when the message stops streaming. */
1542
+ _written = /* @__PURE__ */ new Set();
1541
1543
  /** The segments were released because the bubble was still out of the page at the next microtask. */
1542
1544
  _releasedWhileDetached = false;
1543
1545
  /** A {@link _scheduleReleaseCheck} is queued. */
@@ -1928,6 +1930,8 @@ class AparteChatBubble extends HTMLElement {
1928
1930
  if (index !== -1) {
1929
1931
  const updated = mergeSegmentUpdate(this._segments[index], updates);
1930
1932
  this._segments[index] = updated;
1933
+ if (updated.isStreaming === false) this._written.delete(segmentId);
1934
+ else if ("content" in updates) this._written.add(segmentId);
1931
1935
  this._applySegmentUpdate(segmentId, updated, updates);
1932
1936
  if ("sources" in updates) this._syncSources();
1933
1937
  this._syncCopyAction();
@@ -1939,10 +1943,31 @@ class AparteChatBubble extends HTMLElement {
1939
1943
  const segment = this._segments.find((s2) => s2.id === segmentId);
1940
1944
  if (segment && "content" in segment) {
1941
1945
  segment.content += content;
1946
+ if (segment.isStreaming !== false) this._written.add(segmentId);
1942
1947
  this._applySegmentUpdate(segmentId, segment, { content: segment.content });
1943
1948
  this._syncCopyAction();
1944
1949
  }
1945
1950
  }
1951
+ /**
1952
+ * The message stopped streaming, so a segment it was still writing is finished too.
1953
+ *
1954
+ * A segment written to with no `isStreaming` flag — `appendToSegment` from a stream driven
1955
+ * by hand, as the docs' own streaming demo does — goes through the incremental Markdown
1956
+ * parser, which holds back what may still open a token (the full stop after `**bold**`)
1957
+ * until it is told the text is complete. Nothing told it: the message ended with its tail
1958
+ * missing. Marked finished here, it is flushed and settled like any finished segment.
1959
+ */
1960
+ _settleWrittenSegments() {
1961
+ for (const id of this._written) {
1962
+ const index = this._segments.findIndex((s2) => s2.id === id);
1963
+ const segment = this._segments[index];
1964
+ if (!segment || segment.isStreaming === false) continue;
1965
+ const settled = { ...segment, isStreaming: false };
1966
+ this._segments[index] = settled;
1967
+ this._applySegmentUpdate(id, settled, { isStreaming: false });
1968
+ }
1969
+ this._written.clear();
1970
+ }
1946
1971
  /** Get all segments */
1947
1972
  getSegments() {
1948
1973
  return [...this._segments];
@@ -2186,6 +2211,7 @@ class AparteChatBubble extends HTMLElement {
2186
2211
  const button = event.target?.closest?.("[data-checkpoint-action]");
2187
2212
  const separator = button?.closest(".aparte-checkpoint");
2188
2213
  if (!button || !separator || separator.parentElement !== this) return;
2214
+ if (button.closest(".aparte-checkpoint__summary")) return;
2189
2215
  switch (button.getAttribute("data-checkpoint-action")) {
2190
2216
  case "toggle":
2191
2217
  this._checkpointOpen = !this._checkpointOpen;
@@ -3207,6 +3233,7 @@ class AparteChatBubble extends HTMLElement {
3207
3233
  this._updateWaiting();
3208
3234
  this._updateFinishNote();
3209
3235
  if (wasStreaming && !streaming) this._updateContent();
3236
+ if (wasStreaming && !streaming) this._settleWrittenSegments();
3210
3237
  if (wasStreaming && !streaming && this._segments.length > 0) this._redrawIfStale();
3211
3238
  }
3212
3239
  }
@@ -3515,6 +3542,8 @@ class AparteChatViewport extends HTMLElement {
3515
3542
  * (e.g. Angular) owns the bubble elements.
3516
3543
  */
3517
3544
  _frameworkManagedDOM = false;
3545
+ /** Inside `setMessages`: each append leaves the layout work to the end of the loop. */
3546
+ _bulkAppend = false;
3518
3547
  static get observedAttributes() {
3519
3548
  return ["scroll-threshold", "max-rendered-bubbles", "loading"];
3520
3549
  }
@@ -3630,9 +3659,13 @@ class AparteChatViewport extends HTMLElement {
3630
3659
  if (!el2.hasAttribute("role")) el2.setAttribute("role", "log");
3631
3660
  el2.setAttribute("aria-label", resolveConfig(this).t("transcript"));
3632
3661
  }
3633
- /** Mirror `locale.direction` onto the scroll container. */
3662
+ /**
3663
+ * Mirror `locale.direction` onto the scroll surface: the container, or the viewport itself
3664
+ * when a framework renders the messages — a wrapper's transcript stayed left to right
3665
+ * under a right-to-left locale while its composer turned.
3666
+ */
3634
3667
  _applyDirection() {
3635
- const container = this.querySelector(".aparte-viewport-container");
3668
+ const container = this._frameworkManagedDOM ? this : this.querySelector(".aparte-viewport-container");
3636
3669
  if (!container) return;
3637
3670
  const direction = resolveConfig(this).getLocale().direction;
3638
3671
  if (direction) container.setAttribute("dir", direction);
@@ -3989,6 +4022,7 @@ class AparteChatViewport extends HTMLElement {
3989
4022
  populateBubbleFromMessage(bubble, stored);
3990
4023
  }
3991
4024
  }
4025
+ if (this._bulkAppend) return;
3992
4026
  this._pruneRenderedBubbles();
3993
4027
  this._syncBusy();
3994
4028
  if (message.role === "user") {
@@ -4191,13 +4225,6 @@ class AparteChatViewport extends HTMLElement {
4191
4225
  this._checkpointState?.clear();
4192
4226
  this.dispatchEvent(new CustomEvent("aparte-reset-done", { bubbles: true, composed: true }));
4193
4227
  }
4194
- /**
4195
- * Clear all messages
4196
- * @deprecated Use clearAll() to also remove DOM bubbles
4197
- */
4198
- clearMessages() {
4199
- this._repo.clear();
4200
- }
4201
4228
  /**
4202
4229
  * Replace the entire message list in one shot. Used when switching
4203
4230
  * conversations: clears existing repo + DOM, then appends each message.
@@ -4208,9 +4235,19 @@ class AparteChatViewport extends HTMLElement {
4208
4235
  */
4209
4236
  setMessages(messages) {
4210
4237
  this.clearAll({ revokeAttachments: false });
4211
- for (const m2 of messages) {
4212
- this.appendMessage(m2, { historical: true });
4238
+ this._bulkAppend = true;
4239
+ try {
4240
+ for (const m2 of messages) {
4241
+ this.appendMessage(m2, { historical: true });
4242
+ }
4243
+ } finally {
4244
+ this._bulkAppend = false;
4213
4245
  }
4246
+ this._pruneRenderedBubbles();
4247
+ this._syncBusy();
4248
+ if (messages.some((m2) => m2.role === "user")) this._isAutoScrollEnabled = true;
4249
+ this._recalculateSpacer();
4250
+ this._autoScroll();
4214
4251
  }
4215
4252
  /**
4216
4253
  * Scroll to bottom of viewport
@@ -4435,6 +4472,7 @@ class AparteChatViewport extends HTMLElement {
4435
4472
  }
4436
4473
  this.classList.add("aparte-viewport--framework");
4437
4474
  this._nameScrollSurface(this);
4475
+ this._applyDirection();
4438
4476
  const scrollBtn = document.createElement("button");
4439
4477
  scrollBtn.className = "aparte-btn aparte-btn--surface aparte-btn--circle aparte-btn--lg aparte-scroll-btn aparte-scroll-btn--hidden";
4440
4478
  scrollBtn.setAttribute("type", "button");
@@ -5803,6 +5841,7 @@ class AparteComposerSend extends HTMLElement {
5803
5841
  class="aparte-btn aparte-btn--primary aparte-btn--solid aparte-btn--icon aparte-cs-button aparte-send-button"
5804
5842
  aria-label="${escapeAttr(label)}"
5805
5843
  title="${escapeAttr(label)}"
5844
+ data-act="send"
5806
5845
  ${disabled ? "disabled" : ""}
5807
5846
  >${icon}</button>`;
5808
5847
  }
@@ -5873,6 +5912,7 @@ class AparteComposerSend extends HTMLElement {
5873
5912
  }
5874
5913
  this._button.disabled = !panel.submitEnabled;
5875
5914
  this._button.innerHTML = this._getSubmitIcon();
5915
+ this._button.setAttribute("data-act", "submit");
5876
5916
  const label = cfg.t("submitButton") || "Submit";
5877
5917
  this._button.setAttribute("aria-label", label);
5878
5918
  this._button.setAttribute("title", label);
@@ -5889,6 +5929,7 @@ class AparteComposerSend extends HTMLElement {
5889
5929
  const isEmpty = root.value.trim() === "" && root.attachments.length === 0;
5890
5930
  this._button.disabled = root.disabled || isEmpty;
5891
5931
  this._button.innerHTML = this._getSendIcon();
5932
+ this._button.setAttribute("data-act", "send");
5892
5933
  const label = resolveConfig(this).t("sendButton") || "Send";
5893
5934
  this._button.setAttribute("aria-label", label);
5894
5935
  this._button.setAttribute("title", label);
@@ -5899,6 +5940,7 @@ class AparteComposerSend extends HTMLElement {
5899
5940
  if (streaming) {
5900
5941
  this._button.disabled = false;
5901
5942
  this._button.innerHTML = this._getStopIcon();
5943
+ this._button.setAttribute("data-act", "stop");
5902
5944
  const label = resolveConfig(this).t("stopButton") || "Stop";
5903
5945
  this._button.setAttribute("aria-label", label);
5904
5946
  this._button.setAttribute("title", label);
@@ -7173,6 +7215,7 @@ class AparteSuggestions extends HTMLElement {
7173
7215
  this._transcriptObserver?.disconnect();
7174
7216
  this._transcriptObserver = null;
7175
7217
  this._transcript = null;
7218
+ this._stopHolding();
7176
7219
  window.removeEventListener("aparte-config-change", this._onConfigChange);
7177
7220
  }
7178
7221
  attributeChangedCallback(name) {
@@ -7280,7 +7323,8 @@ class AparteSuggestions extends HTMLElement {
7280
7323
  const last = bubbles && bubbles.length ? bubbles[bubbles.length - 1] : null;
7281
7324
  const marks = last && last.getAttribute("data-role") !== "user" ? last.querySelectorAll("[data-aparte-suggestions]") : null;
7282
7325
  const mark = marks && marks.length ? marks[marks.length - 1] : null;
7283
- this._showAnswers(mark ? parseSuggestions(mark.getAttribute("data-aparte-suggestions") ?? "[]") : []);
7326
+ const offered = mark ? parseSuggestions(mark.getAttribute("data-aparte-suggestions") ?? "[]") : [];
7327
+ this._showAnswers(offered.map(visibleReply).filter((r) => r !== null));
7284
7328
  }
7285
7329
  /** Show these replies; the same ones already shown redraw nothing (a transcript mutation is frequent). */
7286
7330
  _showAnswers(list) {
@@ -7322,6 +7366,40 @@ class AparteSuggestions extends HTMLElement {
7322
7366
  }
7323
7367
  this.appendChild(row);
7324
7368
  }
7369
+ _sending = false;
7370
+ _sendingTimer;
7371
+ _stopHolding = () => {
7372
+ this._sending = false;
7373
+ clearTimeout(this._sendingTimer);
7374
+ window.removeEventListener("aparte-message-start", this._onTurnStart);
7375
+ };
7376
+ /**
7377
+ * The latch ends when ITS chat's turn starts. Another chat's `aparte-message-start` crosses the
7378
+ * window too, and must not release it: the second chip would then send a second message while the
7379
+ * first is still being built. The composer's own rule: an event naming no chat is for every chat.
7380
+ */
7381
+ _onTurnStart = (e) => {
7382
+ const from = e.detail?.targetId;
7383
+ const own = this._ownChatId();
7384
+ if (!from || !own || from === own) this._stopHolding();
7385
+ };
7386
+ /** The chat the sending composer belongs to: its `target`, else the id of the chat host above it. */
7387
+ _ownChatId() {
7388
+ const composer = this._composer;
7389
+ const attr = composer?.getAttribute("target");
7390
+ if (attr) return attr;
7391
+ for (let el2 = composer?.parentElement ?? null; el2; el2 = el2.parentElement) {
7392
+ if ((el2.tagName.toLowerCase() === "aparte-chat" || el2.hasAttribute("data-aparte-chat")) && el2.id) return el2.id;
7393
+ }
7394
+ return void 0;
7395
+ }
7396
+ /** A chip sent: no other chip sends until the turn has started, or a second has passed without one. */
7397
+ _holdUntilStreaming() {
7398
+ this._stopHolding();
7399
+ this._sending = true;
7400
+ window.addEventListener("aparte-message-start", this._onTurnStart);
7401
+ this._sendingTimer = setTimeout(this._stopHolding, 1e3);
7402
+ }
7325
7403
  _activate(suggestion) {
7326
7404
  const detail = { label: labelOf(suggestion), prompt: promptOf(suggestion) };
7327
7405
  const proceed = this.dispatchEvent(new CustomEvent("aparte-suggestion", {
@@ -7337,11 +7415,27 @@ class AparteSuggestions extends HTMLElement {
7337
7415
  return;
7338
7416
  }
7339
7417
  if (composer !== this._composer) this._watchComposer();
7418
+ const held = composer;
7419
+ if (held.panelActive) return;
7420
+ const fill = this.getAttribute("mode") === "fill";
7421
+ if (!fill && (held.streaming || this._sending)) return;
7340
7422
  const chipHadFocus = this.contains(document.activeElement);
7423
+ const draft = typeof composer.value === "string" ? composer.value : "";
7424
+ const files = fill ? [] : (composer.attachments ?? []).slice();
7425
+ if (files.length) composer.clearAttachments();
7341
7426
  composer.setValue(detail.prompt);
7342
- if (this.getAttribute("mode") === "fill") composer.focus();
7427
+ if (fill) composer.focus();
7343
7428
  else {
7429
+ let sent = false;
7430
+ const sawSend = () => {
7431
+ sent = true;
7432
+ };
7433
+ composer.addEventListener("aparte-send", sawSend, { once: true });
7344
7434
  composer.submit();
7435
+ composer.removeEventListener("aparte-send", sawSend);
7436
+ if (sent) this._holdUntilStreaming();
7437
+ if (files.length) composer.addAttachments(files);
7438
+ if ((typeof composer.value === "string" ? composer.value : "") !== draft) composer.setValue(draft);
7345
7439
  if (chipHadFocus) composer.focus();
7346
7440
  }
7347
7441
  }
@@ -7400,7 +7494,6 @@ class AparteContext extends HTMLElement {
7400
7494
  */
7401
7495
  _used = null;
7402
7496
  _level = null;
7403
- _compactRequested = false;
7404
7497
  /** The last turn's usage and the reply it belongs to, so the measure has it before the list has written it back. */
7405
7498
  _lastDone = null;
7406
7499
  /** What the model reads changed with nothing on the path to say so (a Restore): the reading is an estimate until the next turn reports. */
@@ -7431,7 +7524,7 @@ class AparteContext extends HTMLElement {
7431
7524
  this._viewChanged = false;
7432
7525
  this._blank = false;
7433
7526
  this._overflow = false;
7434
- this._render(true);
7527
+ this._render();
7435
7528
  };
7436
7529
  /**
7437
7530
  * A conversation is replaced — a new chat, or one loaded in place of the last — and the
@@ -7494,7 +7587,6 @@ class AparteContext extends HTMLElement {
7494
7587
  _onCompacted = (e) => {
7495
7588
  const detail = e.detail;
7496
7589
  if (!this._isMine(detail?.targetId)) return;
7497
- this._compactRequested = false;
7498
7590
  this._compact = null;
7499
7591
  if (detail?.skipped) {
7500
7592
  this._render();
@@ -7505,11 +7597,9 @@ class AparteContext extends HTMLElement {
7505
7597
  if (!this._messages()) this._used = null;
7506
7598
  this._render();
7507
7599
  };
7508
- /** A failed compaction spends the request too; the next `danger` asks again. */
7509
7600
  _onCompactError = (e) => {
7510
7601
  const detail = e.detail;
7511
7602
  if (!this._isMine(detail?.targetId)) return;
7512
- this._compactRequested = false;
7513
7603
  this._compact = detail?.aborted ? null : "failed";
7514
7604
  this._failure = detail?.aborted ? "" : typeof detail?.error === "string" ? detail.error : "";
7515
7605
  this._render();
@@ -7671,7 +7761,7 @@ class AparteContext extends HTMLElement {
7671
7761
  if (this._used === null) return null;
7672
7762
  return { window: capacity, used: this._used, estimated: false, parts: { ...NO_PARTS }, other: this._used };
7673
7763
  }
7674
- _render(askToCompact = false) {
7764
+ _render() {
7675
7765
  const capacity = this._window();
7676
7766
  const measure = capacity === null ? null : this._measure(capacity);
7677
7767
  if (this._compact) this.setAttribute("data-compact", this._compact);
@@ -7758,13 +7848,6 @@ class AparteContext extends HTMLElement {
7758
7848
  const targetId = this._ownTargetId();
7759
7849
  const detail = { level, used, window: capacity, ratio, targetId };
7760
7850
  this.dispatchEvent(new CustomEvent("aparte-context-threshold", { detail, bubbles: true, composed: true }));
7761
- if (level !== "danger") this._compactRequested = false;
7762
- }
7763
- if (askToCompact && level === "danger" && this.hasAttribute("auto-compact") && !this._compactRequested) {
7764
- this._compactRequested = true;
7765
- window.dispatchEvent(new CustomEvent("aparte-compact", {
7766
- detail: { targetId: this._ownTargetId(), auto: true, window: capacity }
7767
- }));
7768
7851
  }
7769
7852
  }
7770
7853
  // ─────────────────────────────────────────────────────────────────────────
@@ -7959,7 +8042,9 @@ class AparteContext extends HTMLElement {
7959
8042
  const anchor = this.getBoundingClientRect();
7960
8043
  const box = panel.getBoundingClientRect();
7961
8044
  if (box.height > 0 && anchor.top < box.height) panel.setAttribute("data-placement", "below");
7962
- if (box.width > 0 && box.right > document.documentElement.clientWidth) panel.setAttribute("data-align", "end");
8045
+ const rtl = getComputedStyle(panel).direction === "rtl";
8046
+ const overflows = rtl ? box.left < 0 : box.right > document.documentElement.clientWidth;
8047
+ if (box.width > 0 && overflows) panel.setAttribute("data-align", "end");
7963
8048
  }
7964
8049
  }
7965
8050
  deferHydrationOf(AparteContext);
@@ -7971,6 +8056,7 @@ const MIN_PITCH = 6;
7971
8056
  const SETTLE_MS = 150;
7972
8057
  const MAX_ALIGN_PASSES = 4;
7973
8058
  const ALIGN_TOLERANCE = 1;
8059
+ const BAND_PERCENT = 30;
7974
8060
  class AparteScrollRail extends HTMLElement {
7975
8061
  static get observedAttributes() {
7976
8062
  return ["target", "every"];
@@ -7978,18 +8064,39 @@ class AparteScrollRail extends HTMLElement {
7978
8064
  _host = null;
7979
8065
  _mutations = null;
7980
8066
  _resizes = null;
8067
+ /** The boxes the resize observer watches: the host, the transcript and its scroll surface. */
8068
+ _sized = [];
7981
8069
  _intersections = null;
7982
8070
  /** The bubbles the intersection observer watches — compared by identity, so a re-rendered bubble is re-observed. */
7983
8071
  _observedBubbles = [];
8072
+ /**
8073
+ * Every message the reading band watches: the ticked ones and, with `every="user"`, the
8074
+ * replies too, each read under the question above it.
8075
+ */
8076
+ _bandTargets = [];
7984
8077
  /** The scroll surface the observer is rooted on, and whose bottom edge is read. */
7985
8078
  _observedSurface = null;
7986
- _rebuildQueued = false;
8079
+ /** One frame does the queued work: a full rebuild when bubbles came or went, else the re-labels. */
8080
+ _frameQueued = false;
8081
+ _rebuildWanted = false;
8082
+ /** Ticked bubbles whose text changed since the last frame: only their names can have moved. */
8083
+ _relabel = /* @__PURE__ */ new Set();
8084
+ /**
8085
+ * Each message's excerpt, read once and forgotten when a mutation touches its text: a
8086
+ * rebuild re-read the head of all 500 questions of a long conversation, twice a turn, for
8087
+ * names that had not changed.
8088
+ */
8089
+ _excerpts = /* @__PURE__ */ new WeakMap();
7987
8090
  _pickQueued = false;
7988
8091
  _currentId = null;
7989
- /** Visible ratio per message id in the reading band, from the intersection observer. */
7990
- _visible = /* @__PURE__ */ new Map();
7991
- /** The bubbles on screen at all, from the second observer; only the last one is read. */
7992
- _onScreen = /* @__PURE__ */ new Set();
8092
+ /**
8093
+ * Visible ratio per message in the reading band, from the intersection observer. Keyed by
8094
+ * the element, not its id: an id changed in place keeps what the observer saw, and a
8095
+ * bubble that left is let go with it.
8096
+ */
8097
+ _visible = /* @__PURE__ */ new WeakMap();
8098
+ /** Whether the last question is on screen at all, from the second observer. */
8099
+ _onScreen = /* @__PURE__ */ new WeakSet();
7993
8100
  _onScreenObserver = null;
7994
8101
  /** The mark a jump asked for, held until the transcript has stopped moving. */
7995
8102
  _held = null;
@@ -8010,6 +8117,8 @@ class AparteScrollRail extends HTMLElement {
8010
8117
  if (!this.getAttribute("role")) this.setAttribute("role", "navigation");
8011
8118
  this.addEventListener("click", this._onClick);
8012
8119
  this.addEventListener("keydown", this._onKeydown);
8120
+ this.addEventListener("focusin", this._onFocusIn);
8121
+ this.addEventListener("focusout", this._onFocusOut);
8013
8122
  window.addEventListener("aparte-config-change", this._onConfigChange);
8014
8123
  this._attach();
8015
8124
  }
@@ -8017,6 +8126,8 @@ class AparteScrollRail extends HTMLElement {
8017
8126
  this._detach();
8018
8127
  this.removeEventListener("click", this._onClick);
8019
8128
  this.removeEventListener("keydown", this._onKeydown);
8129
+ this.removeEventListener("focusin", this._onFocusIn);
8130
+ this.removeEventListener("focusout", this._onFocusOut);
8020
8131
  window.removeEventListener("aparte-config-change", this._onConfigChange);
8021
8132
  }
8022
8133
  attributeChangedCallback(name) {
@@ -8045,16 +8156,37 @@ class AparteScrollRail extends HTMLElement {
8045
8156
  }
8046
8157
  if (typeof MutationObserver !== "undefined") {
8047
8158
  this._mutations = new MutationObserver((records) => {
8048
- if (records.some((record) => !this.contains(record.target))) this._queueRebuild();
8159
+ for (const record of records) {
8160
+ if (this.contains(record.target)) continue;
8161
+ if (record.type === "attributes") {
8162
+ if (isBubble(record.target)) {
8163
+ this._queueRebuild();
8164
+ return;
8165
+ }
8166
+ continue;
8167
+ }
8168
+ const at = record.target instanceof Element ? record.target : record.target.parentElement;
8169
+ const owner = at?.closest("aparte-chat-bubble");
8170
+ if (owner) {
8171
+ this._excerpts.delete(owner);
8172
+ if (this._ticked(owner)) this._queueRelabel(owner);
8173
+ continue;
8174
+ }
8175
+ if (record.type === "childList" && (holdsBubbles(record.addedNodes) || holdsBubbles(record.removedNodes))) {
8176
+ this._queueRebuild();
8177
+ return;
8178
+ }
8179
+ }
8180
+ });
8181
+ this._mutations.observe(this._host, {
8182
+ childList: true,
8183
+ subtree: true,
8184
+ characterData: true,
8185
+ attributes: true,
8186
+ attributeFilter: ["message-id", "data-role"]
8049
8187
  });
8050
- this._mutations.observe(this._host, { childList: true, subtree: true, characterData: true });
8051
- }
8052
- if (typeof ResizeObserver !== "undefined") {
8053
- this._resizes = new ResizeObserver(() => this._layout());
8054
- this._resizes.observe(this._host);
8055
- const viewport = this._viewport();
8056
- if (viewport) this._resizes.observe(viewport);
8057
8188
  }
8189
+ if (typeof ResizeObserver !== "undefined") this._resizes = new ResizeObserver(() => this._layout());
8058
8190
  this._rebuild();
8059
8191
  }
8060
8192
  _detach() {
@@ -8062,19 +8194,56 @@ class AparteScrollRail extends HTMLElement {
8062
8194
  this._mutations = null;
8063
8195
  this._resizes?.disconnect();
8064
8196
  this._resizes = null;
8197
+ this._sized = [];
8198
+ this._relabel.clear();
8199
+ this._rebuildWanted = false;
8065
8200
  this._unobserve();
8066
8201
  this._release();
8067
8202
  this._host = null;
8068
8203
  }
8069
- /** Coalesce a burst of mutations (a streaming reply is one per token) into one rebuild. */
8204
+ /** Coalesce a burst of mutations into one frame of work: a rebuild, which re-names every tick too. */
8070
8205
  _queueRebuild() {
8071
- if (this._rebuildQueued) return;
8072
- this._rebuildQueued = true;
8206
+ this._rebuildWanted = true;
8207
+ this._queueFrame();
8208
+ }
8209
+ _queueRelabel(bubble) {
8210
+ this._relabel.add(bubble);
8211
+ this._queueFrame();
8212
+ }
8213
+ _queueFrame() {
8214
+ if (this._frameQueued) return;
8215
+ this._frameQueued = true;
8073
8216
  requestAnimationFrame(() => {
8074
- this._rebuildQueued = false;
8075
- this._rebuild();
8217
+ this._frameQueued = false;
8218
+ const relabel = [...this._relabel];
8219
+ this._relabel.clear();
8220
+ if (this._rebuildWanted) {
8221
+ this._rebuildWanted = false;
8222
+ this._rebuild();
8223
+ return;
8224
+ }
8225
+ const locale = resolveConfig(this).getLocale();
8226
+ for (const bubble of relabel) this._label(bubble, locale);
8076
8227
  });
8077
8228
  }
8229
+ /** Whether a bubble has a tick: every message with `every="message"`, else the user's. */
8230
+ _ticked(bubble) {
8231
+ if (!bubble.hasAttribute("message-id")) return false;
8232
+ return this.getAttribute("every") === "message" || bubble.getAttribute("data-role") === "user";
8233
+ }
8234
+ /** Re-name one bubble's tick, written only when the name changed. */
8235
+ _label(bubble, locale) {
8236
+ if (!this._host?.contains(bubble)) return;
8237
+ const id = bubble.getAttribute("message-id");
8238
+ if (!id) return;
8239
+ const tick = this.querySelector(`.aparte-scroll-rail__tick[data-message-id="${cssEscape(id)}"]`);
8240
+ if (!tick) return;
8241
+ const label = this._tickLabel(bubble, locale);
8242
+ if (tick.getAttribute("aria-label") !== label) {
8243
+ tick.setAttribute("aria-label", label);
8244
+ tick.title = label;
8245
+ }
8246
+ }
8078
8247
  _viewport() {
8079
8248
  return this._host?.querySelector("aparte-chat-viewport") ?? null;
8080
8249
  }
@@ -8084,22 +8253,31 @@ class AparteScrollRail extends HTMLElement {
8084
8253
  if (!viewport) return null;
8085
8254
  return viewport.querySelector(".aparte-viewport-container") ?? viewport;
8086
8255
  }
8087
- _bubbles() {
8256
+ /** Every message bubble of the transcript, in document order. */
8257
+ _messages() {
8088
8258
  const viewport = this._viewport();
8089
- if (!viewport) return [];
8259
+ return viewport ? Array.from(viewport.querySelectorAll("aparte-chat-bubble[message-id]")) : [];
8260
+ }
8261
+ /** The bubbles that get a tick, from all of them. */
8262
+ _bubbles(all = this._messages()) {
8090
8263
  const every = this.getAttribute("every") === "message" ? "message" : "user";
8091
- const all = Array.from(viewport.querySelectorAll("aparte-chat-bubble[message-id]"));
8092
8264
  return every === "message" ? all : all.filter((b2) => b2.getAttribute("data-role") === "user");
8093
8265
  }
8094
8266
  // ─── Rendering ────────────────────────────────────────────────────────
8095
8267
  /** The first words of a message, for the tick's name. An excerpt, never a summary. */
8096
8268
  _excerpt(bubble) {
8269
+ const known = this._excerpts.get(bubble);
8270
+ if (known !== void 0) return known;
8097
8271
  const body = bubble.querySelector(".aparte-message-content") ?? bubble;
8098
- const text = (body.textContent ?? "").replace(/\s+/g, " ").trim();
8099
- return text.length > EXCERPT_LENGTH ? `${text.slice(0, EXCERPT_LENGTH - 1).trimEnd()}…` : text;
8100
- }
8101
- _tickLabel(bubble) {
8102
- const locale = resolveConfig(this).getLocale();
8272
+ let head = "";
8273
+ const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
8274
+ for (let node = walker.nextNode(); node && head.length < EXCERPT_LENGTH * 16; node = walker.nextNode()) head += node.nodeValue ?? "";
8275
+ const text = head.slice(0, EXCERPT_LENGTH * 16).replace(/\s+/g, " ").trim();
8276
+ const excerpt = text.length > EXCERPT_LENGTH ? `${text.slice(0, EXCERPT_LENGTH - 1).trimEnd()}…` : text;
8277
+ this._excerpts.set(bubble, excerpt);
8278
+ return excerpt;
8279
+ }
8280
+ _tickLabel(bubble, locale) {
8103
8281
  const role = bubble.getAttribute("data-role") === "user" ? locale.roleNameUser ?? "You" : locale.roleNameAssistant ?? "Assistant";
8104
8282
  const excerpt = this._excerpt(bubble);
8105
8283
  return excerpt ? `${role}: ${excerpt}` : role;
@@ -8114,7 +8292,9 @@ class AparteScrollRail extends HTMLElement {
8114
8292
  * and dropped when its bubble left.
8115
8293
  */
8116
8294
  _rebuild() {
8117
- const bubbles = this._bubbles();
8295
+ this._watchSizes();
8296
+ const all = this._messages();
8297
+ const bubbles = this._bubbles(all);
8118
8298
  const locale = resolveConfig(this).getLocale();
8119
8299
  const railLabel = locale.scrollRailLabel ?? "Conversation outline";
8120
8300
  if (this.getAttribute("aria-label") !== railLabel) this.setAttribute("aria-label", railLabel);
@@ -8124,6 +8304,7 @@ class AparteScrollRail extends HTMLElement {
8124
8304
  this._unobserve();
8125
8305
  this._currentId = null;
8126
8306
  this._write("--aparte-scroll-rail-hit-size", "");
8307
+ this._write("--aparte-scroll-rail-gap", "");
8127
8308
  return;
8128
8309
  }
8129
8310
  this.removeAttribute("data-empty");
@@ -8138,24 +8319,27 @@ class AparteScrollRail extends HTMLElement {
8138
8319
  const id = item.firstElementChild instanceof HTMLElement ? item.firstElementChild.dataset["messageId"] : void 0;
8139
8320
  if (id) existing.set(id, item);
8140
8321
  }
8141
- const known = /* @__PURE__ */ new Set();
8142
- let index = 0;
8322
+ const known = new Set(bubbles.map((b2) => b2.getAttribute("message-id")));
8323
+ for (const [id, item] of existing) {
8324
+ if (known.has(id)) continue;
8325
+ item.remove();
8326
+ existing.delete(id);
8327
+ }
8328
+ let at = list.firstElementChild;
8143
8329
  for (const bubble of bubbles) {
8144
8330
  const id = bubble.getAttribute("message-id");
8145
- known.add(id);
8146
8331
  let item = existing.get(id);
8147
- if (item) {
8148
- existing.delete(id);
8149
- } else {
8332
+ if (!item) {
8150
8333
  item = document.createElement("li");
8151
8334
  const tick2 = document.createElement("button");
8152
8335
  tick2.type = "button";
8153
8336
  tick2.className = "aparte-scroll-rail__tick";
8154
8337
  tick2.dataset["messageId"] = id;
8338
+ tick2.tabIndex = -1;
8155
8339
  item.appendChild(tick2);
8156
8340
  }
8157
8341
  const tick = item.firstElementChild;
8158
- const label = this._tickLabel(bubble);
8342
+ const label = this._tickLabel(bubble, locale);
8159
8343
  if (tick.getAttribute("aria-label") !== label) {
8160
8344
  tick.setAttribute("aria-label", label);
8161
8345
  tick.title = label;
@@ -8165,14 +8349,15 @@ class AparteScrollRail extends HTMLElement {
8165
8349
  } else {
8166
8350
  tick.removeAttribute("aria-current");
8167
8351
  }
8168
- const at = list.children[index] ?? null;
8169
- if (at !== item) list.insertBefore(item, at);
8170
- index++;
8352
+ if (item === at) at = at.nextElementSibling;
8353
+ else list.insertBefore(item, at);
8171
8354
  }
8172
- for (const stale of existing.values()) stale.remove();
8173
- if (this._currentId && !known.has(this._currentId)) this._currentId = null;
8174
- if (!sameElements(this._observedBubbles, bubbles)) this._observe(bubbles);
8355
+ const dropped = this._currentId !== null && !known.has(this._currentId);
8356
+ if (dropped) this._currentId = null;
8357
+ this._syncTabStop();
8358
+ if (!sameElements(this._observedBubbles, bubbles) || !sameElements(this._bandTargets, all)) this._observe(bubbles, all);
8175
8359
  this._layout();
8360
+ if (dropped) this._pickCurrent();
8176
8361
  }
8177
8362
  /**
8178
8363
  * Which tick is current is read, not computed: the scroll surface is the root and an
@@ -8184,35 +8369,50 @@ class AparteScrollRail extends HTMLElement {
8184
8369
  * position read is the bottom, because there the reader is under the latest question
8185
8370
  * whatever the band holds, and the observer has nothing to report on the last few
8186
8371
  * pixels.
8187
- */
8188
- _observe(bubbles) {
8189
- this._unobserve();
8190
- this._observedBubbles = bubbles;
8191
- if (typeof IntersectionObserver === "undefined") return;
8192
- const root = this._scrollSurface();
8193
- if (!root) return;
8194
- this._intersections = new IntersectionObserver((entries) => {
8195
- for (const entry of entries) {
8196
- const id = entry.target.getAttribute("message-id");
8197
- if (id) this._visible.set(id, entry.isIntersecting ? entry.intersectionRatio : 0);
8198
- }
8199
- this._pickCurrent();
8200
- }, { root, rootMargin: "0px 0px -70% 0px", threshold: [0, 0.1, 0.25, 0.5, 0.75, 1] });
8201
- this._onScreenObserver = new IntersectionObserver((entries) => {
8202
- for (const entry of entries) {
8203
- const id = entry.target.getAttribute("message-id");
8204
- if (!id) continue;
8205
- if (entry.isIntersecting) this._onScreen.add(id);
8206
- else this._onScreen.delete(id);
8207
- }
8208
- this._pickCurrent();
8209
- }, { root, threshold: [0] });
8210
- for (const bubble of bubbles) {
8211
- this._intersections.observe(bubble);
8212
- this._onScreenObserver.observe(bubble);
8372
+ *
8373
+ * The replies are watched too, and a reply in the band is read under its question. With
8374
+ * the questions alone the band was empty whenever the reader was inside a long reply, and
8375
+ * nothing moved the mark when the layout did: a bubble never rendered has an estimated
8376
+ * height (`content-visibility`) and takes its real one once the scroll has stopped, so a
8377
+ * still reader's question changed with no scroll and no question crossing the band. The
8378
+ * observer reports a reply entering the band whatever moved it.
8379
+ */
8380
+ _observe(bubbles, all) {
8381
+ const root = typeof IntersectionObserver === "undefined" ? null : this._scrollSurface();
8382
+ if (!root) {
8383
+ this._unobserve();
8384
+ this._observedBubbles = bubbles;
8385
+ this._bandTargets = all;
8386
+ return;
8387
+ }
8388
+ if (!this._intersections || !this._onScreenObserver || this._observedSurface !== root) {
8389
+ this._unobserve();
8390
+ this._intersections = new IntersectionObserver((entries) => {
8391
+ for (const entry of entries) this._visible.set(entry.target, entry.isIntersecting ? entry.intersectionRatio : 0);
8392
+ this._pickCurrent();
8393
+ }, { root, rootMargin: `0px 0px -${100 - BAND_PERCENT}% 0px`, threshold: [0, 0.1, 0.25, 0.5, 0.75, 1] });
8394
+ this._onScreenObserver = new IntersectionObserver((entries) => {
8395
+ for (const entry of entries) {
8396
+ if (entry.isIntersecting) this._onScreen.add(entry.target);
8397
+ else this._onScreen.delete(entry.target);
8398
+ }
8399
+ this._pickCurrent();
8400
+ }, { root, threshold: [0] });
8401
+ this._observedSurface = root;
8402
+ root.addEventListener("scroll", this._onRootScroll, { passive: true });
8403
+ }
8404
+ const next = new Set(all);
8405
+ for (const bubble of this._bandTargets) if (!next.has(bubble)) this._intersections.unobserve(bubble);
8406
+ const before = new Set(this._bandTargets);
8407
+ for (const bubble of all) if (!before.has(bubble)) this._intersections.observe(bubble);
8408
+ const last = bubbles[bubbles.length - 1];
8409
+ const previous = this._observedBubbles[this._observedBubbles.length - 1];
8410
+ if (previous !== last) {
8411
+ if (previous) this._onScreenObserver.unobserve(previous);
8412
+ this._onScreenObserver.observe(last);
8213
8413
  }
8214
- this._observedSurface = root;
8215
- root.addEventListener("scroll", this._onRootScroll, { passive: true });
8414
+ this._observedBubbles = bubbles;
8415
+ this._bandTargets = all;
8216
8416
  }
8217
8417
  _unobserve() {
8218
8418
  this._intersections?.disconnect();
@@ -8222,8 +8422,9 @@ class AparteScrollRail extends HTMLElement {
8222
8422
  this._observedSurface?.removeEventListener("scroll", this._onRootScroll);
8223
8423
  this._observedSurface = null;
8224
8424
  this._observedBubbles = [];
8225
- this._visible.clear();
8226
- this._onScreen.clear();
8425
+ this._bandTargets = [];
8426
+ this._visible = /* @__PURE__ */ new WeakMap();
8427
+ this._onScreen = /* @__PURE__ */ new WeakSet();
8227
8428
  }
8228
8429
  /** A scroll only matters at the bottom edge, where the observer is silent: one pick per frame. */
8229
8430
  _onRootScroll = () => {
@@ -8245,18 +8446,65 @@ class AparteScrollRail extends HTMLElement {
8245
8446
  if (this._held) return;
8246
8447
  const bubbles = this._observedBubbles;
8247
8448
  if (bubbles.length === 0) return;
8248
- const lastId = bubbles[bubbles.length - 1].getAttribute("message-id");
8249
- if (this._atBottom() || this._onScreen.has(lastId)) {
8449
+ const lastBubble = bubbles[bubbles.length - 1];
8450
+ const lastId = lastBubble.getAttribute("message-id");
8451
+ if (this._atBottom() || this._onScreen.has(lastBubble)) {
8250
8452
  this._setCurrent(lastId);
8251
8453
  return;
8252
8454
  }
8253
8455
  let last = null;
8254
- for (const bubble of bubbles) {
8255
- const id = bubble.getAttribute("message-id");
8256
- if ((this._visible.get(id) ?? 0) > 0) last = id;
8456
+ let above = null;
8457
+ let seen = false;
8458
+ for (const bubble of this._bandTargets) {
8459
+ if (this._ticked(bubble)) above = bubble.getAttribute("message-id");
8460
+ if ((this._visible.get(bubble) ?? 0) > 0) {
8461
+ seen = true;
8462
+ if (above !== null) last = above;
8463
+ }
8257
8464
  }
8465
+ if (last === null && seen) return;
8466
+ last ??= this._lastAbove();
8258
8467
  if (last !== null) this._setCurrent(last);
8259
8468
  }
8469
+ /**
8470
+ * The last question whose top is above the reading band's lower edge: by halves, since
8471
+ * the questions are in document order and their tops only grow. A question never
8472
+ * rendered has its estimated height (`content-visibility`), which keeps that order.
8473
+ * `null` when no question is above the edge or nothing is laid out, and the mark stays
8474
+ * as it was.
8475
+ */
8476
+ _lastAbove() {
8477
+ const surface = this._observedSurface;
8478
+ const bubbles = this._observedBubbles;
8479
+ if (!surface || bubbles.length === 0) return null;
8480
+ const box = surface.getBoundingClientRect();
8481
+ if (box.height <= 0) return null;
8482
+ const edge = box.top + box.height * BAND_PERCENT / 100;
8483
+ let low = 0;
8484
+ let high = bubbles.length - 1;
8485
+ let found = -1;
8486
+ while (low <= high) {
8487
+ const mid = low + high >> 1;
8488
+ if (bubbles[mid].getBoundingClientRect().top < edge) {
8489
+ found = mid;
8490
+ low = mid + 1;
8491
+ } else {
8492
+ high = mid - 1;
8493
+ }
8494
+ }
8495
+ return found < 0 ? null : bubbles[found].getAttribute("message-id");
8496
+ }
8497
+ /** The tick a message is read under: its own, else the question above it, as the band reads a reply. */
8498
+ _markFor(bubble) {
8499
+ const id = bubble.getAttribute("message-id");
8500
+ if (this._ticked(bubble)) return id;
8501
+ let above = null;
8502
+ for (const candidate of this._messages()) {
8503
+ if (candidate === bubble) break;
8504
+ if (this._ticked(candidate)) above = candidate.getAttribute("message-id");
8505
+ }
8506
+ return above ?? id;
8507
+ }
8260
8508
  _setCurrent(id) {
8261
8509
  if (this._currentId === id) return;
8262
8510
  this._currentId = id;
@@ -8268,6 +8516,40 @@ class AparteScrollRail extends HTMLElement {
8268
8516
  tick.removeAttribute("aria-current");
8269
8517
  }
8270
8518
  }
8519
+ this._syncTabStop();
8520
+ }
8521
+ /**
8522
+ * One Tab stop for the whole rail, as in a toolbar: the tick that has the focus, else
8523
+ * the current one, else the last. Every tick was a button in the tab order, so a
8524
+ * keyboard reader crossed 500 of them between the transcript and the composer of a
8525
+ * long conversation; the arrows, Home and End walk the rail instead.
8526
+ */
8527
+ _syncTabStop(ignoreFocus = false) {
8528
+ const ticks = Array.from(this.querySelectorAll(".aparte-scroll-rail__tick"));
8529
+ if (ticks.length === 0) return;
8530
+ const focused = ignoreFocus ? null : activeElementIn(this);
8531
+ const stop = (focused instanceof HTMLElement && ticks.includes(focused) ? focused : void 0) ?? ticks.find((t) => t.dataset["messageId"] === this._currentId) ?? ticks[ticks.length - 1];
8532
+ this._setTabStop(stop, ticks);
8533
+ }
8534
+ /**
8535
+ * The stop follows the focus onto a tick, however it got there: the arrows, a click (a
8536
+ * click on the current tick moved the focus but not the stop, which made two), a host's
8537
+ * `focus()`.
8538
+ */
8539
+ _onFocusIn = (e) => {
8540
+ const tick = e.target instanceof HTMLElement && e.target.classList.contains("aparte-scroll-rail__tick") ? e.target : null;
8541
+ if (tick && this.contains(tick)) this._setTabStop(tick, Array.from(this.querySelectorAll(".aparte-scroll-rail__tick")));
8542
+ };
8543
+ /** Leaving the rail, the stop goes back to the current tick: Tab back in lands where the reader is. */
8544
+ _onFocusOut = (e) => {
8545
+ if (e.relatedTarget instanceof Node && this.contains(e.relatedTarget)) return;
8546
+ this._syncTabStop(true);
8547
+ };
8548
+ _setTabStop(stop, ticks) {
8549
+ for (const tick of ticks) {
8550
+ const wanted = tick === stop ? 0 : -1;
8551
+ if (tick.tabIndex !== wanted) tick.tabIndex = wanted;
8552
+ }
8271
8553
  }
8272
8554
  /** Past the floor the rail scrolls itself: the current tick is kept inside its window. */
8273
8555
  _reveal(tick) {
@@ -8279,6 +8561,22 @@ class AparteScrollRail extends HTMLElement {
8279
8561
  else if (bottom > this.scrollTop + room) this.scrollTop = bottom - room;
8280
8562
  }
8281
8563
  // ─── Geometry ─────────────────────────────────────────────────────────
8564
+ /**
8565
+ * Point the resize observer at the boxes the geometry is read from. Re-pointed on each
8566
+ * rebuild: a viewport a wrapper mounts after the rail, or replaces, was never watched, and
8567
+ * the panel or composer that resized it later left the rail measuring the old box. The
8568
+ * scroll surface is watched for itself: a classic scrollbar appearing narrows it without
8569
+ * resizing the viewport, and the rail has to move clear of the bar.
8570
+ */
8571
+ _watchSizes() {
8572
+ if (!this._resizes) return;
8573
+ const wanted = [];
8574
+ for (const box of [this._host, this._viewport(), this._scrollSurface()]) if (box && !wanted.includes(box)) wanted.push(box);
8575
+ if (sameElements(this._sized, wanted)) return;
8576
+ for (const box of this._sized) if (!wanted.includes(box)) this._resizes.unobserve(box);
8577
+ for (const box of wanted) if (!this._sized.includes(box)) this._resizes.observe(box);
8578
+ this._sized = wanted;
8579
+ }
8282
8580
  /** Write a custom property on this element only when its value changed; '' removes it. */
8283
8581
  _write(name, value) {
8284
8582
  if (this._written.get(name) === value) return;
@@ -8313,18 +8611,18 @@ class AparteScrollRail extends HTMLElement {
8313
8611
  this._write("--aparte-scroll-rail-block-end", `${Math.max(0, Math.round(h2.bottom - v2.bottom))}px`);
8314
8612
  }
8315
8613
  }
8316
- const count = this._list()?.children.length ?? 0;
8317
- const height = this.clientHeight;
8318
- if (!count || !height) {
8319
- this._write("--aparte-scroll-rail-hit-size", "");
8320
- this._write("--aparte-scroll-rail-gap", "");
8321
- return;
8322
- }
8323
8614
  const above = host ?? document.documentElement;
8324
8615
  const aboveStyle = getComputedStyle(above);
8325
8616
  const hit = parseFloat(aboveStyle.getPropertyValue("--aparte-scroll-rail-hit-size")) || 24;
8326
8617
  const thickness = parseFloat(aboveStyle.getPropertyValue("--aparte-scroll-rail-tick-thickness")) || 2;
8327
- if (count * hit <= height) {
8618
+ const tightened = (this._written.get("--aparte-scroll-rail-hit-size") ?? "") !== "";
8619
+ if (tightened && this.scrollHeight <= this.clientHeight + 1) {
8620
+ this._write("--aparte-scroll-rail-hit-size", "");
8621
+ this._write("--aparte-scroll-rail-gap", "");
8622
+ }
8623
+ const height = this.clientHeight;
8624
+ const count = this._list()?.children.length ?? 0;
8625
+ if (!count || !height || count * hit <= height) {
8328
8626
  this._write("--aparte-scroll-rail-hit-size", "");
8329
8627
  this._write("--aparte-scroll-rail-gap", "");
8330
8628
  return;
@@ -8349,7 +8647,10 @@ class AparteScrollRail extends HTMLElement {
8349
8647
  if (index === -1) return;
8350
8648
  e.preventDefault();
8351
8649
  const next = e.key === "Home" ? 0 : e.key === "End" ? ticks.length - 1 : e.key === "ArrowDown" ? Math.min(ticks.length - 1, index + 1) : Math.max(0, index - 1);
8352
- ticks[next]?.focus();
8650
+ const target = ticks[next];
8651
+ if (!target) return;
8652
+ this._setTabStop(target, ticks);
8653
+ target.focus();
8353
8654
  };
8354
8655
  /**
8355
8656
  * Scroll the transcript to a message. Announced first, cancelable; then a
@@ -8376,7 +8677,7 @@ class AparteScrollRail extends HTMLElement {
8376
8677
  if (!bubble) return;
8377
8678
  this._viewport()?.setAutoScroll?.(false);
8378
8679
  this._scrollTo(bubble);
8379
- this._setCurrent(messageId);
8680
+ this._setCurrent(this._markFor(bubble));
8380
8681
  this._hold(messageId);
8381
8682
  }
8382
8683
  _bubbleOf(messageId) {
@@ -8415,7 +8716,7 @@ class AparteScrollRail extends HTMLElement {
8415
8716
  }
8416
8717
  }
8417
8718
  this._release();
8418
- if (id) this._setCurrent(id);
8719
+ if (id) this._setCurrent(bubble ? this._markFor(bubble) : id);
8419
8720
  }
8420
8721
  _release() {
8421
8722
  if (this._settleTimer !== null) clearTimeout(this._settleTimer);
@@ -8425,6 +8726,12 @@ class AparteScrollRail extends HTMLElement {
8425
8726
  this._held = null;
8426
8727
  }
8427
8728
  }
8729
+ function isBubble(node) {
8730
+ return node instanceof Element && node.localName === "aparte-chat-bubble";
8731
+ }
8732
+ function holdsBubbles(nodes) {
8733
+ return Array.from(nodes).some((n2) => n2 instanceof Element && (isBubble(n2) || n2.localName === "aparte-chat-viewport" || n2.querySelector("aparte-chat-bubble") !== null));
8734
+ }
8428
8735
  function sameElements(a4, b2) {
8429
8736
  if (a4.length !== b2.length) return false;
8430
8737
  for (let i2 = 0; i2 < a4.length; i2++) if (a4[i2] !== b2[i2]) return false;
@@ -8620,7 +8927,7 @@ class AparteSidebar extends HTMLElement {
8620
8927
  const root = rootOf(this);
8621
8928
  const controls = root === document ? Array.from(document.querySelectorAll(selector)) : [...root.querySelectorAll(selector), ...document.querySelectorAll(selector)];
8622
8929
  for (const control of controls) {
8623
- if (!this._drives(control)) continue;
8930
+ if (inRenderedContent(control) || !this._drives(control)) continue;
8624
8931
  control.setAttribute("aria-expanded", String(!this.collapsed));
8625
8932
  control.setAttribute("aria-controls", this.id);
8626
8933
  }
@@ -8708,7 +9015,7 @@ class AparteSidebar extends HTMLElement {
8708
9015
  /** A `[data-aparte-sidebar-toggle]` anywhere toggles this sidebar — no script in the host. */
8709
9016
  _onDocumentClick = (e) => {
8710
9017
  const control = eventOrigin(e)?.closest?.("[data-aparte-sidebar-toggle]");
8711
- if (!control) return;
9018
+ if (!control || inRenderedContent(control)) return;
8712
9019
  if (!this._drives(control)) return;
8713
9020
  this.toggle(control);
8714
9021
  };
@@ -9509,7 +9816,7 @@ class AparteSplit extends HTMLElement {
9509
9816
  */
9510
9817
  _onDocumentClick = (e) => {
9511
9818
  const control = eventOrigin(e)?.closest?.("[data-aparte-split-pane]");
9512
- if (!control) return;
9819
+ if (!control || inRenderedContent(control)) return;
9513
9820
  const value = (control.getAttribute("data-aparte-split-pane") ?? "").trim();
9514
9821
  const which = value === "start" || value === "end" ? value : null;
9515
9822
  const named = which ? "" : value;
@@ -9536,6 +9843,7 @@ class AparteSplit extends HTMLElement {
9536
9843
  const which = (control.getAttribute("data-aparte-split-pane") ?? "").trim();
9537
9844
  if (which !== "start" && which !== "end") continue;
9538
9845
  if (control.localName !== "button" && control.getAttribute("role") !== "button") continue;
9846
+ if (inRenderedContent(control)) continue;
9539
9847
  const target = control.closest("aparte-split") ?? rootOf(control).querySelector("aparte-split") ?? document.querySelector("aparte-split");
9540
9848
  if (target !== this) continue;
9541
9849
  if (this.stacked) control.setAttribute("aria-pressed", String(which === this.pane));
@@ -9702,7 +10010,8 @@ class AparteLauncher extends HTMLElement {
9702
10010
  * in another language. Resolved live, never kept: the boundary may arrive after connect.
9703
10011
  */
9704
10012
  _config() {
9705
- return resolveConfig(this.querySelector(`[${APARTE_HOST_ATTR}]`) ?? this);
10013
+ const boundary = Array.from(this.querySelectorAll(`[${APARTE_HOST_ATTR}]`)).find((el2) => !inRenderedContent(el2));
10014
+ return resolveConfig(boundary ?? this);
9706
10015
  }
9707
10016
  /**
9708
10017
  * The button is a child of the element, whatever was done to the children since: put
@@ -9784,14 +10093,14 @@ class AparteLauncher extends HTMLElement {
9784
10093
  * person just pressed.
9785
10094
  */
9786
10095
  _focusChat() {
9787
- const composer = Array.from(this.querySelectorAll('[role="textbox"]:not([aria-disabled="true"])')).find((el2) => !el2.closest("[hidden]") && el2.checkVisibility?.() !== false);
10096
+ const composer = Array.from(this.querySelectorAll('[role="textbox"]:not([aria-disabled="true"])')).find((el2) => !inRenderedContent(el2) && !el2.closest("[hidden]") && el2.checkVisibility?.() !== false);
9788
10097
  const target = composer ?? this._focusables().find((el2) => el2 !== this._button);
9789
10098
  target?.focus();
9790
10099
  }
9791
10100
  /** A `[data-aparte-launcher-close]` inside closes the chat — no script in your card. */
9792
10101
  _onClick = (e) => {
9793
10102
  const control = eventOrigin(e)?.closest?.("[data-aparte-launcher-close]");
9794
- if (control && this.contains(control)) this.close();
10103
+ if (control && this.contains(control) && !inRenderedContent(control)) this.close();
9795
10104
  };
9796
10105
  /**
9797
10106
  * A modal dialog open inside the card, with the key pressed inside it. The browser
@@ -9836,6 +10145,45 @@ deferHydrationOf(AparteLauncher);
9836
10145
  if (!customElements.get("aparte-launcher")) {
9837
10146
  customElements.define("aparte-launcher", AparteLauncher);
9838
10147
  }
10148
+ const INSTALLED = Symbol.for("aparte.imageHolds");
10149
+ const HELD = ".aparte-image-held[data-aparte-image]";
10150
+ function showHeldImage(link) {
10151
+ const address = link.getAttribute("data-aparte-image") ?? "";
10152
+ resolveConfig(link).showImage(address);
10153
+ const img = document.createElement("img");
10154
+ img.setAttribute("referrerpolicy", "no-referrer");
10155
+ img.setAttribute("alt", link.getAttribute("data-aparte-image-alt") ?? "");
10156
+ img.setAttribute("src", address);
10157
+ const focused = link === document.activeElement;
10158
+ link.replaceWith(img);
10159
+ if (focused) {
10160
+ img.tabIndex = -1;
10161
+ img.focus({ preventScroll: true });
10162
+ }
10163
+ }
10164
+ function onClick(event) {
10165
+ if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
10166
+ const link = event.target?.closest?.(HELD);
10167
+ if (!link) return;
10168
+ event.preventDefault();
10169
+ event.stopPropagation();
10170
+ showHeldImage(link);
10171
+ }
10172
+ function onKeyDown(event) {
10173
+ if (event.key !== "Enter" && event.key !== " ") return;
10174
+ const button = event.target;
10175
+ if (!button?.matches?.(`span${HELD}`)) return;
10176
+ event.preventDefault();
10177
+ event.stopPropagation();
10178
+ showHeldImage(button);
10179
+ }
10180
+ function installImageHoldsOnce() {
10181
+ const doc = document;
10182
+ if (doc[INSTALLED]) return;
10183
+ doc[INSTALLED] = true;
10184
+ doc.addEventListener("click", onClick, true);
10185
+ doc.addEventListener("keydown", onKeyDown, true);
10186
+ }
9839
10187
  const APARTE_ELEMENTS = [
9840
10188
  // Chat shell + transcript
9841
10189
  ["aparte-chat", AparteChat],
@@ -9875,7 +10223,10 @@ function registerAllComponents() {
9875
10223
  );
9876
10224
  }
9877
10225
  }
9878
- if (typeof document !== "undefined") installDialogTriggersOnce();
10226
+ if (typeof document !== "undefined") {
10227
+ installDialogTriggersOnce();
10228
+ installImageHoldsOnce();
10229
+ }
9879
10230
  export {
9880
10231
  A as APARTE_CONFIG_CHANGE,
9881
10232
  a as APARTE_CONVERSATION_SCHEMA_VERSION,