@aparte/core 0.32.1 → 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 (68) 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/context/aparte-context.d.ts +4 -11
  6. package/dist/components/context/aparte-context.d.ts.map +1 -1
  7. package/dist/components/launcher/aparte-launcher.d.ts.map +1 -1
  8. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts +77 -5
  9. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts.map +1 -1
  10. package/dist/components/sidebar/aparte-sidebar.d.ts.map +1 -1
  11. package/dist/components/split/aparte-split.d.ts.map +1 -1
  12. package/dist/components/suggestions/aparte-suggestions.d.ts +15 -1
  13. package/dist/components/suggestions/aparte-suggestions.d.ts.map +1 -1
  14. package/dist/components/suggestions/suggestion-blocks.d.ts +21 -1
  15. package/dist/components/suggestions/suggestion-blocks.d.ts.map +1 -1
  16. package/dist/components/viewport/aparte-chat-viewport.d.ts +2 -5
  17. package/dist/components/viewport/aparte-chat-viewport.d.ts.map +1 -1
  18. package/dist/config/aparte-config.d.ts +56 -4
  19. package/dist/config/aparte-config.d.ts.map +1 -1
  20. package/dist/config/config-context.d.ts.map +1 -1
  21. package/dist/config/image-policy.d.ts +104 -0
  22. package/dist/config/image-policy.d.ts.map +1 -0
  23. package/dist/config/index.d.ts +1 -0
  24. package/dist/config/index.d.ts.map +1 -1
  25. package/dist/config/locale.d.ts +8 -10
  26. package/dist/config/locale.d.ts.map +1 -1
  27. package/dist/config/sanitize.d.ts +36 -0
  28. package/dist/config/sanitize.d.ts.map +1 -1
  29. package/dist/custom-elements.json +3357 -2243
  30. package/dist/{defer-hydration-DQKULLmH.js → defer-hydration-Dw5D80FC.js} +810 -61
  31. package/dist/defer-hydration-Dw5D80FC.js.map +1 -0
  32. package/dist/generated/element-attributes.d.ts +1 -3
  33. package/dist/generated/element-attributes.d.ts.map +1 -1
  34. package/dist/index.css +1 -1
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +459 -119
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.node.d.ts +2 -2
  40. package/dist/index.node.d.ts.map +1 -1
  41. package/dist/index.node.js +1 -1
  42. package/dist/index.node.js.map +1 -1
  43. package/dist/interop/dialog-triggers.d.ts.map +1 -1
  44. package/dist/interop/image-holds.d.ts +20 -0
  45. package/dist/interop/image-holds.d.ts.map +1 -0
  46. package/dist/transport/agent-handler.d.ts +10 -0
  47. package/dist/transport/agent-handler.d.ts.map +1 -1
  48. package/dist/transport/agent-ticket.d.ts.map +1 -1
  49. package/dist/transport/backend-handler.d.ts +8 -0
  50. package/dist/transport/backend-handler.d.ts.map +1 -1
  51. package/dist/transport/backend-transport.d.ts.map +1 -1
  52. package/dist/transport/json-headers.d.ts +10 -0
  53. package/dist/transport/json-headers.d.ts.map +1 -0
  54. package/dist/transport/request-guard.d.ts +14 -0
  55. package/dist/transport/request-guard.d.ts.map +1 -0
  56. package/dist/types/events.d.ts +6 -13
  57. package/dist/types/events.d.ts.map +1 -1
  58. package/dist/types/index.d.ts +1 -1
  59. package/dist/types/index.d.ts.map +1 -1
  60. package/dist/types/models.d.ts +0 -34
  61. package/dist/types/models.d.ts.map +1 -1
  62. package/dist/types/segments.d.ts +0 -11
  63. package/dist/types/segments.d.ts.map +1 -1
  64. package/dist/utils/rendered-content.d.ts +3 -0
  65. package/dist/utils/rendered-content.d.ts.map +1 -0
  66. package/llms.txt +13 -0
  67. package/package.json +11 -4
  68. package/dist/defer-hydration-DQKULLmH.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-DQKULLmH.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-DQKULLmH.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
  }
@@ -3993,6 +4022,7 @@ class AparteChatViewport extends HTMLElement {
3993
4022
  populateBubbleFromMessage(bubble, stored);
3994
4023
  }
3995
4024
  }
4025
+ if (this._bulkAppend) return;
3996
4026
  this._pruneRenderedBubbles();
3997
4027
  this._syncBusy();
3998
4028
  if (message.role === "user") {
@@ -4195,13 +4225,6 @@ class AparteChatViewport extends HTMLElement {
4195
4225
  this._checkpointState?.clear();
4196
4226
  this.dispatchEvent(new CustomEvent("aparte-reset-done", { bubbles: true, composed: true }));
4197
4227
  }
4198
- /**
4199
- * Clear all messages
4200
- * @deprecated Use clearAll() to also remove DOM bubbles
4201
- */
4202
- clearMessages() {
4203
- this._repo.clear();
4204
- }
4205
4228
  /**
4206
4229
  * Replace the entire message list in one shot. Used when switching
4207
4230
  * conversations: clears existing repo + DOM, then appends each message.
@@ -4212,9 +4235,19 @@ class AparteChatViewport extends HTMLElement {
4212
4235
  */
4213
4236
  setMessages(messages) {
4214
4237
  this.clearAll({ revokeAttachments: false });
4215
- for (const m2 of messages) {
4216
- 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;
4217
4245
  }
4246
+ this._pruneRenderedBubbles();
4247
+ this._syncBusy();
4248
+ if (messages.some((m2) => m2.role === "user")) this._isAutoScrollEnabled = true;
4249
+ this._recalculateSpacer();
4250
+ this._autoScroll();
4218
4251
  }
4219
4252
  /**
4220
4253
  * Scroll to bottom of viewport
@@ -7182,6 +7215,7 @@ class AparteSuggestions extends HTMLElement {
7182
7215
  this._transcriptObserver?.disconnect();
7183
7216
  this._transcriptObserver = null;
7184
7217
  this._transcript = null;
7218
+ this._stopHolding();
7185
7219
  window.removeEventListener("aparte-config-change", this._onConfigChange);
7186
7220
  }
7187
7221
  attributeChangedCallback(name) {
@@ -7289,7 +7323,8 @@ class AparteSuggestions extends HTMLElement {
7289
7323
  const last = bubbles && bubbles.length ? bubbles[bubbles.length - 1] : null;
7290
7324
  const marks = last && last.getAttribute("data-role") !== "user" ? last.querySelectorAll("[data-aparte-suggestions]") : null;
7291
7325
  const mark = marks && marks.length ? marks[marks.length - 1] : null;
7292
- 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));
7293
7328
  }
7294
7329
  /** Show these replies; the same ones already shown redraw nothing (a transcript mutation is frequent). */
7295
7330
  _showAnswers(list) {
@@ -7331,6 +7366,40 @@ class AparteSuggestions extends HTMLElement {
7331
7366
  }
7332
7367
  this.appendChild(row);
7333
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
+ }
7334
7403
  _activate(suggestion) {
7335
7404
  const detail = { label: labelOf(suggestion), prompt: promptOf(suggestion) };
7336
7405
  const proceed = this.dispatchEvent(new CustomEvent("aparte-suggestion", {
@@ -7346,11 +7415,27 @@ class AparteSuggestions extends HTMLElement {
7346
7415
  return;
7347
7416
  }
7348
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;
7349
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();
7350
7426
  composer.setValue(detail.prompt);
7351
- if (this.getAttribute("mode") === "fill") composer.focus();
7427
+ if (fill) composer.focus();
7352
7428
  else {
7429
+ let sent = false;
7430
+ const sawSend = () => {
7431
+ sent = true;
7432
+ };
7433
+ composer.addEventListener("aparte-send", sawSend, { once: true });
7353
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);
7354
7439
  if (chipHadFocus) composer.focus();
7355
7440
  }
7356
7441
  }
@@ -7409,7 +7494,6 @@ class AparteContext extends HTMLElement {
7409
7494
  */
7410
7495
  _used = null;
7411
7496
  _level = null;
7412
- _compactRequested = false;
7413
7497
  /** The last turn's usage and the reply it belongs to, so the measure has it before the list has written it back. */
7414
7498
  _lastDone = null;
7415
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. */
@@ -7440,7 +7524,7 @@ class AparteContext extends HTMLElement {
7440
7524
  this._viewChanged = false;
7441
7525
  this._blank = false;
7442
7526
  this._overflow = false;
7443
- this._render(true);
7527
+ this._render();
7444
7528
  };
7445
7529
  /**
7446
7530
  * A conversation is replaced — a new chat, or one loaded in place of the last — and the
@@ -7503,7 +7587,6 @@ class AparteContext extends HTMLElement {
7503
7587
  _onCompacted = (e) => {
7504
7588
  const detail = e.detail;
7505
7589
  if (!this._isMine(detail?.targetId)) return;
7506
- this._compactRequested = false;
7507
7590
  this._compact = null;
7508
7591
  if (detail?.skipped) {
7509
7592
  this._render();
@@ -7514,11 +7597,9 @@ class AparteContext extends HTMLElement {
7514
7597
  if (!this._messages()) this._used = null;
7515
7598
  this._render();
7516
7599
  };
7517
- /** A failed compaction spends the request too; the next `danger` asks again. */
7518
7600
  _onCompactError = (e) => {
7519
7601
  const detail = e.detail;
7520
7602
  if (!this._isMine(detail?.targetId)) return;
7521
- this._compactRequested = false;
7522
7603
  this._compact = detail?.aborted ? null : "failed";
7523
7604
  this._failure = detail?.aborted ? "" : typeof detail?.error === "string" ? detail.error : "";
7524
7605
  this._render();
@@ -7680,7 +7761,7 @@ class AparteContext extends HTMLElement {
7680
7761
  if (this._used === null) return null;
7681
7762
  return { window: capacity, used: this._used, estimated: false, parts: { ...NO_PARTS }, other: this._used };
7682
7763
  }
7683
- _render(askToCompact = false) {
7764
+ _render() {
7684
7765
  const capacity = this._window();
7685
7766
  const measure = capacity === null ? null : this._measure(capacity);
7686
7767
  if (this._compact) this.setAttribute("data-compact", this._compact);
@@ -7767,13 +7848,6 @@ class AparteContext extends HTMLElement {
7767
7848
  const targetId = this._ownTargetId();
7768
7849
  const detail = { level, used, window: capacity, ratio, targetId };
7769
7850
  this.dispatchEvent(new CustomEvent("aparte-context-threshold", { detail, bubbles: true, composed: true }));
7770
- if (level !== "danger") this._compactRequested = false;
7771
- }
7772
- if (askToCompact && level === "danger" && this.hasAttribute("auto-compact") && !this._compactRequested) {
7773
- this._compactRequested = true;
7774
- window.dispatchEvent(new CustomEvent("aparte-compact", {
7775
- detail: { targetId: this._ownTargetId(), auto: true, window: capacity }
7776
- }));
7777
7851
  }
7778
7852
  }
7779
7853
  // ─────────────────────────────────────────────────────────────────────────
@@ -7982,6 +8056,7 @@ const MIN_PITCH = 6;
7982
8056
  const SETTLE_MS = 150;
7983
8057
  const MAX_ALIGN_PASSES = 4;
7984
8058
  const ALIGN_TOLERANCE = 1;
8059
+ const BAND_PERCENT = 30;
7985
8060
  class AparteScrollRail extends HTMLElement {
7986
8061
  static get observedAttributes() {
7987
8062
  return ["target", "every"];
@@ -7989,18 +8064,39 @@ class AparteScrollRail extends HTMLElement {
7989
8064
  _host = null;
7990
8065
  _mutations = null;
7991
8066
  _resizes = null;
8067
+ /** The boxes the resize observer watches: the host, the transcript and its scroll surface. */
8068
+ _sized = [];
7992
8069
  _intersections = null;
7993
8070
  /** The bubbles the intersection observer watches — compared by identity, so a re-rendered bubble is re-observed. */
7994
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 = [];
7995
8077
  /** The scroll surface the observer is rooted on, and whose bottom edge is read. */
7996
8078
  _observedSurface = null;
7997
- _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();
7998
8090
  _pickQueued = false;
7999
8091
  _currentId = null;
8000
- /** Visible ratio per message id in the reading band, from the intersection observer. */
8001
- _visible = /* @__PURE__ */ new Map();
8002
- /** The bubbles on screen at all, from the second observer; only the last one is read. */
8003
- _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();
8004
8100
  _onScreenObserver = null;
8005
8101
  /** The mark a jump asked for, held until the transcript has stopped moving. */
8006
8102
  _held = null;
@@ -8021,6 +8117,8 @@ class AparteScrollRail extends HTMLElement {
8021
8117
  if (!this.getAttribute("role")) this.setAttribute("role", "navigation");
8022
8118
  this.addEventListener("click", this._onClick);
8023
8119
  this.addEventListener("keydown", this._onKeydown);
8120
+ this.addEventListener("focusin", this._onFocusIn);
8121
+ this.addEventListener("focusout", this._onFocusOut);
8024
8122
  window.addEventListener("aparte-config-change", this._onConfigChange);
8025
8123
  this._attach();
8026
8124
  }
@@ -8028,6 +8126,8 @@ class AparteScrollRail extends HTMLElement {
8028
8126
  this._detach();
8029
8127
  this.removeEventListener("click", this._onClick);
8030
8128
  this.removeEventListener("keydown", this._onKeydown);
8129
+ this.removeEventListener("focusin", this._onFocusIn);
8130
+ this.removeEventListener("focusout", this._onFocusOut);
8031
8131
  window.removeEventListener("aparte-config-change", this._onConfigChange);
8032
8132
  }
8033
8133
  attributeChangedCallback(name) {
@@ -8056,16 +8156,37 @@ class AparteScrollRail extends HTMLElement {
8056
8156
  }
8057
8157
  if (typeof MutationObserver !== "undefined") {
8058
8158
  this._mutations = new MutationObserver((records) => {
8059
- 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"]
8060
8187
  });
8061
- this._mutations.observe(this._host, { childList: true, subtree: true, characterData: true });
8062
- }
8063
- if (typeof ResizeObserver !== "undefined") {
8064
- this._resizes = new ResizeObserver(() => this._layout());
8065
- this._resizes.observe(this._host);
8066
- const viewport = this._viewport();
8067
- if (viewport) this._resizes.observe(viewport);
8068
8188
  }
8189
+ if (typeof ResizeObserver !== "undefined") this._resizes = new ResizeObserver(() => this._layout());
8069
8190
  this._rebuild();
8070
8191
  }
8071
8192
  _detach() {
@@ -8073,19 +8194,56 @@ class AparteScrollRail extends HTMLElement {
8073
8194
  this._mutations = null;
8074
8195
  this._resizes?.disconnect();
8075
8196
  this._resizes = null;
8197
+ this._sized = [];
8198
+ this._relabel.clear();
8199
+ this._rebuildWanted = false;
8076
8200
  this._unobserve();
8077
8201
  this._release();
8078
8202
  this._host = null;
8079
8203
  }
8080
- /** 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. */
8081
8205
  _queueRebuild() {
8082
- if (this._rebuildQueued) return;
8083
- 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;
8084
8216
  requestAnimationFrame(() => {
8085
- this._rebuildQueued = false;
8086
- 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);
8087
8227
  });
8088
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
+ }
8089
8247
  _viewport() {
8090
8248
  return this._host?.querySelector("aparte-chat-viewport") ?? null;
8091
8249
  }
@@ -8095,22 +8253,31 @@ class AparteScrollRail extends HTMLElement {
8095
8253
  if (!viewport) return null;
8096
8254
  return viewport.querySelector(".aparte-viewport-container") ?? viewport;
8097
8255
  }
8098
- _bubbles() {
8256
+ /** Every message bubble of the transcript, in document order. */
8257
+ _messages() {
8099
8258
  const viewport = this._viewport();
8100
- 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()) {
8101
8263
  const every = this.getAttribute("every") === "message" ? "message" : "user";
8102
- const all = Array.from(viewport.querySelectorAll("aparte-chat-bubble[message-id]"));
8103
8264
  return every === "message" ? all : all.filter((b2) => b2.getAttribute("data-role") === "user");
8104
8265
  }
8105
8266
  // ─── Rendering ────────────────────────────────────────────────────────
8106
8267
  /** The first words of a message, for the tick's name. An excerpt, never a summary. */
8107
8268
  _excerpt(bubble) {
8269
+ const known = this._excerpts.get(bubble);
8270
+ if (known !== void 0) return known;
8108
8271
  const body = bubble.querySelector(".aparte-message-content") ?? bubble;
8109
- const text = (body.textContent ?? "").replace(/\s+/g, " ").trim();
8110
- return text.length > EXCERPT_LENGTH ? `${text.slice(0, EXCERPT_LENGTH - 1).trimEnd()}…` : text;
8111
- }
8112
- _tickLabel(bubble) {
8113
- 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) {
8114
8281
  const role = bubble.getAttribute("data-role") === "user" ? locale.roleNameUser ?? "You" : locale.roleNameAssistant ?? "Assistant";
8115
8282
  const excerpt = this._excerpt(bubble);
8116
8283
  return excerpt ? `${role}: ${excerpt}` : role;
@@ -8125,7 +8292,9 @@ class AparteScrollRail extends HTMLElement {
8125
8292
  * and dropped when its bubble left.
8126
8293
  */
8127
8294
  _rebuild() {
8128
- const bubbles = this._bubbles();
8295
+ this._watchSizes();
8296
+ const all = this._messages();
8297
+ const bubbles = this._bubbles(all);
8129
8298
  const locale = resolveConfig(this).getLocale();
8130
8299
  const railLabel = locale.scrollRailLabel ?? "Conversation outline";
8131
8300
  if (this.getAttribute("aria-label") !== railLabel) this.setAttribute("aria-label", railLabel);
@@ -8135,6 +8304,7 @@ class AparteScrollRail extends HTMLElement {
8135
8304
  this._unobserve();
8136
8305
  this._currentId = null;
8137
8306
  this._write("--aparte-scroll-rail-hit-size", "");
8307
+ this._write("--aparte-scroll-rail-gap", "");
8138
8308
  return;
8139
8309
  }
8140
8310
  this.removeAttribute("data-empty");
@@ -8149,24 +8319,27 @@ class AparteScrollRail extends HTMLElement {
8149
8319
  const id = item.firstElementChild instanceof HTMLElement ? item.firstElementChild.dataset["messageId"] : void 0;
8150
8320
  if (id) existing.set(id, item);
8151
8321
  }
8152
- const known = /* @__PURE__ */ new Set();
8153
- 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;
8154
8329
  for (const bubble of bubbles) {
8155
8330
  const id = bubble.getAttribute("message-id");
8156
- known.add(id);
8157
8331
  let item = existing.get(id);
8158
- if (item) {
8159
- existing.delete(id);
8160
- } else {
8332
+ if (!item) {
8161
8333
  item = document.createElement("li");
8162
8334
  const tick2 = document.createElement("button");
8163
8335
  tick2.type = "button";
8164
8336
  tick2.className = "aparte-scroll-rail__tick";
8165
8337
  tick2.dataset["messageId"] = id;
8338
+ tick2.tabIndex = -1;
8166
8339
  item.appendChild(tick2);
8167
8340
  }
8168
8341
  const tick = item.firstElementChild;
8169
- const label = this._tickLabel(bubble);
8342
+ const label = this._tickLabel(bubble, locale);
8170
8343
  if (tick.getAttribute("aria-label") !== label) {
8171
8344
  tick.setAttribute("aria-label", label);
8172
8345
  tick.title = label;
@@ -8176,14 +8349,15 @@ class AparteScrollRail extends HTMLElement {
8176
8349
  } else {
8177
8350
  tick.removeAttribute("aria-current");
8178
8351
  }
8179
- const at = list.children[index] ?? null;
8180
- if (at !== item) list.insertBefore(item, at);
8181
- index++;
8352
+ if (item === at) at = at.nextElementSibling;
8353
+ else list.insertBefore(item, at);
8182
8354
  }
8183
- for (const stale of existing.values()) stale.remove();
8184
- if (this._currentId && !known.has(this._currentId)) this._currentId = null;
8185
- 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);
8186
8359
  this._layout();
8360
+ if (dropped) this._pickCurrent();
8187
8361
  }
8188
8362
  /**
8189
8363
  * Which tick is current is read, not computed: the scroll surface is the root and an
@@ -8195,35 +8369,50 @@ class AparteScrollRail extends HTMLElement {
8195
8369
  * position read is the bottom, because there the reader is under the latest question
8196
8370
  * whatever the band holds, and the observer has nothing to report on the last few
8197
8371
  * pixels.
8198
- */
8199
- _observe(bubbles) {
8200
- this._unobserve();
8201
- this._observedBubbles = bubbles;
8202
- if (typeof IntersectionObserver === "undefined") return;
8203
- const root = this._scrollSurface();
8204
- if (!root) return;
8205
- this._intersections = new IntersectionObserver((entries) => {
8206
- for (const entry of entries) {
8207
- const id = entry.target.getAttribute("message-id");
8208
- if (id) this._visible.set(id, entry.isIntersecting ? entry.intersectionRatio : 0);
8209
- }
8210
- this._pickCurrent();
8211
- }, { root, rootMargin: "0px 0px -70% 0px", threshold: [0, 0.1, 0.25, 0.5, 0.75, 1] });
8212
- this._onScreenObserver = new IntersectionObserver((entries) => {
8213
- for (const entry of entries) {
8214
- const id = entry.target.getAttribute("message-id");
8215
- if (!id) continue;
8216
- if (entry.isIntersecting) this._onScreen.add(id);
8217
- else this._onScreen.delete(id);
8218
- }
8219
- this._pickCurrent();
8220
- }, { root, threshold: [0] });
8221
- for (const bubble of bubbles) {
8222
- this._intersections.observe(bubble);
8223
- 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;
8224
8387
  }
8225
- this._observedSurface = root;
8226
- root.addEventListener("scroll", this._onRootScroll, { passive: true });
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);
8413
+ }
8414
+ this._observedBubbles = bubbles;
8415
+ this._bandTargets = all;
8227
8416
  }
8228
8417
  _unobserve() {
8229
8418
  this._intersections?.disconnect();
@@ -8233,8 +8422,9 @@ class AparteScrollRail extends HTMLElement {
8233
8422
  this._observedSurface?.removeEventListener("scroll", this._onRootScroll);
8234
8423
  this._observedSurface = null;
8235
8424
  this._observedBubbles = [];
8236
- this._visible.clear();
8237
- this._onScreen.clear();
8425
+ this._bandTargets = [];
8426
+ this._visible = /* @__PURE__ */ new WeakMap();
8427
+ this._onScreen = /* @__PURE__ */ new WeakSet();
8238
8428
  }
8239
8429
  /** A scroll only matters at the bottom edge, where the observer is silent: one pick per frame. */
8240
8430
  _onRootScroll = () => {
@@ -8256,18 +8446,65 @@ class AparteScrollRail extends HTMLElement {
8256
8446
  if (this._held) return;
8257
8447
  const bubbles = this._observedBubbles;
8258
8448
  if (bubbles.length === 0) return;
8259
- const lastId = bubbles[bubbles.length - 1].getAttribute("message-id");
8260
- 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)) {
8261
8452
  this._setCurrent(lastId);
8262
8453
  return;
8263
8454
  }
8264
8455
  let last = null;
8265
- for (const bubble of bubbles) {
8266
- const id = bubble.getAttribute("message-id");
8267
- 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
+ }
8268
8464
  }
8465
+ if (last === null && seen) return;
8466
+ last ??= this._lastAbove();
8269
8467
  if (last !== null) this._setCurrent(last);
8270
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
+ }
8271
8508
  _setCurrent(id) {
8272
8509
  if (this._currentId === id) return;
8273
8510
  this._currentId = id;
@@ -8279,6 +8516,40 @@ class AparteScrollRail extends HTMLElement {
8279
8516
  tick.removeAttribute("aria-current");
8280
8517
  }
8281
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
+ }
8282
8553
  }
8283
8554
  /** Past the floor the rail scrolls itself: the current tick is kept inside its window. */
8284
8555
  _reveal(tick) {
@@ -8290,6 +8561,22 @@ class AparteScrollRail extends HTMLElement {
8290
8561
  else if (bottom > this.scrollTop + room) this.scrollTop = bottom - room;
8291
8562
  }
8292
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
+ }
8293
8580
  /** Write a custom property on this element only when its value changed; '' removes it. */
8294
8581
  _write(name, value) {
8295
8582
  if (this._written.get(name) === value) return;
@@ -8324,18 +8611,18 @@ class AparteScrollRail extends HTMLElement {
8324
8611
  this._write("--aparte-scroll-rail-block-end", `${Math.max(0, Math.round(h2.bottom - v2.bottom))}px`);
8325
8612
  }
8326
8613
  }
8327
- const count = this._list()?.children.length ?? 0;
8328
- const height = this.clientHeight;
8329
- if (!count || !height) {
8330
- this._write("--aparte-scroll-rail-hit-size", "");
8331
- this._write("--aparte-scroll-rail-gap", "");
8332
- return;
8333
- }
8334
8614
  const above = host ?? document.documentElement;
8335
8615
  const aboveStyle = getComputedStyle(above);
8336
8616
  const hit = parseFloat(aboveStyle.getPropertyValue("--aparte-scroll-rail-hit-size")) || 24;
8337
8617
  const thickness = parseFloat(aboveStyle.getPropertyValue("--aparte-scroll-rail-tick-thickness")) || 2;
8338
- 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) {
8339
8626
  this._write("--aparte-scroll-rail-hit-size", "");
8340
8627
  this._write("--aparte-scroll-rail-gap", "");
8341
8628
  return;
@@ -8360,7 +8647,10 @@ class AparteScrollRail extends HTMLElement {
8360
8647
  if (index === -1) return;
8361
8648
  e.preventDefault();
8362
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);
8363
- ticks[next]?.focus();
8650
+ const target = ticks[next];
8651
+ if (!target) return;
8652
+ this._setTabStop(target, ticks);
8653
+ target.focus();
8364
8654
  };
8365
8655
  /**
8366
8656
  * Scroll the transcript to a message. Announced first, cancelable; then a
@@ -8387,7 +8677,7 @@ class AparteScrollRail extends HTMLElement {
8387
8677
  if (!bubble) return;
8388
8678
  this._viewport()?.setAutoScroll?.(false);
8389
8679
  this._scrollTo(bubble);
8390
- this._setCurrent(messageId);
8680
+ this._setCurrent(this._markFor(bubble));
8391
8681
  this._hold(messageId);
8392
8682
  }
8393
8683
  _bubbleOf(messageId) {
@@ -8426,7 +8716,7 @@ class AparteScrollRail extends HTMLElement {
8426
8716
  }
8427
8717
  }
8428
8718
  this._release();
8429
- if (id) this._setCurrent(id);
8719
+ if (id) this._setCurrent(bubble ? this._markFor(bubble) : id);
8430
8720
  }
8431
8721
  _release() {
8432
8722
  if (this._settleTimer !== null) clearTimeout(this._settleTimer);
@@ -8436,6 +8726,12 @@ class AparteScrollRail extends HTMLElement {
8436
8726
  this._held = null;
8437
8727
  }
8438
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
+ }
8439
8735
  function sameElements(a4, b2) {
8440
8736
  if (a4.length !== b2.length) return false;
8441
8737
  for (let i2 = 0; i2 < a4.length; i2++) if (a4[i2] !== b2[i2]) return false;
@@ -8631,7 +8927,7 @@ class AparteSidebar extends HTMLElement {
8631
8927
  const root = rootOf(this);
8632
8928
  const controls = root === document ? Array.from(document.querySelectorAll(selector)) : [...root.querySelectorAll(selector), ...document.querySelectorAll(selector)];
8633
8929
  for (const control of controls) {
8634
- if (!this._drives(control)) continue;
8930
+ if (inRenderedContent(control) || !this._drives(control)) continue;
8635
8931
  control.setAttribute("aria-expanded", String(!this.collapsed));
8636
8932
  control.setAttribute("aria-controls", this.id);
8637
8933
  }
@@ -8719,7 +9015,7 @@ class AparteSidebar extends HTMLElement {
8719
9015
  /** A `[data-aparte-sidebar-toggle]` anywhere toggles this sidebar — no script in the host. */
8720
9016
  _onDocumentClick = (e) => {
8721
9017
  const control = eventOrigin(e)?.closest?.("[data-aparte-sidebar-toggle]");
8722
- if (!control) return;
9018
+ if (!control || inRenderedContent(control)) return;
8723
9019
  if (!this._drives(control)) return;
8724
9020
  this.toggle(control);
8725
9021
  };
@@ -9520,7 +9816,7 @@ class AparteSplit extends HTMLElement {
9520
9816
  */
9521
9817
  _onDocumentClick = (e) => {
9522
9818
  const control = eventOrigin(e)?.closest?.("[data-aparte-split-pane]");
9523
- if (!control) return;
9819
+ if (!control || inRenderedContent(control)) return;
9524
9820
  const value = (control.getAttribute("data-aparte-split-pane") ?? "").trim();
9525
9821
  const which = value === "start" || value === "end" ? value : null;
9526
9822
  const named = which ? "" : value;
@@ -9547,6 +9843,7 @@ class AparteSplit extends HTMLElement {
9547
9843
  const which = (control.getAttribute("data-aparte-split-pane") ?? "").trim();
9548
9844
  if (which !== "start" && which !== "end") continue;
9549
9845
  if (control.localName !== "button" && control.getAttribute("role") !== "button") continue;
9846
+ if (inRenderedContent(control)) continue;
9550
9847
  const target = control.closest("aparte-split") ?? rootOf(control).querySelector("aparte-split") ?? document.querySelector("aparte-split");
9551
9848
  if (target !== this) continue;
9552
9849
  if (this.stacked) control.setAttribute("aria-pressed", String(which === this.pane));
@@ -9713,7 +10010,8 @@ class AparteLauncher extends HTMLElement {
9713
10010
  * in another language. Resolved live, never kept: the boundary may arrive after connect.
9714
10011
  */
9715
10012
  _config() {
9716
- 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);
9717
10015
  }
9718
10016
  /**
9719
10017
  * The button is a child of the element, whatever was done to the children since: put
@@ -9795,14 +10093,14 @@ class AparteLauncher extends HTMLElement {
9795
10093
  * person just pressed.
9796
10094
  */
9797
10095
  _focusChat() {
9798
- 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);
9799
10097
  const target = composer ?? this._focusables().find((el2) => el2 !== this._button);
9800
10098
  target?.focus();
9801
10099
  }
9802
10100
  /** A `[data-aparte-launcher-close]` inside closes the chat — no script in your card. */
9803
10101
  _onClick = (e) => {
9804
10102
  const control = eventOrigin(e)?.closest?.("[data-aparte-launcher-close]");
9805
- if (control && this.contains(control)) this.close();
10103
+ if (control && this.contains(control) && !inRenderedContent(control)) this.close();
9806
10104
  };
9807
10105
  /**
9808
10106
  * A modal dialog open inside the card, with the key pressed inside it. The browser
@@ -9847,6 +10145,45 @@ deferHydrationOf(AparteLauncher);
9847
10145
  if (!customElements.get("aparte-launcher")) {
9848
10146
  customElements.define("aparte-launcher", AparteLauncher);
9849
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
+ }
9850
10187
  const APARTE_ELEMENTS = [
9851
10188
  // Chat shell + transcript
9852
10189
  ["aparte-chat", AparteChat],
@@ -9886,7 +10223,10 @@ function registerAllComponents() {
9886
10223
  );
9887
10224
  }
9888
10225
  }
9889
- if (typeof document !== "undefined") installDialogTriggersOnce();
10226
+ if (typeof document !== "undefined") {
10227
+ installDialogTriggersOnce();
10228
+ installImageHoldsOnce();
10229
+ }
9890
10230
  export {
9891
10231
  A as APARTE_CONFIG_CHANGE,
9892
10232
  a as APARTE_CONVERSATION_SCHEMA_VERSION,