@aparte/n8n-chat 0.2.0 → 0.3.1

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 (69) hide show
  1. package/README.md +161 -18
  2. package/dist/cards.d.ts +25 -1
  3. package/dist/cdn/chunks/{chunk-CZ5742JA.js → chunk-37ODPEBD.js} +1 -1
  4. package/dist/cdn/chunks/{chunk-CZ5742JA.js.map → chunk-37ODPEBD.js.map} +1 -1
  5. package/dist/cdn/chunks/{chunk-7JR7KL6J.js → chunk-DEOOTEDD.js} +2 -2
  6. package/dist/cdn/chunks/{chunk-7JR7KL6J.js.map → chunk-DEOOTEDD.js.map} +1 -1
  7. package/dist/cdn/chunks/{chunk-VTTH7HGO.js → chunk-NKYV5B7Q.js} +2 -2
  8. package/dist/cdn/chunks/{chunk-VTTH7HGO.js.map → chunk-NKYV5B7Q.js.map} +3 -3
  9. package/dist/cdn/chunks/{chunk-OJFRNS5M.js → chunk-RDVTD2YO.js} +2 -2
  10. package/dist/cdn/chunks/{chunk-OJFRNS5M.js.map → chunk-RDVTD2YO.js.map} +1 -1
  11. package/dist/cdn/chunks/{chunk-IPWLCOPM.js → chunk-U6354LAY.js} +2 -2
  12. package/dist/cdn/chunks/{chunk-IPWLCOPM.js.map → chunk-U6354LAY.js.map} +1 -1
  13. package/dist/cdn/chunks/{chunk-IWAJFJNA.js → chunk-ZNUFBTZ7.js} +8 -5
  14. package/dist/cdn/chunks/chunk-ZNUFBTZ7.js.map +7 -0
  15. package/dist/cdn/chunks/{de-JS3CQEVR.js → de-BCWJVDW5.js} +1 -1
  16. package/dist/cdn/chunks/{de-JS3CQEVR.js.map → de-BCWJVDW5.js.map} +1 -1
  17. package/dist/cdn/chunks/{es-OHKGLFEF.js → es-72JNODLG.js} +1 -1
  18. package/dist/cdn/chunks/{es-OHKGLFEF.js.map → es-72JNODLG.js.map} +1 -1
  19. package/dist/cdn/chunks/{fr-6S44XMU5.js → fr-ZKACSOY5.js} +1 -1
  20. package/dist/cdn/chunks/{fr-6S44XMU5.js.map → fr-ZKACSOY5.js.map} +1 -1
  21. package/dist/cdn/chunks/{highlight-FGIKUPIF.js → highlight-DG2OVLBT.js} +2 -2
  22. package/dist/cdn/chunks/{highlight-FGIKUPIF.js.map → highlight-DG2OVLBT.js.map} +1 -1
  23. package/dist/cdn/chunks/{it-K4WYXXDJ.js → it-SSBBMSGX.js} +1 -1
  24. package/dist/cdn/chunks/{it-K4WYXXDJ.js.map → it-SSBBMSGX.js.map} +1 -1
  25. package/dist/cdn/chunks/{items-S4LF2DJA.js → items-MITCIPF3.js} +3 -3
  26. package/dist/cdn/chunks/{items-S4LF2DJA.js.map → items-MITCIPF3.js.map} +1 -1
  27. package/dist/cdn/chunks/{ja-BN7TZW62.js → ja-NCV4Z63H.js} +1 -1
  28. package/dist/cdn/chunks/{ja-BN7TZW62.js.map → ja-NCV4Z63H.js.map} +1 -1
  29. package/dist/cdn/chunks/{ko-ARHO7UI3.js → ko-VCNS24WV.js} +1 -1
  30. package/dist/cdn/chunks/{ko-ARHO7UI3.js.map → ko-VCNS24WV.js.map} +1 -1
  31. package/dist/cdn/chunks/{link-C46K5O7X.js → link-7JYKZK3A.js} +2 -2
  32. package/dist/cdn/chunks/{link-C46K5O7X.js.map → link-7JYKZK3A.js.map} +1 -1
  33. package/dist/cdn/chunks/{media-QI5BPERX.js → media-7CZBXNEK.js} +2 -2
  34. package/dist/cdn/chunks/{media-QI5BPERX.js.map → media-7CZBXNEK.js.map} +1 -1
  35. package/dist/cdn/chunks/{order-YISYH73K.js → order-CPY2L7MI.js} +2 -2
  36. package/dist/cdn/chunks/{order-YISYH73K.js.map → order-CPY2L7MI.js.map} +1 -1
  37. package/dist/cdn/chunks/{place-UFCH3NQE.js → place-KQ3IA5IV.js} +43 -4
  38. package/dist/cdn/chunks/place-KQ3IA5IV.js.map +7 -0
  39. package/dist/cdn/chunks/{plan-KQWF73QI.js → plan-OKXEPKPV.js} +2 -2
  40. package/dist/cdn/chunks/{plan-KQWF73QI.js.map → plan-OKXEPKPV.js.map} +1 -1
  41. package/dist/cdn/chunks/{product-7UBLOMZ7.js → product-ONQRJRDO.js} +24 -4
  42. package/dist/cdn/chunks/product-ONQRJRDO.js.map +7 -0
  43. package/dist/cdn/chunks/{pt-BR-R7ZRM3GG.js → pt-BR-73MNA3YX.js} +1 -1
  44. package/dist/cdn/chunks/{pt-BR-R7ZRM3GG.js.map → pt-BR-73MNA3YX.js.map} +1 -1
  45. package/dist/cdn/chunks/{ru-FJNIMGMU.js → ru-SCEGVTR4.js} +1 -1
  46. package/dist/cdn/chunks/{ru-FJNIMGMU.js.map → ru-SCEGVTR4.js.map} +1 -1
  47. package/dist/cdn/chunks/{score-O2KEAYDS.js → score-QF27XJUE.js} +2 -2
  48. package/dist/cdn/chunks/{score-O2KEAYDS.js.map → score-QF27XJUE.js.map} +1 -1
  49. package/dist/cdn/chunks/{stats-GSXFRGYZ.js → stats-2W3GFI4P.js} +2 -2
  50. package/dist/cdn/chunks/{stats-GSXFRGYZ.js.map → stats-2W3GFI4P.js.map} +1 -1
  51. package/dist/cdn/chunks/{stock-53NVFLC3.js → stock-RCVJOOH4.js} +2 -2
  52. package/dist/cdn/chunks/{stock-53NVFLC3.js.map → stock-RCVJOOH4.js.map} +1 -1
  53. package/dist/cdn/chunks/{weather-VI2RCU4X.js → weather-NQGN2JOS.js} +2 -2
  54. package/dist/cdn/chunks/{weather-VI2RCU4X.js.map → weather-NQGN2JOS.js.map} +1 -1
  55. package/dist/cdn/chunks/{zh-CN-DUCWBXJP.js → zh-CN-4K6QPBRT.js} +1 -1
  56. package/dist/cdn/chunks/{zh-CN-DUCWBXJP.js.map → zh-CN-4K6QPBRT.js.map} +1 -1
  57. package/dist/cdn/n8n-chat.js +57 -57
  58. package/dist/cdn/n8n-chat.js.map +4 -4
  59. package/dist/create-chat.d.ts +39 -6
  60. package/dist/index.d.ts +3 -0
  61. package/dist/index.js +74 -42
  62. package/dist/index.js.map +1 -1
  63. package/dist/strings.d.ts +1 -1
  64. package/dist/style.css +383 -370
  65. package/dist/theme.css +381 -368
  66. package/package.json +7 -7
  67. package/dist/cdn/chunks/chunk-IWAJFJNA.js.map +0 -7
  68. package/dist/cdn/chunks/place-UFCH3NQE.js.map +0 -7
  69. package/dist/cdn/chunks/product-7UBLOMZ7.js.map +0 -7
@@ -135,7 +135,7 @@ ${c}
135
135
  </div>
136
136
  </div>
137
137
  </div>
138
- `,this.querySelector(".aparte-status-container")?.setAttribute("aria-label",t),this._writeText(this.getAttribute("text"))}_writeText(t){let e=t||null,s=this.querySelector(".aparte-status-text");s&&(s.textContent=e??""),this._syncLiveWord()}_syncLiveWord(){let t=this.querySelector(".aparte-status-sr");if(!t)return;let e=!this.getAttribute("text");t.textContent=e&&this.hasAttribute("visible")?this._word():""}_updateVisibility(t){let e=this.querySelector(".aparte-status-container");e&&e.setAttribute("data-visible",String(t)),this._syncLiveWord()}_updateText(t){let e=this.querySelector(".aparte-status-container");if(!e)return;let s=this._cfg?.getStatusRenderer?.();if(s){let i=t||this._word();e.setAttribute("aria-label",i);let r=j(this._cfg,()=>s(i));r instanceof HTMLElement?e.replaceChildren(r):e.innerHTML=r;return}this._writeText(t),e.setAttribute("aria-label",t||this._word())}};$(Be);customElements.get("aparte-chat-status")||customElements.define("aparte-chat-status",Be);function Gr(n,t){if(n.role!=="assistant"||n.segments?.length||typeof n.content!="string"||!n.content.trim())return n;let e=Ai(n.content,{blocks:t});return e.length<=1&&e.every(i=>i.type==="text")?n:pn({...n,segments:e})}function pn(n){return Object.defineProperty(n,en,{value:!0,enumerable:!1}),n}function zr(n){return n[en]===!0}var He=class extends HTMLElement{_container=null;_scrollBtn=null;_bottomSpacer=null;_fwSpacerHeight=0;_spacerRafId=null;_spacerFrozenUntil=0;_layoutTransitionMs=0;_repo=new be;_isAutoScrollEnabled=!0;_lastScrollTop=0;_lastScrollHeight=0;_lastMutationAt=Number.NEGATIVE_INFINITY;_settleShadowMs=100;_settleBoundPx=100;_ownScrollAt=Number.NEGATIVE_INFINITY;_readerInputAt=Number.NEGATIVE_INFINITY;_ownScrollWindowMs=1e3;_settleWindowMs=400;_glideUntil=0;_glideWindowMs=450;_glideSettleTimer=null;_settleUntil=0;_settleRafId=null;_scrollKeys=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]);_scrollThreshold=50;_smoothScrollOnce=!1;_maxRenderedBubbles=1e3;_resizeObserver=null;_mutationObserver=null;_tailObserver=null;_tail=[];_tailHeights=new WeakMap;_onDisclosureToggle=()=>{this._scheduleSpacerUpdate()};_overlayRoot=null;_overlayObserver=null;_overlayInset=-1;_transcriptInset=-1;_boundResetHandler=null;_checkpointState=null;_stopCheckpointState=null;_frameworkManagedDOM=!1;static get observedAttributes(){return["scroll-threshold","max-rendered-bubbles","loading"]}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",K(t))}setLoading(t){this.loading=t}_syncLoading(){let t=this._container;if(!t)return;let e=this.hasAttribute("loading");if(t.setAttribute("aria-busy",e?"true":"false"),this._frameworkManagedDOM)return;let s=t.querySelector(":scope > .aparte-viewport-loading");if(!e){s?.remove(),t.querySelector(":scope > .aparte-viewport-loading-status")?.remove();return}if(s)return;let i=k(this),r=document.createElement("div");r.className="aparte-viewport-loading",r.setAttribute("aria-hidden","true"),r.innerHTML='<span class="aparte-skeleton aparte-skeleton--rect aparte-viewport-loading__user"></span><span class="aparte-skeleton aparte-skeleton--text"></span><span class="aparte-skeleton aparte-skeleton--text"></span><span class="aparte-skeleton aparte-skeleton--text"></span><span class="aparte-skeleton aparte-skeleton--text aparte-viewport-loading__last"></span>';let a=document.createElement("span");a.className="aparte-viewport-loading-status aparte-sr-only",a.setAttribute("role","status"),t.prepend(r,a);let o=()=>{a.isConnected&&(a.textContent=i.t("loadingConversation"))};typeof requestAnimationFrame=="function"?requestAnimationFrame(o):o()}constructor(){super(),this._handleScroll=this._handleScroll.bind(this),this._handleScrollEnd=this._handleScrollEnd.bind(this)}connectedCallback(){this.hasAttribute("framework-managed")&&(this._frameworkManagedDOM=!0),this._render(),this._setupEventListeners(),this._setupObservers(),this._updateTranscriptInset(),this._boundResetHandler=()=>this.clearAll(),window.addEventListener("aparte-reset",this._boundResetHandler),window.addEventListener("aparte-config-change",this._onConfigChange),this._checkpointState??=new ge({ownId:()=>kr(this)??(this.id||void 0),bubbleOf:t=>this.querySelector(`aparte-chat-bubble[message-id="${z(t)}"]`),owns:t=>!!this.getMessage(t),active:()=>!this._frameworkManagedDOM}),this._stopCheckpointState??=this._checkpointState.start()}_onConfigChange=t=>{let e=t.detail;if(e?.config&&e.config!==k(this))return;this._applyDirection(),this._scrollBtn?.setAttribute("aria-label",k(this).t("scrollToBottom")),(this._frameworkManagedDOM?this:this.querySelector(".aparte-viewport-container"))?.setAttribute("aria-label",k(this).t("transcript"))};_nameScrollSurface(t){t.setAttribute("tabindex","0"),t.hasAttribute("role")||t.setAttribute("role","log"),t.setAttribute("aria-label",k(this).t("transcript"))}_applyDirection(){let t=this.querySelector(".aparte-viewport-container");if(!t)return;let e=k(this).getLocale().direction;e?t.setAttribute("dir",e):t.removeAttribute("dir")}disconnectedCallback(){window.removeEventListener("aparte-config-change",this._onConfigChange),this._boundResetHandler&&(window.removeEventListener("aparte-reset",this._boundResetHandler),this._boundResetHandler=null),this._stopCheckpointState?.(),this._stopCheckpointState=null,this._cleanup()}attributeChangedCallback(t,e,s){if(e!==s)switch(t){case"scroll-threshold":this._scrollThreshold=parseInt(s||"50",10);break;case"max-rendered-bubbles":this._maxRenderedBubbles=parseInt(s||"1000",10),this._pruneRenderedBubbles();break;case"loading":this._syncLoading();break}}configure(t){t.scrollThreshold!==void 0&&(this._scrollThreshold=t.scrollThreshold),t.maxRenderedBubbles!==void 0&&(this._maxRenderedBubbles=t.maxRenderedBubbles,this._pruneRenderedBubbles()),t.layoutTransitionMs!==void 0&&(this._layoutTransitionMs=t.layoutTransitionMs)}appendToken(t,e){let s=this._getOrCreateMessage(t);s.content=(s.content||"")+e,this._notifyBubble(t,"appendToken",e),this._autoScroll(),this._scheduleSpacerUpdate()}appendToSegment(t,e,s){let i=this._getOrCreateMessage(t);i.segments||(i.segments=[]);let r=i.segments.findIndex(o=>o.id===e),a=r===-1?void 0:i.segments[r];a&&"content"in a&&(i.segments[r]={...a,content:a.content+s,...ki(a)}),this.dispatchEvent(new CustomEvent("aparte-segment-update",{bubbles:!0,composed:!0,detail:{messageId:t,segmentId:e,content:s,append:!0}})),this._notifyBubble(t,"appendToSegment",s,e),this._autoScroll()}_activeMessageId(){let t=this._repo.headId,e=this._streamingMessageId();return e!==null&&e!==t?null:t}_streamingMessageId(){let t=this._repo.headId,e=null;for(let s of this._repo.getAllMessages())if(s.isStreaming){if(s.id!==t)return s.id;e=s.id}return e}_syncBusy(){this._frameworkManagedDOM||this.setTranscriptBusy(this._streamingMessageId()!==null)}_busy=!1;setTranscriptBusy(t){this._busy=t,this.toggleAttribute("data-busy",t);for(let e of this.querySelectorAll("aparte-chat-bubble"))e.setTranscriptBusy?.(t)}addSegment(t,e){let s=typeof t=="string"?t:this._activeMessageId(),i=typeof t=="string"?e:t;if(!s||!i)return;let r=this._getOrCreateMessage(s);r.segments||(r.segments=[]);let a=Hs(r.segments,i,s,k(this).getSegmentDefaults(i.type));r.segments.push(a),this._notifyBubble(s,"addSegment",a),this._autoScroll()}updateSegment(t,e,s){let i=s===void 0&&typeof e=="object",r=i?this._activeMessageId():t,a=i?t:e,o=i?e:s;if(!r)return;let l=this._repo.getMessageById(r);if(!l?.segments)return;let c=l.segments.findIndex(d=>d.id===a);if(c!==-1){let d=l.segments[c],u=Ci(d,o);l.segments[c]=$s(d,u),this._notifyBubble(r,"updateSegment",{segmentId:a,updates:u})}}removeSegment(t,e){let s=e===void 0,i=s?this._activeMessageId():t,r=s?t:e;if(!i||!r)return;let a=this._repo.getMessageById(i);if(a?.segments){let o=a.segments.findIndex(l=>l.id===r);o!==-1&&(a.segments.splice(o,1),Ti(a.segments))}this._notifyBubble(i,"removeSegment",r)}startSegment(t,e){let s={...e,isStreaming:!0};this.addSegment(t,s)}completeSegment(t,e){this.updateSegment(t,e,{isStreaming:!1})}setUsage(t,e){let s=this._repo.getMessageById(t);s&&(s.usage=e),this._notifyBubble(t,"setUsage",e)}completeMessage(t){let e=this._repo.getMessageById(t);e&&(e.isStreaming=!1,e.status="completed",this._settleSegments(t,e),this._notifyBubble(t,"complete",{status:"completed"}),this._syncBusy(),this._recalculateSpacer())}_settleSegments(t,e){if(e.segments)for(let s of Mi(e.segments))this.updateSegment(t,s,{isStreaming:!1})}updateMessage(t,e){let s=this._repo.getMessageById(t);s&&(Object.assign(s,e),e.status&&(s.isStreaming=e.status==="streaming"||e.status==="pending",qs(e.status)&&this._settleSegments(t,s)),this._notifyBubble(t,"update",e),e.status&&this._syncBusy(),this._autoScroll())}addMessage(t){let e=Se({...t});xt(t)&&(e.isStreaming=!0),this._repo.addOrUpdateMessage(this._repo.headId,e),this._pruneRenderedBubbles(),this._syncBusy(),this._autoScroll()}appendMessage(t,e){t=Gr(t,k(this).getStreamBlocks());let s=e?.historical?Se(t):t.segments?.length?{...t,segments:t.segments.reduce((i,r)=>(i.push(Hs(i,r,t.id,k(this).getSegmentDefaults(r.type))),i),[])}:{...t};if(!e?.historical&&xt(t)&&(s.isStreaming=!0),zr(t)&&pn(s),this._repo.addOrUpdateMessage(this._repo.headId,s),!this._frameworkManagedDOM){let i=this.querySelector(".aparte-messages-wrapper");if(i){let r=document.createElement("aparte-chat-bubble");r.setAttribute("message-id",t.id),r.setAttribute("data-role",t.role),t.compaction&&r.setAttribute("data-kind","compaction"),t.timestamp&&r.setAttribute("timestamp",String(t.timestamp)),t.content&&r.setAttribute("content",t.content),xt(t)&&r.setAttribute("streaming",""),this._bottomSpacer&&this._bottomSpacer.parentNode===i?i.insertBefore(r,this._bottomSpacer):i.appendChild(r),tn(r,s)}}this._pruneRenderedBubbles(),this._syncBusy(),t.role==="user"&&(this._isAutoScrollEnabled=!0,this._smoothScrollToBottom()),this._recalculateSpacer(),t.role==="user"?requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._smoothScrollToBottom()}):this._autoScroll()}updateLastMessage(t,e){let s=this._repo.headId;if(s)if(e?.append)this.appendToken(s,t);else{let i=this._repo.getMessageById(s);i&&(i.content=t),this._notifyBubble(s,"appendToken",t)}}addBranch(t){let e=this._repo.getMessage(t);if(!e)return 0;let s={id:G(),role:"assistant",content:"",status:"pending",timestamp:Date.now()};return this._repo.addOrUpdateMessage(e.parentId,s),this._repo.switchToBranch(s.id),this._reRenderActivePath(),this._repo.getBranches(s.id).indexOf(s.id)}addSiblingOf(t,e){let s=this._repo.getMessage(t);if(!s)return null;let i=s.message.role==="user"?t:s.parentId,r={...e};return xt(e)&&(r.isStreaming=!0),this._repo.addOrUpdateMessage(i,r),this._repo.switchToBranch(e.id),this._reRenderActivePath(),e.id}navigateBranch(t,e){if(this._busy)return;let s=this._repo.getBranches(t),i=s.indexOf(t);if(i===-1)return;let r=e==="prev"?i-1:i+1;r<0||r>=s.length||(this._isAutoScrollEnabled=this._isAtBottom(),this._updateScrollButton(),this._repo.switchToBranch(s[r]),this._reRenderActivePath())}truncateResponsesAfter(t){let e=this._repo.getMessages();if(this._repo.clearChildren(t),!this._frameworkManagedDOM){let s=this.querySelector(".aparte-messages-wrapper");if(s){let i=e.findIndex(a=>a.id===t),r=i>=0?e.slice(i+1):[];for(let a of r)s.querySelector(`aparte-chat-bubble[message-id="${z(a.id)}"]`)?.remove()}}}truncateFrom(t){let e=this._repo.getMessages(),s=e.findIndex(r=>r.id===t);if(s===-1)return;let i=e.slice(s).map(r=>r.id);if(this._repo.resetHead(t),!this._frameworkManagedDOM){let r=this.querySelector(".aparte-messages-wrapper");for(let a of i)r?.querySelector(`aparte-chat-bubble[message-id="${z(a)}"]`)?.remove()}}getMessage(t){return this._repo.getMessageById(t)}getMessages(){return this._repo.getMessages()}exportTree(){return this._repo.export()}importTree(t){this.clearAll({revokeAttachments:!1});let e=k(this).getStreamBlocks();this._repo.import({...t,messages:t.messages.map(s=>{let i=Gr(s.message,e),r=Se(i);return zr(i)&&pn(r),{...s,message:r}})}),this._reRenderActivePath()}clearAll(t){if(t?.revokeAttachments!==!1)for(let e of this._repo.getAllMessages())Ar(e.attachments);if(this._repo.clear(),this._syncBusy(),!this._frameworkManagedDOM){let e=this.querySelector(".aparte-messages-wrapper");e&&Array.from(e.querySelectorAll("aparte-chat-bubble")).forEach(s=>s.remove())}this._setSpacerHeight(0),this._isAutoScrollEnabled=!0,this._updateScrollButton(),this._checkpointState?.clear(),this.dispatchEvent(new CustomEvent("aparte-reset-done",{bubbles:!0,composed:!0}))}clearMessages(){this._repo.clear()}setMessages(t){this.clearAll({revokeAttachments:!1});for(let e of t)this.appendMessage(e,{historical:!0})}scrollToBottom(){this._scrollToBottom()}resetSpacer(){this._setSpacerHeight(0),this._layoutTransitionMs>0&&(this._spacerFrozenUntil=Date.now()+this._layoutTransitionMs)}setAutoScroll(t){this._isAutoScrollEnabled=t,t||(this._readerInputAt=performance.now())}setFrameworkManagedDOM(t){this._frameworkManagedDOM=t}_getOrCreateMessage(t){let e=this._repo.getMessageById(t);if(e)return e;let s={id:t,role:"assistant",content:"",timestamp:Date.now(),isStreaming:!0,status:"streaming"};return this._repo.addOrUpdateMessage(this._repo.headId,s),s}_notifyBubble(t,e,s,i){let r=this.querySelector(`aparte-chat-bubble[message-id="${z(t)}"], [data-aparte-bubble][message-id="${z(t)}"]`);if(r)switch(e){case"appendToken":r.appendToken?.(s);break;case"appendToSegment":r.appendToSegment?.(i,s);break;case"addSegment":r.addSegment?.(s);break;case"updateSegment":{let{segmentId:a,updates:o}=s;r.updateSegment?.(a,o);break}case"removeSegment":r.removeSegment?.(s);break;case"setUsage":r.setUsage?.(s);break;case"update":{let a=s;["status","segments","content","attachments","usage","finishReason","contextSummary","compaction"].some(l=>l in a)&&r.updateMessage?.(s);break}case"complete":r.updateMessage?.(s);break}}_reRenderActivePath(){let t=this._repo.getMessages(),e=t.map(r=>{let a=this._repo.getBranches(r.id);return{id:r.id,count:a.length,index:a.indexOf(r.id)}});if(this._frameworkManagedDOM){this._dispatchPathChanged(t,e);return}let s=this.querySelector(".aparte-messages-wrapper");if(!s)return;s.innerHTML="";let i=Math.max(0,t.length-this._maxRenderedBubbles);for(let r=i;r<t.length;r++){let a=t[r],o=e[r],l=document.createElement("aparte-chat-bubble");l.setAttribute("message-id",a.id),l.setAttribute("data-role",a.role),a.compaction&&l.setAttribute("data-kind","compaction"),a.timestamp&&l.setAttribute("timestamp",String(a.timestamp)),xt(a)&&l.setAttribute("streaming",""),s.appendChild(l),tn(l,a,o)}this._dispatchPathChanged(t,e),this._syncBusy(),this._checkpointState?.reapply(),this._recalculateSpacer()}_dispatchPathChanged(t,e){let s={messages:t,siblings:e};this.dispatchEvent(new CustomEvent("aparte-path-changed",{bubbles:!0,composed:!0,detail:s}))}_autoScroll(){this._isAutoScrollEnabled&&requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._scrollToBottom()}),this._pruneRenderedBubbles()}requestSmoothScroll(){this._smoothScrollOnce=!0}_render(){if(this._frameworkManagedDOM){this._setupFrameworkDOM();return}if(this.querySelector(".aparte-viewport-container"))this._container=this.querySelector(".aparte-viewport-container"),this._scrollBtn=this.querySelector(".aparte-scroll-btn"),this._bottomSpacer=this.querySelector(".aparte-bottom-spacer");else{let t=document.createElement("div");t.className="aparte-viewport-container";let e=k(this).getLocale();e.direction&&t.setAttribute("dir",e.direction),t.setAttribute("role","log"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","false"),t.setAttribute("aria-relevant","additions"),this._nameScrollSurface(t);let s=document.createElement("div");for(s.className="aparte-messages-wrapper";this.firstChild;)s.appendChild(this.firstChild);this._bottomSpacer=document.createElement("div"),this._bottomSpacer.className="aparte-bottom-spacer",this._bottomSpacer.setAttribute("aria-hidden","true"),s.appendChild(this._bottomSpacer),t.appendChild(s),this.appendChild(t),this._container=t,this._syncLoading(),this._scrollBtn=document.createElement("button"),this._scrollBtn.className="aparte-btn aparte-btn--surface aparte-btn--circle aparte-btn--lg aparte-scroll-btn aparte-scroll-btn--hidden",this._scrollBtn.setAttribute("type","button"),this._scrollBtn.setAttribute("aria-label",k(this).t("scrollToBottom"));let i=k(this).getIcon("scrollDown");this._scrollBtn.innerHTML=i,this.appendChild(this._scrollBtn)}}_setupFrameworkDOM(){if(this._container=this,this._bottomSpacer=null,this.classList.contains("aparte-viewport--framework")){this._scrollBtn=this.querySelector(":scope > .aparte-scroll-btn");return}this.classList.add("aparte-viewport--framework"),this._nameScrollSurface(this);let t=document.createElement("button");t.className="aparte-btn aparte-btn--surface aparte-btn--circle aparte-btn--lg aparte-scroll-btn aparte-scroll-btn--hidden",t.setAttribute("type","button"),t.setAttribute("aria-label",k(this).t("scrollToBottom"));let e=k(this).getIcon("scrollDown");t.innerHTML=e,this.appendChild(t),this._scrollBtn=t}_keepScrollButtonLast(){this._scrollBtn&&this.lastElementChild!==this._scrollBtn&&this.appendChild(this._scrollBtn)}_getSpacerHeight(){return this._frameworkManagedDOM?this._fwSpacerHeight:this._bottomSpacer?.offsetHeight??0}_setSpacerHeight(t){this._frameworkManagedDOM?(this._fwSpacerHeight=t,this.style.setProperty("--aparte-fw-spacer",`${t}px`)):this._bottomSpacer&&(this._bottomSpacer.style.height=`${t}px`)}_onScrollBtnClick=()=>{this._isAutoScrollEnabled=!0,this._smoothScrollToBottom(),this._updateScrollButton()};_pointerHeld=!1;_holdPointer=()=>{this._pointerHeld=!0};_releasePointer=()=>{this._pointerHeld=!1};_noteReaderInput=t=>{if(!(t.type==="keydown"&&!this._scrollKeys.has(t.key))){if(t.type==="pointerdown"){let e=this._container;if(!e)return;let{clientX:s}=t,i=e.getBoundingClientRect();if(!(getComputedStyle(e).direction==="rtl"?s<=i.right-e.clientWidth:s>=i.left+e.clientWidth))return}if(this._readerInputAt=performance.now(),this._gliding()&&this._container&&(this._glideUntil=0,t.type==="wheel"||t.type==="touchmove")){this._ownScrollAt=performance.now();let e=this._container.scrollTop;this._container.scrollTop=e}}};_onBranchNavigate=t=>{let e=t;e.stopPropagation(),this.navigateBranch(e.detail.messageId,e.detail.direction)};_setupEventListeners(){this._container?.addEventListener("scroll",this._handleScroll,{passive:!0}),this._container?.addEventListener("scrollend",this._handleScrollEnd,{passive:!0});for(let t of["wheel","touchmove","pointerdown","keydown"])this._container?.addEventListener(t,this._noteReaderInput,{passive:!0});this._container?.addEventListener("pointerdown",this._holdPointer,{passive:!0}),document.addEventListener("pointerup",this._releasePointer,!0),document.addEventListener("pointercancel",this._releasePointer,!0),this._scrollBtn?.addEventListener("click",this._onScrollBtnClick),this.addEventListener("aparte-branch-navigate",this._onBranchNavigate)}_setupObservers(){this._resizeObserver=new ResizeObserver(()=>{this._updateOverlayInset(),this._updateTranscriptInset(),this._isAutoScrollEnabled&&this._scrollToBottom(),this._recalculateSpacer(),this._updateScrollButton()});let t=this.querySelector(".aparte-messages-wrapper");if(this._container&&(this._frameworkManagedDOM?this._resizeObserver.observe(this._container,{box:"border-box"}):this._resizeObserver.observe(this._container)),this._overlayRoot=this.closest("[overlay-composer]"),this._overlayRoot&&this._resizeObserver){for(let s of this._overlayStack())this._resizeObserver.observe(s);this._overlayObserver=new MutationObserver(()=>{for(let s of this._overlayStack())this._resizeObserver?.observe(s);this._updateOverlayInset()}),this._overlayObserver.observe(this._overlayRoot,{childList:!0}),this._updateOverlayInset()}this._mutationObserver=new MutationObserver(s=>{if(this._lastMutationAt=performance.now(),this._frameworkManagedDOM&&this._keepScrollButtonLast(),this._isAutoScrollEnabled&&!this._gliding()){let r=s.flatMap(o=>Array.from(o.addedNodes)).filter(o=>o instanceof Element&&o.tagName==="APARTE-CHAT-BUBBLE"),a=r.length===1?r[0]:void 0;if(a&&a.getAttribute("data-role")==="user"&&a.parentElement){let o=a.parentElement.querySelectorAll("aparte-chat-bubble");o[o.length-1]===a&&(this._smoothScrollOnce=!0)}}this._isAutoScrollEnabled&&requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._scrollToBottom()}),this._scheduleSpacerUpdate();let i=r=>Array.from(r).some(a=>a instanceof Element&&(a.tagName==="APARTE-CHAT-BUBBLE"||a.querySelector("aparte-chat-bubble")!==null));s.some(r=>i(r.addedNodes)||i(r.removedNodes))&&this._observeTail()}),this._tailObserver=new ResizeObserver(s=>{let i=!1;for(let r of s){let a=Math.round(r.borderBoxSize?.[0]?.blockSize??r.contentRect.height);this._tailHeights.get(r.target)!==a&&(i=!0),this._tailHeights.set(r.target,a)}i&&this._scheduleSpacerUpdate()}),this._observeTail(),this.addEventListener("toggle",this._onDisclosureToggle,!0);let e=this._frameworkManagedDOM?this:t;e&&this._mutationObserver.observe(e,{childList:!0,subtree:!0})}_overlayStack(){return this._overlayRoot?Array.from(this._overlayRoot.children).filter(t=>t instanceof HTMLElement&&t!==this&&t.tagName.toLowerCase()!=="aparte-scroll-rail"):[]}_updateOverlayInset(){if(!this._overlayRoot)return;let t=this.getBoundingClientRect().bottom,e=1/0;for(let i of this._overlayStack()){let r=i.getBoundingClientRect();r.height>0&&(e=Math.min(e,r.top))}let s=e===1/0?0:Math.max(0,Math.round(t-e));s!==this._overlayInset&&(this._overlayInset=s,this.style.setProperty("--aparte-bottom-inset",`${s}px`))}_updateTranscriptInset(){let t=this.parentElement;if(!t)return;let e=this.querySelector(".aparte-messages-wrapper")??this._container??this,s=parseFloat(getComputedStyle(e).paddingInlineStart)||0,i=getComputedStyle(t).direction==="rtl",r=e.getBoundingClientRect(),a=t.getBoundingClientRect(),o=i?a.right-r.right:r.left-a.left,l=Math.max(0,Math.round((o+s)*10)/10);l!==this._transcriptInset&&(this._transcriptInset=l,t.style.setProperty("--aparte-transcript-inset",`${l}px`))}_isAtBottom(){if(!this._container)return!0;let{scrollTop:t,scrollHeight:e,clientHeight:s}=this._container;return e-t-s<=this._scrollThreshold}_handleScroll(){if(!this._container)return;let t=this._container.scrollTop,e=this._container.scrollHeight,s=this._lastScrollTop-t,i=Math.abs(e-this._lastScrollHeight),r=performance.now(),a=e<this._lastScrollHeight-1,o=r-this._lastMutationAt<this._settleShadowMs&&s<=this._settleBoundPx,l=r-this._ownScrollAt<this._ownScrollWindowMs&&r-this._readerInputAt>=this._ownScrollWindowMs&&!this._pointerHeld&&(s<=i+2||a||o),c=s>1&&!l,d=s>1&&r-this._readerInputAt<this._ownScrollWindowMs;this._lastScrollTop=t,this._lastScrollHeight=e,this._isAtBottom()&&!d?this._isAutoScrollEnabled=!0:c?this._isAutoScrollEnabled=!1:s>1&&l&&this._isAutoScrollEnabled&&this._settleAtBottom(),this._updateScrollButton()}_scrollToBottom(){if(this._container){if(this._smoothScrollOnce){this._smoothScrollOnce=!1,this._smoothScrollToBottom();return}if(this._gliding()){this._retargetGlide();return}this._ownScrollAt=performance.now(),this._container.scrollTop=this._container.scrollHeight,this._settleAtBottom()}}_gliding(){return performance.now()<this._glideUntil}_retargetGlide(){this._container&&(this._ownScrollAt=performance.now(),this._armGlide(),this._container.scrollTo({top:this._container.scrollHeight,behavior:"smooth"}))}_armGlide(){this._glideUntil=performance.now()+this._glideWindowMs,this._glideSettleTimer!==null&&clearTimeout(this._glideSettleTimer),this._glideSettleTimer=setTimeout(()=>{if(this._glideSettleTimer=null,!this._container||!this._isAutoScrollEnabled||this._gliding())return;let t=this._container.scrollHeight-this._container.clientHeight;this._container.scrollTop<this._lastScrollTop-1||t-this._container.scrollTop>1&&this._scrollToBottom()},this._glideWindowMs+16)}_handleScrollEnd(){if(!this._container)return;this._container.scrollHeight-this._container.clientHeight-this._container.scrollTop<=1&&(this._glideUntil=0)}_settleAtBottom(){if(this._settleUntil=performance.now()+this._settleWindowMs,this._settleRafId!==null)return;let t=()=>{if(this._settleRafId=null,!this.isConnected||!this._container||!this._isAutoScrollEnabled){this._settleUntil=0;return}let e=this._container.scrollHeight-this._container.clientHeight;e-this._container.scrollTop>1&&!this._gliding()&&(this._ownScrollAt=performance.now(),this._container.scrollTop=e),performance.now()<this._settleUntil?this._settleRafId=requestAnimationFrame(t):this._settleUntil=0};this._settleRafId=requestAnimationFrame(t)}_smoothScrollToBottom(){this._container&&(this._ownScrollAt=performance.now(),typeof this._container.scrollTo=="function"&&!this._prefersReducedMotion()?(this._armGlide(),this._container.scrollTo({top:this._container.scrollHeight,behavior:"smooth"})):this._container.scrollTop=this._container.scrollHeight)}_prefersReducedMotion(){return typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}_updateScrollButton(){let t=this._scrollBtn;if(!t)return;let e=this._isAtBottom();t.classList.contains("aparte-scroll-btn--hidden")===e&&t.hasAttribute("tabindex")===e||(t.classList.toggle("aparte-scroll-btn--hidden",e),e?(t.setAttribute("tabindex","-1"),t.setAttribute("aria-hidden","true")):(t.removeAttribute("tabindex"),t.removeAttribute("aria-hidden")))}_recalculateSpacer(){if(!this._container||!this._frameworkManagedDOM&&!this._bottomSpacer||Date.now()<this._spacerFrozenUntil)return;let t=Array.from(this.querySelectorAll("aparte-chat-bubble"));if(t.length===0){this._setSpacerHeight(0);return}let e=[...t].reverse().find(h=>h.getAttribute("data-role")==="user");if(!e){this._setSpacerHeight(0);return}let s=this._getSpacerHeight(),i=this._container.getBoundingClientRect(),a=e.getBoundingClientRect().top-i.top+this._container.scrollTop,o=this._container.scrollHeight-s;if(o<=this._container.clientHeight){this._setSpacerHeight(0);return}let l=o-a,c=parseFloat(getComputedStyle(this._container).scrollPaddingTop)||0,d=this._container.clientHeight-c-l,u=this._container.clientHeight;this._setSpacerHeight(Math.min(Math.max(0,d),u)),this._isAutoScrollEnabled&&this._scrollToBottom()}_observeTail(){if(!this._tailObserver)return;let t=Array.from(this.querySelectorAll("aparte-chat-bubble")),e=t.length;for(;e>0&&t[e-1].getAttribute("data-role")!=="user";)e--;let s=e>0?t.slice(e-1):[];for(let i of this._tail)s.includes(i)||this._tailObserver.unobserve(i);for(let i of s)this._tail.includes(i)||(this._tailHeights.set(i,Math.round(i.offsetHeight)),this._tailObserver.observe(i,{box:"border-box"}));this._tail=s}_scheduleSpacerUpdate(){this._spacerRafId===null&&(this._spacerRafId=requestAnimationFrame(()=>{this._spacerRafId=null,this._recalculateSpacer(),this._updateScrollButton()}))}_pruneRenderedBubbles(){if(this._frameworkManagedDOM)return;let t=this.querySelector(".aparte-messages-wrapper");if(!t)return;let e=t.querySelectorAll("aparte-chat-bubble"),s=e.length-this._maxRenderedBubbles;for(let i=0;i<s;i++)e[i]?.remove()}_cleanup(){this._container?.removeEventListener("scroll",this._handleScroll),this._container?.removeEventListener("scrollend",this._handleScrollEnd),this._glideSettleTimer!==null&&(clearTimeout(this._glideSettleTimer),this._glideSettleTimer=null);for(let t of["wheel","touchmove","pointerdown","keydown"])this._container?.removeEventListener(t,this._noteReaderInput);this._container?.removeEventListener("pointerdown",this._holdPointer),document.removeEventListener("pointerup",this._releasePointer,!0),document.removeEventListener("pointercancel",this._releasePointer,!0),this._pointerHeld=!1,this._scrollBtn?.removeEventListener("click",this._onScrollBtnClick),this.removeEventListener("aparte-branch-navigate",this._onBranchNavigate),this._resizeObserver?.disconnect(),this._mutationObserver?.disconnect(),this._tailObserver?.disconnect(),this._tailObserver=null,this._tail=[],this.removeEventListener("toggle",this._onDisclosureToggle,!0),this._overlayObserver?.disconnect(),this._overlayObserver=null,this._overlayRoot=null,this._overlayInset=-1,this._transcriptInset=-1,this._resizeObserver=null,this._mutationObserver=null,this._spacerRafId!==null&&(cancelAnimationFrame(this._spacerRafId),this._spacerRafId=null),this._settleRafId!==null&&(cancelAnimationFrame(this._settleRafId),this._settleRafId=null),this._settleUntil=0}};$(He);customElements.get("aparte-chat-viewport")||customElements.define("aparte-chat-viewport",He);var $e=class n extends HTMLElement{_value="";_streaming=!1;_attachments=[];_listeners=new Map;_panelActive=!1;_panelMode="submit";_panelSubmitEnabled=!1;_panelOnSubmit=null;_panelToken=null;_panelOnEvict=null;static _STATE_EVENTS=new Set(["value-change","streaming-change","disabled-change","attachments-change","panel-change"]);_onMessageStart=this._handleMessageStart.bind(this);_onMessageDone=this._handleMessageDone.bind(this);get _cfg(){return k(this)}_onConfigChangeEvent=t=>{let e=t.detail;e?.config&&e.config!==this._cfg||this._onConfigChange()};_modelGated=!1;_onConfigChange=()=>{this._evaluateModelGate(),this._applyDirection()};_applyDirection(){let t=(this._cfg??k(this)).getLocale().direction;t?this.setAttribute("dir",t):this.removeAttribute("dir")}static get observedAttributes(){return["placeholder","disabled","target"]}connectedCallback(){window.addEventListener("aparte-message-start",this._onMessageStart),window.addEventListener("aparte-message-done",this._onMessageDone),window.addEventListener("aparte-message-error",this._onMessageDone),window.addEventListener("aparte-message-aborted",this._onMessageDone),window.addEventListener("aparte-config-change",this._onConfigChangeEvent),queueMicrotask(()=>this._warnIfUnattached()),this._evaluateModelGate(),this._applyDirection()}disconnectedCallback(){window.removeEventListener("aparte-message-start",this._onMessageStart),window.removeEventListener("aparte-message-done",this._onMessageDone),window.removeEventListener("aparte-message-error",this._onMessageDone),window.removeEventListener("aparte-message-aborted",this._onMessageDone),window.removeEventListener("aparte-config-change",this._onConfigChangeEvent),this._listeners.clear()}attributeChangedCallback(t,e,s){if(t==="disabled"&&this._emit("disabled-change",{disabled:s!==null}),t==="placeholder")for(let i of this.querySelectorAll("aparte-composer-input"))i.syncPlaceholder?.()}get value(){return this._value}get streaming(){return this._streaming}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",K(t))}get submitOnEnter(){return this.getAttribute("submit-on-enter")!=="false"}get attachments(){return this._attachments}get placeholder(){return this.getAttribute("placeholder")??""}set placeholder(t){t==null?this.removeAttribute("placeholder"):this.setAttribute("placeholder",String(t))}get targetId(){return this.getAttribute("target")}getState(){return{value:this._value,streaming:this._streaming,disabled:this.disabled,attachments:[...this._attachments],panelActive:this._panelActive,submitEnabled:this._panelSubmitEnabled}}setValue(t){this._value=t,this._emit("value-change",{value:t})}addAttachments(t){this._attachments=[...this._attachments,...Array.from(t)],this._emit("attachments-change",{attachments:this._attachments})}removeAttachment(t){this._attachments=this._attachments.filter(e=>e!==t),this._emit("attachments-change",{attachments:this._attachments})}clearAttachments(){this._attachments=[],this._emit("attachments-change",{attachments:[]})}showPanel(t,e){this._evictPanel();let s=this.querySelector("[data-aparte-panel-host]"),i=this.querySelector("aparte-composer-input");this.setAttribute("data-panel-active",""),t.dataset.apartePanel="true",s?s.appendChild(t):i?i.insertAdjacentElement("afterend",t):this.appendChild(t),this._panelActive=!0,this._panelSubmitEnabled=e?.submitEnabled??!1,this._panelMode=e?.mode??"submit",this._reflectPanelMode(),this._panelOnSubmit=e?.onSubmit??null,this._panelOnEvict=e?.onEvict??null;let r=Symbol("aparte-composer-panel");return this._panelToken=r,this._emit("panel-change",{active:!0,submitEnabled:this._panelSubmitEnabled,mode:this._panelMode}),r}hidePanel(t){if(t!==void 0){if(t!==this._panelToken)return;this._teardownPanel();return}this._evictPanel()}_evictPanel(){let t=this._panelOnEvict;this._teardownPanel(),t?.()}_teardownPanel(){let t=document.activeElement,e=t instanceof Node&&this.contains(t),s=this.querySelector("[data-aparte-panel]");s&&s.remove(),this.removeAttribute("data-panel-active"),this._panelActive=!1,this._panelSubmitEnabled=!1,this._panelMode="submit",this._reflectPanelMode(),this._panelOnSubmit=null,this._panelOnEvict=null,this._panelToken=null,this._emit("panel-change",{active:!1,submitEnabled:!1,mode:"submit"}),e&&this.focus()}setPanelSubmitEnabled(t,e){this._panelActive&&(this._panelSubmitEnabled=t,e&&(this._panelMode=e),this._reflectPanelMode(),this._emit("panel-change",{active:!0,submitEnabled:t,mode:this._panelMode}))}_reflectPanelMode(){this._panelActive?this.setAttribute("data-panel-mode",this._panelMode):this.removeAttribute("data-panel-mode")}get panelActive(){return this._panelActive}_evaluateModelGate(){let t=this._cfg.getRequireModelSelection()&&!this._cfg.hasSelectedModel();t!==this._modelGated&&(this._modelGated=t,this.toggleAttribute("data-model-gated",t))}submit(){if(this._panelActive){this._panelMode!=="none"&&this._panelSubmitEnabled&&this._panelOnSubmit?.();return}if(this._streaming){this.cancel();return}let t=this._value.trim();if(!t&&this._attachments.length===0||this.disabled||this._modelGated)return;this._emit("submit",{value:t,attachments:this._attachments});let e={content:t,timestamp:Date.now(),targetId:this._ownTargetId(),files:this._attachments.length>0?[...this._attachments]:void 0};this.dispatchEvent(new CustomEvent("aparte-send",{bubbles:!0,composed:!0,detail:e})),this.setValue(""),this.clearAttachments()}cancel(){this._emit("cancel",{}),this.dispatchEvent(new CustomEvent("aparte-cancel",{bubbles:!0,composed:!0}));let t={targetId:this._ownTargetId()};window.dispatchEvent(new CustomEvent("aparte-abort",{bubbles:!1,detail:t})),window.dispatchEvent(new CustomEvent("aparte-message-aborted",{bubbles:!1,detail:t}))}reset(){this.setValue(""),this.clearAttachments(),this._panelActive&&this._evictPanel()}focus(){this.querySelector("aparte-composer-input")?.focus()}_emit(t,e){this._listeners.get(t)?.forEach(s=>s(e)),n._STATE_EVENTS.has(t)&&this.dispatchEvent(new CustomEvent("aparte-composer-change",{bubbles:!0,composed:!0,detail:{state:this.getState(),composer:this}}))}_on(t,e){return this._listeners.has(t)||this._listeners.set(t,new Set),this._listeners.get(t).add(e),()=>this._listeners.get(t)?.delete(e)}_isForThisComposer(t){let e=t.detail?.targetId;return!e||!this._ownTargetId()||e===this._ownTargetId()}_warnIfUnattached(){!this.isConnected||this._ownTargetId()||document.querySelectorAll("aparte-chat, [data-aparte-chat]").length<2||console.warn(`[aparte-composer] this composer belongs to no chat while the page has several: give it target="<chat id>" or place it under a chat host with an id, or it will answer to every chat's events.`)}_ownTargetId(){let t=this.targetId;if(t)return t;let e=this.parentElement;for(;e;){if((e.tagName?.toLowerCase()==="aparte-chat"||e.hasAttribute?.("data-aparte-chat"))&&e.id)return e.id;e=e.parentElement}}_streamingMessageId=null;_isForThisTurn(t){let e=t.detail?.messageId;return!e||this._streamingMessageId===null||e===this._streamingMessageId}_handleMessageStart(t){this._isForThisComposer(t)&&(this._streamingMessageId=t.detail?.messageId??null,this._streaming=!0,this._emit("streaming-change",{streaming:!0}))}_handleMessageDone(t){!this._isForThisComposer(t)||!this._isForThisTurn(t)||(this._streamingMessageId=null,this._streaming=!1,this._emit("streaming-change",{streaming:!1}),this._panelActive&&this._evictPanel())}};$($e);customElements.get("aparte-composer")||customElements.define("aparte-composer",$e);function ra(n,t){let e=(n??"").split(",").map(r=>r.trim().toLowerCase()).filter(Boolean);if(e.length===0)return!0;let s=t.name.toLowerCase(),i=t.type.toLowerCase();return e.some(r=>r.startsWith(".")?s.endsWith(r):r.endsWith("/*")?i.startsWith(r.slice(0,-1)):i===r)}var qe=class extends HTMLElement{_editor=null;_maxHeight=200;_minHeight=44;_resizeObserver=null;_unsubscribes=[];_onInput=this._handleInput.bind(this);_onKeydown=this._handleKeydown.bind(this);_onFocus=this._handleFocus.bind(this);_onBlur=this._handleBlur.bind(this);_onPaste=this._handlePaste.bind(this);static get observedAttributes(){return["placeholder","max-height","min-height","disabled"]}connectedCallback(){this._render(),this._editor=this.querySelector(".aparte-ci-editor"),this._editor?.addEventListener("input",this._onInput),this._editor?.addEventListener("keydown",this._onKeydown),this._editor?.addEventListener("focus",this._onFocus),this._editor?.addEventListener("blur",this._onBlur),this._editor?.addEventListener("paste",this._onPaste),this._connectToRoot(),this._scheduleInitialReflow(),this._editor&&typeof ResizeObserver=="function"&&(this._resizeObserver=new ResizeObserver(()=>this._adjustHeight()),this._resizeObserver.observe(this._editor)),this._unsubscribes.push(ut(this,()=>this._updatePlaceholder()))}disconnectedCallback(){this._editor?.removeEventListener("input",this._onInput),this._editor?.removeEventListener("keydown",this._onKeydown),this._editor?.removeEventListener("focus",this._onFocus),this._editor?.removeEventListener("blur",this._onBlur),this._editor?.removeEventListener("paste",this._onPaste),this._resizeObserver?.disconnect(),this._resizeObserver=null,this._unsubscribes.forEach(t=>t()),this._unsubscribes=[]}attributeChangedCallback(t,e,s){t==="placeholder"&&this._updatePlaceholder(),t==="max-height"&&(this._maxHeight=parseInt(s||"200",10)),t==="min-height"&&(this._minHeight=parseInt(s||"44",10)),t==="disabled"&&this._updateDisabled(s!==null)}getValue(){if(!this._editor)return"";let t="",e=s=>{s.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?t+=i.textContent??"":i.nodeName==="BR"?t+=`
138
+ `,this.querySelector(".aparte-status-container")?.setAttribute("aria-label",t),this._writeText(this.getAttribute("text"))}_writeText(t){let e=t||null,s=this.querySelector(".aparte-status-text");s&&(s.textContent=e??""),this._syncLiveWord()}_syncLiveWord(){let t=this.querySelector(".aparte-status-sr");if(!t)return;let e=!this.getAttribute("text");t.textContent=e&&this.hasAttribute("visible")?this._word():""}_updateVisibility(t){let e=this.querySelector(".aparte-status-container");e&&e.setAttribute("data-visible",String(t)),this._syncLiveWord()}_updateText(t){let e=this.querySelector(".aparte-status-container");if(!e)return;let s=this._cfg?.getStatusRenderer?.();if(s){let i=t||this._word();e.setAttribute("aria-label",i);let r=j(this._cfg,()=>s(i));r instanceof HTMLElement?e.replaceChildren(r):e.innerHTML=r;return}this._writeText(t),e.setAttribute("aria-label",t||this._word())}};$(Be);customElements.get("aparte-chat-status")||customElements.define("aparte-chat-status",Be);function Gr(n,t){if(n.role!=="assistant"||n.segments?.length||typeof n.content!="string"||!n.content.trim())return n;let e=Ai(n.content,{blocks:t});return e.length<=1&&e.every(i=>i.type==="text")?n:pn({...n,segments:e})}function pn(n){return Object.defineProperty(n,en,{value:!0,enumerable:!1}),n}function zr(n){return n[en]===!0}var He=class extends HTMLElement{_container=null;_scrollBtn=null;_bottomSpacer=null;_fwSpacerHeight=0;_spacerRafId=null;_spacerFrozenUntil=0;_layoutTransitionMs=0;_repo=new be;_isAutoScrollEnabled=!0;_lastScrollTop=0;_lastScrollHeight=0;_lastMutationAt=Number.NEGATIVE_INFINITY;_settleShadowMs=100;_settleBoundPx=100;_ownScrollAt=Number.NEGATIVE_INFINITY;_readerInputAt=Number.NEGATIVE_INFINITY;_ownScrollWindowMs=1e3;_settleWindowMs=400;_glideUntil=0;_glideWindowMs=450;_glideSettleTimer=null;_settleUntil=0;_settleRafId=null;_scrollKeys=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]);_scrollThreshold=50;_smoothScrollOnce=!1;_maxRenderedBubbles=1e3;_resizeObserver=null;_mutationObserver=null;_tailObserver=null;_tail=[];_tailHeights=new WeakMap;_onDisclosureToggle=()=>{this._scheduleSpacerUpdate()};_overlayRoot=null;_overlayObserver=null;_overlayAttrObserver=null;_overlayInset=-1;_transcriptInset=-1;_boundResetHandler=null;_checkpointState=null;_stopCheckpointState=null;_frameworkManagedDOM=!1;static get observedAttributes(){return["scroll-threshold","max-rendered-bubbles","loading"]}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",K(t))}setLoading(t){this.loading=t}_syncLoading(){let t=this._container;if(!t)return;let e=this.hasAttribute("loading");if(t.setAttribute("aria-busy",e?"true":"false"),this._frameworkManagedDOM)return;let s=t.querySelector(":scope > .aparte-viewport-loading");if(!e){s?.remove(),t.querySelector(":scope > .aparte-viewport-loading-status")?.remove();return}if(s)return;let i=k(this),r=document.createElement("div");r.className="aparte-viewport-loading",r.setAttribute("aria-hidden","true"),r.innerHTML='<span class="aparte-skeleton aparte-skeleton--rect aparte-viewport-loading__user"></span><span class="aparte-skeleton aparte-skeleton--text"></span><span class="aparte-skeleton aparte-skeleton--text"></span><span class="aparte-skeleton aparte-skeleton--text"></span><span class="aparte-skeleton aparte-skeleton--text aparte-viewport-loading__last"></span>';let a=document.createElement("span");a.className="aparte-viewport-loading-status aparte-sr-only",a.setAttribute("role","status"),t.prepend(r,a);let o=()=>{a.isConnected&&(a.textContent=i.t("loadingConversation"))};typeof requestAnimationFrame=="function"?requestAnimationFrame(o):o()}constructor(){super(),this._handleScroll=this._handleScroll.bind(this),this._handleScrollEnd=this._handleScrollEnd.bind(this)}connectedCallback(){this.hasAttribute("framework-managed")&&(this._frameworkManagedDOM=!0),this._render(),this._setupEventListeners(),this._setupObservers(),this._updateTranscriptInset(),this._boundResetHandler=()=>this.clearAll(),window.addEventListener("aparte-reset",this._boundResetHandler),window.addEventListener("aparte-config-change",this._onConfigChange),this._checkpointState??=new ge({ownId:()=>kr(this)??(this.id||void 0),bubbleOf:t=>this.querySelector(`aparte-chat-bubble[message-id="${z(t)}"]`),owns:t=>!!this.getMessage(t),active:()=>!this._frameworkManagedDOM}),this._stopCheckpointState??=this._checkpointState.start()}_onConfigChange=t=>{let e=t.detail;if(e?.config&&e.config!==k(this))return;this._applyDirection(),this._scrollBtn?.setAttribute("aria-label",k(this).t("scrollToBottom")),(this._frameworkManagedDOM?this:this.querySelector(".aparte-viewport-container"))?.setAttribute("aria-label",k(this).t("transcript"))};_nameScrollSurface(t){t.setAttribute("tabindex","0"),t.hasAttribute("role")||t.setAttribute("role","log"),t.setAttribute("aria-label",k(this).t("transcript"))}_applyDirection(){let t=this.querySelector(".aparte-viewport-container");if(!t)return;let e=k(this).getLocale().direction;e?t.setAttribute("dir",e):t.removeAttribute("dir")}disconnectedCallback(){window.removeEventListener("aparte-config-change",this._onConfigChange),this._boundResetHandler&&(window.removeEventListener("aparte-reset",this._boundResetHandler),this._boundResetHandler=null),this._stopCheckpointState?.(),this._stopCheckpointState=null,this._cleanup()}attributeChangedCallback(t,e,s){if(e!==s)switch(t){case"scroll-threshold":this._scrollThreshold=parseInt(s||"50",10);break;case"max-rendered-bubbles":this._maxRenderedBubbles=parseInt(s||"1000",10),this._pruneRenderedBubbles();break;case"loading":this._syncLoading();break}}configure(t){t.scrollThreshold!==void 0&&(this._scrollThreshold=t.scrollThreshold),t.maxRenderedBubbles!==void 0&&(this._maxRenderedBubbles=t.maxRenderedBubbles,this._pruneRenderedBubbles()),t.layoutTransitionMs!==void 0&&(this._layoutTransitionMs=t.layoutTransitionMs)}appendToken(t,e){let s=this._getOrCreateMessage(t);s.content=(s.content||"")+e,this._notifyBubble(t,"appendToken",e),this._autoScroll(),this._scheduleSpacerUpdate()}appendToSegment(t,e,s){let i=this._getOrCreateMessage(t);i.segments||(i.segments=[]);let r=i.segments.findIndex(o=>o.id===e),a=r===-1?void 0:i.segments[r];a&&"content"in a&&(i.segments[r]={...a,content:a.content+s,...ki(a)}),this.dispatchEvent(new CustomEvent("aparte-segment-update",{bubbles:!0,composed:!0,detail:{messageId:t,segmentId:e,content:s,append:!0}})),this._notifyBubble(t,"appendToSegment",s,e),this._autoScroll()}_activeMessageId(){let t=this._repo.headId,e=this._streamingMessageId();return e!==null&&e!==t?null:t}_streamingMessageId(){let t=this._repo.headId,e=null;for(let s of this._repo.getAllMessages())if(s.isStreaming){if(s.id!==t)return s.id;e=s.id}return e}_syncBusy(){this._frameworkManagedDOM||this.setTranscriptBusy(this._streamingMessageId()!==null)}_busy=!1;setTranscriptBusy(t){this._busy=t,this.toggleAttribute("data-busy",t);for(let e of this.querySelectorAll("aparte-chat-bubble"))e.setTranscriptBusy?.(t)}addSegment(t,e){let s=typeof t=="string"?t:this._activeMessageId(),i=typeof t=="string"?e:t;if(!s||!i)return;let r=this._getOrCreateMessage(s);r.segments||(r.segments=[]);let a=Hs(r.segments,i,s,k(this).getSegmentDefaults(i.type));r.segments.push(a),this._notifyBubble(s,"addSegment",a),this._autoScroll()}updateSegment(t,e,s){let i=s===void 0&&typeof e=="object",r=i?this._activeMessageId():t,a=i?t:e,o=i?e:s;if(!r)return;let l=this._repo.getMessageById(r);if(!l?.segments)return;let c=l.segments.findIndex(d=>d.id===a);if(c!==-1){let d=l.segments[c],u=Ci(d,o);l.segments[c]=$s(d,u),this._notifyBubble(r,"updateSegment",{segmentId:a,updates:u})}}removeSegment(t,e){let s=e===void 0,i=s?this._activeMessageId():t,r=s?t:e;if(!i||!r)return;let a=this._repo.getMessageById(i);if(a?.segments){let o=a.segments.findIndex(l=>l.id===r);o!==-1&&(a.segments.splice(o,1),Ti(a.segments))}this._notifyBubble(i,"removeSegment",r)}startSegment(t,e){let s={...e,isStreaming:!0};this.addSegment(t,s)}completeSegment(t,e){this.updateSegment(t,e,{isStreaming:!1})}setUsage(t,e){let s=this._repo.getMessageById(t);s&&(s.usage=e),this._notifyBubble(t,"setUsage",e)}completeMessage(t){let e=this._repo.getMessageById(t);e&&(e.isStreaming=!1,e.status="completed",this._settleSegments(t,e),this._notifyBubble(t,"complete",{status:"completed"}),this._syncBusy(),this._recalculateSpacer())}_settleSegments(t,e){if(e.segments)for(let s of Mi(e.segments))this.updateSegment(t,s,{isStreaming:!1})}updateMessage(t,e){let s=this._repo.getMessageById(t);s&&(Object.assign(s,e),e.status&&(s.isStreaming=e.status==="streaming"||e.status==="pending",qs(e.status)&&this._settleSegments(t,s)),this._notifyBubble(t,"update",e),e.status&&this._syncBusy(),this._autoScroll())}addMessage(t){let e=Se({...t});xt(t)&&(e.isStreaming=!0),this._repo.addOrUpdateMessage(this._repo.headId,e),this._pruneRenderedBubbles(),this._syncBusy(),this._autoScroll()}appendMessage(t,e){t=Gr(t,k(this).getStreamBlocks());let s=e?.historical?Se(t):t.segments?.length?{...t,segments:t.segments.reduce((i,r)=>(i.push(Hs(i,r,t.id,k(this).getSegmentDefaults(r.type))),i),[])}:{...t};if(!e?.historical&&xt(t)&&(s.isStreaming=!0),zr(t)&&pn(s),this._repo.addOrUpdateMessage(this._repo.headId,s),!this._frameworkManagedDOM){let i=this.querySelector(".aparte-messages-wrapper");if(i){let r=document.createElement("aparte-chat-bubble");r.setAttribute("message-id",t.id),r.setAttribute("data-role",t.role),t.compaction&&r.setAttribute("data-kind","compaction"),t.timestamp&&r.setAttribute("timestamp",String(t.timestamp)),t.content&&r.setAttribute("content",t.content),xt(t)&&r.setAttribute("streaming",""),this._bottomSpacer&&this._bottomSpacer.parentNode===i?i.insertBefore(r,this._bottomSpacer):i.appendChild(r),tn(r,s)}}this._pruneRenderedBubbles(),this._syncBusy(),t.role==="user"&&(this._isAutoScrollEnabled=!0,this._smoothScrollToBottom()),this._recalculateSpacer(),t.role==="user"?requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._smoothScrollToBottom()}):this._autoScroll()}updateLastMessage(t,e){let s=this._repo.headId;if(s)if(e?.append)this.appendToken(s,t);else{let i=this._repo.getMessageById(s);i&&(i.content=t),this._notifyBubble(s,"appendToken",t)}}addBranch(t){let e=this._repo.getMessage(t);if(!e)return 0;let s={id:G(),role:"assistant",content:"",status:"pending",timestamp:Date.now()};return this._repo.addOrUpdateMessage(e.parentId,s),this._repo.switchToBranch(s.id),this._reRenderActivePath(),this._repo.getBranches(s.id).indexOf(s.id)}addSiblingOf(t,e){let s=this._repo.getMessage(t);if(!s)return null;let i=s.message.role==="user"?t:s.parentId,r={...e};return xt(e)&&(r.isStreaming=!0),this._repo.addOrUpdateMessage(i,r),this._repo.switchToBranch(e.id),this._reRenderActivePath(),e.id}navigateBranch(t,e){if(this._busy)return;let s=this._repo.getBranches(t),i=s.indexOf(t);if(i===-1)return;let r=e==="prev"?i-1:i+1;r<0||r>=s.length||(this._isAutoScrollEnabled=this._isAtBottom(),this._updateScrollButton(),this._repo.switchToBranch(s[r]),this._reRenderActivePath())}truncateResponsesAfter(t){let e=this._repo.getMessages();if(this._repo.clearChildren(t),!this._frameworkManagedDOM){let s=this.querySelector(".aparte-messages-wrapper");if(s){let i=e.findIndex(a=>a.id===t),r=i>=0?e.slice(i+1):[];for(let a of r)s.querySelector(`aparte-chat-bubble[message-id="${z(a.id)}"]`)?.remove()}}}truncateFrom(t){let e=this._repo.getMessages(),s=e.findIndex(r=>r.id===t);if(s===-1)return;let i=e.slice(s).map(r=>r.id);if(this._repo.resetHead(t),!this._frameworkManagedDOM){let r=this.querySelector(".aparte-messages-wrapper");for(let a of i)r?.querySelector(`aparte-chat-bubble[message-id="${z(a)}"]`)?.remove()}}getMessage(t){return this._repo.getMessageById(t)}getMessages(){return this._repo.getMessages()}exportTree(){return this._repo.export()}importTree(t){this.clearAll({revokeAttachments:!1});let e=k(this).getStreamBlocks();this._repo.import({...t,messages:t.messages.map(s=>{let i=Gr(s.message,e),r=Se(i);return zr(i)&&pn(r),{...s,message:r}})}),this._reRenderActivePath()}clearAll(t){if(t?.revokeAttachments!==!1)for(let e of this._repo.getAllMessages())Ar(e.attachments);if(this._repo.clear(),this._syncBusy(),!this._frameworkManagedDOM){let e=this.querySelector(".aparte-messages-wrapper");e&&Array.from(e.querySelectorAll("aparte-chat-bubble")).forEach(s=>s.remove())}this._setSpacerHeight(0),this._isAutoScrollEnabled=!0,this._updateScrollButton(),this._checkpointState?.clear(),this.dispatchEvent(new CustomEvent("aparte-reset-done",{bubbles:!0,composed:!0}))}clearMessages(){this._repo.clear()}setMessages(t){this.clearAll({revokeAttachments:!1});for(let e of t)this.appendMessage(e,{historical:!0})}scrollToBottom(){this._scrollToBottom()}resetSpacer(){this._setSpacerHeight(0),this._layoutTransitionMs>0&&(this._spacerFrozenUntil=Date.now()+this._layoutTransitionMs)}setAutoScroll(t){this._isAutoScrollEnabled=t,t||(this._readerInputAt=performance.now())}setFrameworkManagedDOM(t){this._frameworkManagedDOM=t}_getOrCreateMessage(t){let e=this._repo.getMessageById(t);if(e)return e;let s={id:t,role:"assistant",content:"",timestamp:Date.now(),isStreaming:!0,status:"streaming"};return this._repo.addOrUpdateMessage(this._repo.headId,s),s}_notifyBubble(t,e,s,i){let r=this.querySelector(`aparte-chat-bubble[message-id="${z(t)}"], [data-aparte-bubble][message-id="${z(t)}"]`);if(r)switch(e){case"appendToken":r.appendToken?.(s);break;case"appendToSegment":r.appendToSegment?.(i,s);break;case"addSegment":r.addSegment?.(s);break;case"updateSegment":{let{segmentId:a,updates:o}=s;r.updateSegment?.(a,o);break}case"removeSegment":r.removeSegment?.(s);break;case"setUsage":r.setUsage?.(s);break;case"update":{let a=s;["status","segments","content","attachments","usage","finishReason","contextSummary","compaction"].some(l=>l in a)&&r.updateMessage?.(s);break}case"complete":r.updateMessage?.(s);break}}_reRenderActivePath(){let t=this._repo.getMessages(),e=t.map(r=>{let a=this._repo.getBranches(r.id);return{id:r.id,count:a.length,index:a.indexOf(r.id)}});if(this._frameworkManagedDOM){this._dispatchPathChanged(t,e);return}let s=this.querySelector(".aparte-messages-wrapper");if(!s)return;s.innerHTML="";let i=Math.max(0,t.length-this._maxRenderedBubbles);for(let r=i;r<t.length;r++){let a=t[r],o=e[r],l=document.createElement("aparte-chat-bubble");l.setAttribute("message-id",a.id),l.setAttribute("data-role",a.role),a.compaction&&l.setAttribute("data-kind","compaction"),a.timestamp&&l.setAttribute("timestamp",String(a.timestamp)),xt(a)&&l.setAttribute("streaming",""),s.appendChild(l),tn(l,a,o)}this._dispatchPathChanged(t,e),this._syncBusy(),this._checkpointState?.reapply(),this._recalculateSpacer()}_dispatchPathChanged(t,e){let s={messages:t,siblings:e};this.dispatchEvent(new CustomEvent("aparte-path-changed",{bubbles:!0,composed:!0,detail:s}))}_autoScroll(){this._isAutoScrollEnabled&&requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._scrollToBottom()}),this._pruneRenderedBubbles()}requestSmoothScroll(){this._smoothScrollOnce=!0}_render(){if(this._frameworkManagedDOM){this._setupFrameworkDOM();return}if(this.querySelector(".aparte-viewport-container"))this._container=this.querySelector(".aparte-viewport-container"),this._scrollBtn=this.querySelector(".aparte-scroll-btn"),this._bottomSpacer=this.querySelector(".aparte-bottom-spacer");else{let t=document.createElement("div");t.className="aparte-viewport-container";let e=k(this).getLocale();e.direction&&t.setAttribute("dir",e.direction),t.setAttribute("role","log"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","false"),t.setAttribute("aria-relevant","additions"),this._nameScrollSurface(t);let s=document.createElement("div");for(s.className="aparte-messages-wrapper";this.firstChild;)s.appendChild(this.firstChild);this._bottomSpacer=document.createElement("div"),this._bottomSpacer.className="aparte-bottom-spacer",this._bottomSpacer.setAttribute("aria-hidden","true"),s.appendChild(this._bottomSpacer),t.appendChild(s),this.appendChild(t),this._container=t,this._syncLoading(),this._scrollBtn=document.createElement("button"),this._scrollBtn.className="aparte-btn aparte-btn--surface aparte-btn--circle aparte-btn--lg aparte-scroll-btn aparte-scroll-btn--hidden",this._scrollBtn.setAttribute("type","button"),this._scrollBtn.setAttribute("aria-label",k(this).t("scrollToBottom"));let i=k(this).getIcon("scrollDown");this._scrollBtn.innerHTML=i,this.appendChild(this._scrollBtn)}}_setupFrameworkDOM(){if(this._container=this,this._bottomSpacer=null,this.classList.contains("aparte-viewport--framework")){this._scrollBtn=this.querySelector(":scope > .aparte-scroll-btn");return}this.classList.add("aparte-viewport--framework"),this._nameScrollSurface(this);let t=document.createElement("button");t.className="aparte-btn aparte-btn--surface aparte-btn--circle aparte-btn--lg aparte-scroll-btn aparte-scroll-btn--hidden",t.setAttribute("type","button"),t.setAttribute("aria-label",k(this).t("scrollToBottom"));let e=k(this).getIcon("scrollDown");t.innerHTML=e,this.appendChild(t),this._scrollBtn=t}_keepScrollButtonLast(){this._scrollBtn&&this.lastElementChild!==this._scrollBtn&&this.appendChild(this._scrollBtn)}_getSpacerHeight(){return this._frameworkManagedDOM?this._fwSpacerHeight:this._bottomSpacer?.offsetHeight??0}_setSpacerHeight(t){this._frameworkManagedDOM?(this._fwSpacerHeight=t,this.style.setProperty("--aparte-fw-spacer",`${t}px`)):this._bottomSpacer&&(this._bottomSpacer.style.height=`${t}px`)}_onScrollBtnClick=()=>{this._isAutoScrollEnabled=!0,this._smoothScrollToBottom(),this._updateScrollButton()};_pointerHeld=!1;_holdPointer=()=>{this._pointerHeld=!0};_releasePointer=()=>{this._pointerHeld=!1};_noteReaderInput=t=>{if(!(t.type==="keydown"&&!this._scrollKeys.has(t.key))){if(t.type==="pointerdown"){let e=this._container;if(!e)return;let{clientX:s}=t,i=e.getBoundingClientRect();if(!(getComputedStyle(e).direction==="rtl"?s<=i.right-e.clientWidth:s>=i.left+e.clientWidth))return}if(this._readerInputAt=performance.now(),this._gliding()&&this._container&&(this._glideUntil=0,t.type==="wheel"||t.type==="touchmove")){this._ownScrollAt=performance.now();let e=this._container.scrollTop;this._container.scrollTop=e}}};_onBranchNavigate=t=>{let e=t;e.stopPropagation(),this.navigateBranch(e.detail.messageId,e.detail.direction)};_setupEventListeners(){this._container?.addEventListener("scroll",this._handleScroll,{passive:!0}),this._container?.addEventListener("scrollend",this._handleScrollEnd,{passive:!0});for(let t of["wheel","touchmove","pointerdown","keydown"])this._container?.addEventListener(t,this._noteReaderInput,{passive:!0});this._container?.addEventListener("pointerdown",this._holdPointer,{passive:!0}),document.addEventListener("pointerup",this._releasePointer,!0),document.addEventListener("pointercancel",this._releasePointer,!0),this._scrollBtn?.addEventListener("click",this._onScrollBtnClick),this.addEventListener("aparte-branch-navigate",this._onBranchNavigate)}_setupObservers(){this._resizeObserver=new ResizeObserver(()=>{this._updateOverlayInset(),this._updateTranscriptInset(),this._isAutoScrollEnabled&&this._scrollToBottom(),this._recalculateSpacer(),this._updateScrollButton()});let t=this.querySelector(".aparte-messages-wrapper");this._container&&(this._frameworkManagedDOM?this._resizeObserver.observe(this._container,{box:"border-box"}):this._resizeObserver.observe(this._container)),this._wireOverlay(),this.parentElement&&(this._overlayAttrObserver=new MutationObserver(()=>this._wireOverlay()),this._overlayAttrObserver.observe(this.parentElement,{attributes:!0,attributeFilter:["overlay-composer"]})),this._mutationObserver=new MutationObserver(s=>{if(this._lastMutationAt=performance.now(),this._frameworkManagedDOM&&this._keepScrollButtonLast(),this._isAutoScrollEnabled&&!this._gliding()){let r=s.flatMap(o=>Array.from(o.addedNodes)).filter(o=>o instanceof Element&&o.tagName==="APARTE-CHAT-BUBBLE"),a=r.length===1?r[0]:void 0;if(a&&a.getAttribute("data-role")==="user"&&a.parentElement){let o=a.parentElement.querySelectorAll("aparte-chat-bubble");o[o.length-1]===a&&(this._smoothScrollOnce=!0)}}this._isAutoScrollEnabled&&requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._scrollToBottom()}),this._scheduleSpacerUpdate();let i=r=>Array.from(r).some(a=>a instanceof Element&&(a.tagName==="APARTE-CHAT-BUBBLE"||a.querySelector("aparte-chat-bubble")!==null));s.some(r=>i(r.addedNodes)||i(r.removedNodes))&&this._observeTail()}),this._tailObserver=new ResizeObserver(s=>{let i=!1;for(let r of s){let a=Math.round(r.borderBoxSize?.[0]?.blockSize??r.contentRect.height);this._tailHeights.get(r.target)!==a&&(i=!0),this._tailHeights.set(r.target,a)}i&&this._scheduleSpacerUpdate()}),this._observeTail(),this.addEventListener("toggle",this._onDisclosureToggle,!0);let e=this._frameworkManagedDOM?this:t;e&&this._mutationObserver.observe(e,{childList:!0,subtree:!0})}_wireOverlay(){let t=this.closest("[overlay-composer]");if(t!==this._overlayRoot){for(let e of this._overlayStack())this._resizeObserver?.unobserve(e);if(this._overlayObserver?.disconnect(),this._overlayObserver=null,this._overlayRoot=t,this._overlayInset=-1,this.style.removeProperty("--aparte-bottom-inset"),!(!t||!this._resizeObserver)){for(let e of this._overlayStack())this._resizeObserver.observe(e);this._overlayObserver=new MutationObserver(()=>{for(let e of this._overlayStack())this._resizeObserver?.observe(e);this._updateOverlayInset()}),this._overlayObserver.observe(t,{childList:!0}),this._updateOverlayInset()}}}_overlayStack(){return this._overlayRoot?Array.from(this._overlayRoot.children).filter(t=>t instanceof HTMLElement&&t!==this&&t.tagName.toLowerCase()!=="aparte-scroll-rail"):[]}_updateOverlayInset(){if(!this._overlayRoot)return;let t=this.getBoundingClientRect().bottom,e=1/0;for(let i of this._overlayStack()){let r=i.getBoundingClientRect();r.height>0&&(e=Math.min(e,r.top))}let s=e===1/0?0:Math.max(0,Math.round(t-e));s!==this._overlayInset&&(this._overlayInset=s,this.style.setProperty("--aparte-bottom-inset",`${s}px`))}_updateTranscriptInset(){let t=this.parentElement;if(!t)return;let e=this.querySelector(".aparte-messages-wrapper")??this._container??this,s=parseFloat(getComputedStyle(e).paddingInlineStart)||0,i=getComputedStyle(t).direction==="rtl",r=e.getBoundingClientRect(),a=t.getBoundingClientRect(),o=i?a.right-r.right:r.left-a.left,l=Math.max(0,Math.round((o+s)*10)/10);l!==this._transcriptInset&&(this._transcriptInset=l,t.style.setProperty("--aparte-transcript-inset",`${l}px`))}_isAtBottom(){if(!this._container)return!0;let{scrollTop:t,scrollHeight:e,clientHeight:s}=this._container;return e-t-s<=this._scrollThreshold}_handleScroll(){if(!this._container)return;let t=this._container.scrollTop,e=this._container.scrollHeight,s=this._lastScrollTop-t,i=Math.abs(e-this._lastScrollHeight),r=performance.now(),a=e<this._lastScrollHeight-1,o=r-this._lastMutationAt<this._settleShadowMs&&s<=this._settleBoundPx,l=r-this._ownScrollAt<this._ownScrollWindowMs&&r-this._readerInputAt>=this._ownScrollWindowMs&&!this._pointerHeld&&(s<=i+2||a||o),c=s>1&&!l,d=s>1&&r-this._readerInputAt<this._ownScrollWindowMs;this._lastScrollTop=t,this._lastScrollHeight=e,this._isAtBottom()&&!d?this._isAutoScrollEnabled=!0:c?this._isAutoScrollEnabled=!1:s>1&&l&&this._isAutoScrollEnabled&&this._settleAtBottom(),this._updateScrollButton()}_scrollToBottom(){if(this._container){if(this._smoothScrollOnce){this._smoothScrollOnce=!1,this._smoothScrollToBottom();return}if(this._gliding()){this._retargetGlide();return}this._ownScrollAt=performance.now(),this._container.scrollTop=this._container.scrollHeight,this._settleAtBottom()}}_gliding(){return performance.now()<this._glideUntil}_retargetGlide(){this._container&&(this._ownScrollAt=performance.now(),this._armGlide(),this._container.scrollTo({top:this._container.scrollHeight,behavior:"smooth"}))}_armGlide(){this._glideUntil=performance.now()+this._glideWindowMs,this._glideSettleTimer!==null&&clearTimeout(this._glideSettleTimer),this._glideSettleTimer=setTimeout(()=>{if(this._glideSettleTimer=null,!this._container||!this._isAutoScrollEnabled||this._gliding())return;let t=this._container.scrollHeight-this._container.clientHeight;this._container.scrollTop<this._lastScrollTop-1||t-this._container.scrollTop>1&&this._scrollToBottom()},this._glideWindowMs+16)}_handleScrollEnd(){if(!this._container)return;this._container.scrollHeight-this._container.clientHeight-this._container.scrollTop<=1&&(this._glideUntil=0)}_settleAtBottom(){if(this._settleUntil=performance.now()+this._settleWindowMs,this._settleRafId!==null)return;let t=()=>{if(this._settleRafId=null,!this.isConnected||!this._container||!this._isAutoScrollEnabled){this._settleUntil=0;return}let e=this._container.scrollHeight-this._container.clientHeight;e-this._container.scrollTop>1&&!this._gliding()&&(this._ownScrollAt=performance.now(),this._container.scrollTop=e),performance.now()<this._settleUntil?this._settleRafId=requestAnimationFrame(t):this._settleUntil=0};this._settleRafId=requestAnimationFrame(t)}_smoothScrollToBottom(){this._container&&(this._ownScrollAt=performance.now(),typeof this._container.scrollTo=="function"&&!this._prefersReducedMotion()?(this._armGlide(),this._container.scrollTo({top:this._container.scrollHeight,behavior:"smooth"})):this._container.scrollTop=this._container.scrollHeight)}_prefersReducedMotion(){return typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}_updateScrollButton(){let t=this._scrollBtn;if(!t)return;let e=this._isAtBottom();t.classList.contains("aparte-scroll-btn--hidden")===e&&t.hasAttribute("tabindex")===e||(t.classList.toggle("aparte-scroll-btn--hidden",e),e?(t.setAttribute("tabindex","-1"),t.setAttribute("aria-hidden","true")):(t.removeAttribute("tabindex"),t.removeAttribute("aria-hidden")))}_recalculateSpacer(){if(!this._container||!this._frameworkManagedDOM&&!this._bottomSpacer||Date.now()<this._spacerFrozenUntil)return;let t=Array.from(this.querySelectorAll("aparte-chat-bubble"));if(t.length===0){this._setSpacerHeight(0);return}let e=[...t].reverse().find(h=>h.getAttribute("data-role")==="user");if(!e){this._setSpacerHeight(0);return}let s=this._getSpacerHeight(),i=this._container.getBoundingClientRect(),a=e.getBoundingClientRect().top-i.top+this._container.scrollTop,o=this._container.scrollHeight-s;if(o<=this._container.clientHeight){this._setSpacerHeight(0);return}let l=o-a,c=parseFloat(getComputedStyle(this._container).scrollPaddingTop)||0,d=this._container.clientHeight-c-l,u=this._container.clientHeight;this._setSpacerHeight(Math.min(Math.max(0,d),u)),this._isAutoScrollEnabled&&this._scrollToBottom()}_observeTail(){if(!this._tailObserver)return;let t=Array.from(this.querySelectorAll("aparte-chat-bubble")),e=t.length;for(;e>0&&t[e-1].getAttribute("data-role")!=="user";)e--;let s=e>0?t.slice(e-1):[];for(let i of this._tail)s.includes(i)||this._tailObserver.unobserve(i);for(let i of s)this._tail.includes(i)||(this._tailHeights.set(i,Math.round(i.offsetHeight)),this._tailObserver.observe(i,{box:"border-box"}));this._tail=s}_scheduleSpacerUpdate(){this._spacerRafId===null&&(this._spacerRafId=requestAnimationFrame(()=>{this._spacerRafId=null,this._recalculateSpacer(),this._updateScrollButton()}))}_pruneRenderedBubbles(){if(this._frameworkManagedDOM)return;let t=this.querySelector(".aparte-messages-wrapper");if(!t)return;let e=t.querySelectorAll("aparte-chat-bubble"),s=e.length-this._maxRenderedBubbles;for(let i=0;i<s;i++)e[i]?.remove()}_cleanup(){this._container?.removeEventListener("scroll",this._handleScroll),this._container?.removeEventListener("scrollend",this._handleScrollEnd),this._glideSettleTimer!==null&&(clearTimeout(this._glideSettleTimer),this._glideSettleTimer=null);for(let t of["wheel","touchmove","pointerdown","keydown"])this._container?.removeEventListener(t,this._noteReaderInput);this._container?.removeEventListener("pointerdown",this._holdPointer),document.removeEventListener("pointerup",this._releasePointer,!0),document.removeEventListener("pointercancel",this._releasePointer,!0),this._pointerHeld=!1,this._scrollBtn?.removeEventListener("click",this._onScrollBtnClick),this.removeEventListener("aparte-branch-navigate",this._onBranchNavigate),this._resizeObserver?.disconnect(),this._mutationObserver?.disconnect(),this._tailObserver?.disconnect(),this._tailObserver=null,this._tail=[],this.removeEventListener("toggle",this._onDisclosureToggle,!0),this._overlayObserver?.disconnect(),this._overlayObserver=null,this._overlayAttrObserver?.disconnect(),this._overlayAttrObserver=null,this._overlayRoot=null,this._overlayInset=-1,this._transcriptInset=-1,this._resizeObserver=null,this._mutationObserver=null,this._spacerRafId!==null&&(cancelAnimationFrame(this._spacerRafId),this._spacerRafId=null),this._settleRafId!==null&&(cancelAnimationFrame(this._settleRafId),this._settleRafId=null),this._settleUntil=0}};$(He);customElements.get("aparte-chat-viewport")||customElements.define("aparte-chat-viewport",He);var $e=class n extends HTMLElement{_value="";_streaming=!1;_attachments=[];_listeners=new Map;_panelActive=!1;_panelMode="submit";_panelSubmitEnabled=!1;_panelOnSubmit=null;_panelToken=null;_panelOnEvict=null;static _STATE_EVENTS=new Set(["value-change","streaming-change","disabled-change","attachments-change","panel-change"]);_onMessageStart=this._handleMessageStart.bind(this);_onMessageDone=this._handleMessageDone.bind(this);get _cfg(){return k(this)}_onConfigChangeEvent=t=>{let e=t.detail;e?.config&&e.config!==this._cfg||this._onConfigChange()};_modelGated=!1;_onConfigChange=()=>{this._evaluateModelGate(),this._applyDirection()};_applyDirection(){let t=(this._cfg??k(this)).getLocale().direction;t?this.setAttribute("dir",t):this.removeAttribute("dir")}static get observedAttributes(){return["placeholder","disabled","target"]}connectedCallback(){window.addEventListener("aparte-message-start",this._onMessageStart),window.addEventListener("aparte-message-done",this._onMessageDone),window.addEventListener("aparte-message-error",this._onMessageDone),window.addEventListener("aparte-message-aborted",this._onMessageDone),window.addEventListener("aparte-config-change",this._onConfigChangeEvent),queueMicrotask(()=>this._warnIfUnattached()),this._evaluateModelGate(),this._applyDirection()}disconnectedCallback(){window.removeEventListener("aparte-message-start",this._onMessageStart),window.removeEventListener("aparte-message-done",this._onMessageDone),window.removeEventListener("aparte-message-error",this._onMessageDone),window.removeEventListener("aparte-message-aborted",this._onMessageDone),window.removeEventListener("aparte-config-change",this._onConfigChangeEvent),this._listeners.clear()}attributeChangedCallback(t,e,s){if(t==="disabled"&&this._emit("disabled-change",{disabled:s!==null}),t==="placeholder")for(let i of this.querySelectorAll("aparte-composer-input"))i.syncPlaceholder?.()}get value(){return this._value}get streaming(){return this._streaming}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",K(t))}get submitOnEnter(){return this.getAttribute("submit-on-enter")!=="false"}get attachments(){return this._attachments}get placeholder(){return this.getAttribute("placeholder")??""}set placeholder(t){t==null?this.removeAttribute("placeholder"):this.setAttribute("placeholder",String(t))}get targetId(){return this.getAttribute("target")}getState(){return{value:this._value,streaming:this._streaming,disabled:this.disabled,attachments:[...this._attachments],panelActive:this._panelActive,submitEnabled:this._panelSubmitEnabled}}setValue(t){this._value=t,this._emit("value-change",{value:t})}addAttachments(t){this._attachments=[...this._attachments,...Array.from(t)],this._emit("attachments-change",{attachments:this._attachments})}removeAttachment(t){this._attachments=this._attachments.filter(e=>e!==t),this._emit("attachments-change",{attachments:this._attachments})}clearAttachments(){this._attachments=[],this._emit("attachments-change",{attachments:[]})}showPanel(t,e){this._evictPanel();let s=this.querySelector("[data-aparte-panel-host]"),i=this.querySelector("aparte-composer-input");this.setAttribute("data-panel-active",""),t.dataset.apartePanel="true",s?s.appendChild(t):i?i.insertAdjacentElement("afterend",t):this.appendChild(t),this._panelActive=!0,this._panelSubmitEnabled=e?.submitEnabled??!1,this._panelMode=e?.mode??"submit",this._reflectPanelMode(),this._panelOnSubmit=e?.onSubmit??null,this._panelOnEvict=e?.onEvict??null;let r=Symbol("aparte-composer-panel");return this._panelToken=r,this._emit("panel-change",{active:!0,submitEnabled:this._panelSubmitEnabled,mode:this._panelMode}),r}hidePanel(t){if(t!==void 0){if(t!==this._panelToken)return;this._teardownPanel();return}this._evictPanel()}_evictPanel(){let t=this._panelOnEvict;this._teardownPanel(),t?.()}_teardownPanel(){let t=document.activeElement,e=t instanceof Node&&this.contains(t),s=this.querySelector("[data-aparte-panel]");s&&s.remove(),this.removeAttribute("data-panel-active"),this._panelActive=!1,this._panelSubmitEnabled=!1,this._panelMode="submit",this._reflectPanelMode(),this._panelOnSubmit=null,this._panelOnEvict=null,this._panelToken=null,this._emit("panel-change",{active:!1,submitEnabled:!1,mode:"submit"}),e&&this.focus()}setPanelSubmitEnabled(t,e){this._panelActive&&(this._panelSubmitEnabled=t,e&&(this._panelMode=e),this._reflectPanelMode(),this._emit("panel-change",{active:!0,submitEnabled:t,mode:this._panelMode}))}_reflectPanelMode(){this._panelActive?this.setAttribute("data-panel-mode",this._panelMode):this.removeAttribute("data-panel-mode")}get panelActive(){return this._panelActive}_evaluateModelGate(){let t=this._cfg.getRequireModelSelection()&&!this._cfg.hasSelectedModel();t!==this._modelGated&&(this._modelGated=t,this.toggleAttribute("data-model-gated",t))}submit(){if(this._panelActive){this._panelMode!=="none"&&this._panelSubmitEnabled&&this._panelOnSubmit?.();return}if(this._streaming){this.cancel();return}let t=this._value.trim();if(!t&&this._attachments.length===0||this.disabled||this._modelGated)return;this._emit("submit",{value:t,attachments:this._attachments});let e={content:t,timestamp:Date.now(),targetId:this._ownTargetId(),files:this._attachments.length>0?[...this._attachments]:void 0};this.dispatchEvent(new CustomEvent("aparte-send",{bubbles:!0,composed:!0,detail:e})),this.setValue(""),this.clearAttachments()}cancel(){this._emit("cancel",{}),this.dispatchEvent(new CustomEvent("aparte-cancel",{bubbles:!0,composed:!0}));let t={targetId:this._ownTargetId()};window.dispatchEvent(new CustomEvent("aparte-abort",{bubbles:!1,detail:t})),window.dispatchEvent(new CustomEvent("aparte-message-aborted",{bubbles:!1,detail:t}))}reset(){this.setValue(""),this.clearAttachments(),this._panelActive&&this._evictPanel()}focus(){this.querySelector("aparte-composer-input")?.focus()}_emit(t,e){this._listeners.get(t)?.forEach(s=>s(e)),n._STATE_EVENTS.has(t)&&this.dispatchEvent(new CustomEvent("aparte-composer-change",{bubbles:!0,composed:!0,detail:{state:this.getState(),composer:this}}))}_on(t,e){return this._listeners.has(t)||this._listeners.set(t,new Set),this._listeners.get(t).add(e),()=>this._listeners.get(t)?.delete(e)}_isForThisComposer(t){let e=t.detail?.targetId;return!e||!this._ownTargetId()||e===this._ownTargetId()}_warnIfUnattached(){!this.isConnected||this._ownTargetId()||document.querySelectorAll("aparte-chat, [data-aparte-chat]").length<2||console.warn(`[aparte-composer] this composer belongs to no chat while the page has several: give it target="<chat id>" or place it under a chat host with an id, or it will answer to every chat's events.`)}_ownTargetId(){let t=this.targetId;if(t)return t;let e=this.parentElement;for(;e;){if((e.tagName?.toLowerCase()==="aparte-chat"||e.hasAttribute?.("data-aparte-chat"))&&e.id)return e.id;e=e.parentElement}}_streamingMessageId=null;_isForThisTurn(t){let e=t.detail?.messageId;return!e||this._streamingMessageId===null||e===this._streamingMessageId}_handleMessageStart(t){this._isForThisComposer(t)&&(this._streamingMessageId=t.detail?.messageId??null,this._streaming=!0,this._emit("streaming-change",{streaming:!0}))}_handleMessageDone(t){!this._isForThisComposer(t)||!this._isForThisTurn(t)||(this._streamingMessageId=null,this._streaming=!1,this._emit("streaming-change",{streaming:!1}),this._panelActive&&this._evictPanel())}};$($e);customElements.get("aparte-composer")||customElements.define("aparte-composer",$e);function ra(n,t){let e=(n??"").split(",").map(r=>r.trim().toLowerCase()).filter(Boolean);if(e.length===0)return!0;let s=t.name.toLowerCase(),i=t.type.toLowerCase();return e.some(r=>r.startsWith(".")?s.endsWith(r):r.endsWith("/*")?i.startsWith(r.slice(0,-1)):i===r)}var qe=class extends HTMLElement{_editor=null;_maxHeight=200;_minHeight=44;_resizeObserver=null;_unsubscribes=[];_onInput=this._handleInput.bind(this);_onKeydown=this._handleKeydown.bind(this);_onFocus=this._handleFocus.bind(this);_onBlur=this._handleBlur.bind(this);_onPaste=this._handlePaste.bind(this);static get observedAttributes(){return["placeholder","max-height","min-height","disabled"]}connectedCallback(){this._render(),this._editor=this.querySelector(".aparte-ci-editor"),this._editor?.addEventListener("input",this._onInput),this._editor?.addEventListener("keydown",this._onKeydown),this._editor?.addEventListener("focus",this._onFocus),this._editor?.addEventListener("blur",this._onBlur),this._editor?.addEventListener("paste",this._onPaste),this._connectToRoot(),this._scheduleInitialReflow(),this._editor&&typeof ResizeObserver=="function"&&(this._resizeObserver=new ResizeObserver(()=>this._adjustHeight()),this._resizeObserver.observe(this._editor)),this._unsubscribes.push(ut(this,()=>this._updatePlaceholder()))}disconnectedCallback(){this._editor?.removeEventListener("input",this._onInput),this._editor?.removeEventListener("keydown",this._onKeydown),this._editor?.removeEventListener("focus",this._onFocus),this._editor?.removeEventListener("blur",this._onBlur),this._editor?.removeEventListener("paste",this._onPaste),this._resizeObserver?.disconnect(),this._resizeObserver=null,this._unsubscribes.forEach(t=>t()),this._unsubscribes=[]}attributeChangedCallback(t,e,s){t==="placeholder"&&this._updatePlaceholder(),t==="max-height"&&(this._maxHeight=parseInt(s||"200",10)),t==="min-height"&&(this._minHeight=parseInt(s||"44",10)),t==="disabled"&&this._updateDisabled(s!==null)}getValue(){if(!this._editor)return"";let t="",e=s=>{s.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?t+=i.textContent??"":i.nodeName==="BR"?t+=`
139
139
  `:e(i)})};return e(this._editor),t.trim()}setValue(t){this._editor&&(this._editor.textContent=t,this._updatePlaceholderVisibility(),this._adjustHeight(),this._getRoot()?.setValue(t))}clear(){this._editor&&(this._editor.innerHTML="",this._updatePlaceholderVisibility(),this._adjustHeight(),this._getRoot()?.setValue(""))}syncPlaceholder(){this._updatePlaceholder()}focus(){this._editor?.focus()}blur(){this._editor?.blur()}focusEnd(){if(!this._editor)return;this._editor.focus();let t=this.ownerDocument?.getSelection();if(!t)return;let e=this.ownerDocument.createRange();e.selectNodeContents(this._editor),e.collapse(!1),t.removeAllRanges(),t.addRange(e)}_getRoot(){return this.closest("aparte-composer")}_getPlaceholder(){return this.getAttribute("placeholder")||this._getRoot()?.placeholder||k(this).t("inputPlaceholder")||"Type a message..."}_render(){if(this.querySelector(".aparte-ci-editor"))return;let t=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1,e=M(this._getPlaceholder());this.innerHTML=`<div
140
140
  class="aparte-ci-editor"
141
141
  contenteditable="${!t}"
@@ -203,4 +203,4 @@ ${c}
203
203
  <button type="button" class="aparte-btn aparte-btn--sm aparte-btn--danger aparte-btn--solid" data-menu-action="confirm-delete">${i}</button>
204
204
  </div>
205
205
  </div>`}_openMenu(t,e){this._closeMenu();let s=t.dataset.convId,i=this._conversations.find(a=>a.id===s);if(!i)return;let r=document.createElement("div");r.className="aparte-menu aparte-conv-menu",r.setAttribute("role","menu"),r.setAttribute("aria-label",i.title||this._t("newChat")),r.innerHTML=this._menuMarkup(i),t.appendChild(r),e.setAttribute("aria-expanded","true"),this._open={id:s,row:t,button:e,menu:r},this._placeMenu(e,r),r.querySelector('[role="menuitem"]')?.focus(),document.addEventListener("pointerdown",this._onDocumentPointerDown,!0),document.addEventListener("pointerup",this._onDocumentPointerUp,!0),document.addEventListener("pointercancel",this._onDocumentPointerUp,!0),window.addEventListener("scroll",this._onWindowScroll,!0),window.addEventListener("resize",this._onWindowScroll)}_placeMenu(t,e){let s=t.getBoundingClientRect(),i=e.getBoundingClientRect(),r=s.bottom+hn;r+i.height>window.innerHeight-Te&&s.top-i.height-hn>=Te&&(r=s.top-i.height-hn);let o=getComputedStyle(this).direction==="rtl"?s.left:s.right-i.width;o=Math.max(Te,Math.min(o,window.innerWidth-i.width-Te)),e.style.top=`${r}px`,e.style.left=`${o}px`}_closeMenu(t=!1){let e=this._open;e&&(this._open=null,e.menu.remove(),e.button.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this._onDocumentPointerDown,!0),document.removeEventListener("pointerup",this._onDocumentPointerUp,!0),document.removeEventListener("pointercancel",this._onDocumentPointerUp,!0),this._pressInMenu=!1,window.removeEventListener("scroll",this._onWindowScroll,!0),window.removeEventListener("resize",this._onWindowScroll),t&&e.button.isConnected&&e.button.focus())}_pressInMenu=!1;_onDocumentPointerUp=()=>{this._pressInMenu=!1};_onDocumentPointerDown=t=>{let e=this._open;if(!e)return;let s=ht(t);this._pressInMenu=!!s&&e.menu.contains(s),!(e.menu.contains(s)||e.button.contains(s))&&this._closeMenu()};_onWindowScroll=()=>{this._closeMenu()};_onFocusOut=t=>{let e=this._open;if(!e)return;let s=t.relatedTarget;!s&&this._pressInMenu||s&&(e.menu.contains(s)||e.button.contains(s))||e.menu.contains(t.target)&&this._closeMenu()};_manage(t,e){if(!this.hasAttribute("manage")||t.defaultPrevented)return;let s=k(this).getConversationManager();if(!s){if(this._warnedNoManager)return;this._warnedNoManager=!0,console.warn("[aparte-conversation-list] `manage` is set but no conversation manager is registered, so the row menu writes nothing. Call setConversationManager(manager) on your config, or drop `manage` and handle the events yourself.");return}e(s).catch(i=>{console.warn("[aparte-conversation-list] the conversation manager refused the change:",i)})}_onMenuAction(t){let e=this._open;if(!e)return;let s=this._conversations.find(r=>r.id===e.id);if(!s){this._closeMenu();return}let i=s.id;switch(t){case"rename":this._closeMenu(),this._startRename(e.row,s);return;case"pin":if(this._closeMenu(!0),s.pinnedAt){let r=new CustomEvent("aparte-conversation-unpin",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.unpin(i))}else{let r=new CustomEvent("aparte-conversation-pin",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.pin(i))}return;case"archive":if(this._closeMenu(!0),s.archivedAt){let r=new CustomEvent("aparte-conversation-unarchive",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.unarchive(i))}else{let r=new CustomEvent("aparte-conversation-archive",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.archive(i))}return;case"delete":{let r=[...e.menu.childNodes],a=document.createElement("div");a.innerHTML=this._confirmMarkup(s),e.menu.append(...a.childNodes),e.menu.setAttribute("role","dialog"),e.menu.setAttribute("aria-label",this._confirmQuestion(s)),e.menu.querySelector('[data-menu-action="cancel"]')?.focus();for(let o of r)o.remove();this._placeMenu(e.button,e.menu);return}case"cancel":this._closeMenu(!0);return;case"confirm-delete":{this._closeMenu(!0);let r=new CustomEvent("aparte-conversation-delete",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.delete(i));return}}}_menuFocusables(){let t=this._open;return t?Array.from(t.menu.querySelectorAll('[role="menuitem"], [data-menu-action]')):[]}_onMenuKeydown(t){let e=this._menuFocusables(),s=e.indexOf(pt(this)),i=r=>{t.preventDefault(),e[(r+e.length)%e.length]?.focus()};switch(t.key){case"Escape":t.preventDefault(),this._closeMenu(!0);return;case"Tab":t.preventDefault(),this._closeMenu(!0);return;case"ArrowDown":i(s+1);return;case"ArrowUp":i(s-1);return;case"Home":i(0);return;case"End":i(e.length-1);return}}_startRename(t,e){let s=t.querySelector(".aparte-conv-item__select");if(!s)return;let i=document.createElement("input");i.type="text",i.className="aparte-field aparte-field--sm aparte-conv-item__input",i.value=e.title,i.setAttribute("aria-label",this._t("conversationTitle")),i.dataset.renameId=e.id,s.replaceWith(i),this._renaming={id:e.id,input:i,done:!1},i.addEventListener("blur",r=>{let a=r.relatedTarget;this._finishRename(!0,!a||this.contains(a))}),i.focus(),i.select()}_finishRename(t,e){let s=this._renaming;if(!s||s.done)return;s.done=!0;let i=this._conversations.find(a=>a.id===s.id),r=s.input.value.trim();if(this._render(),t&&i&&r&&r!==i.title){let a=new CustomEvent("aparte-conversation-rename",{detail:{id:i.id,title:r},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(a),this._manage(a,o=>o.updateTitle(i.id,r))}e&&this.querySelector(`[data-select-id="${z(s.id)}"]`)?.focus()}_onClick=t=>{let e=t.target,s=e.closest("[data-menu-action]");if(s&&this._open?.menu.contains(s)){t.stopPropagation(),this._onMenuAction(s.dataset.menuAction);return}let i=e.closest("[data-more-id]");if(i){t.stopPropagation(),this._open?.button===i?this._closeMenu(!0):this._openMenu(i.closest("[data-conv-id]"),i);return}if(e.closest("[data-rename-id]"))return;let r=e.closest("[data-select-id]");r&&(this._closeMenu(),this.dispatchEvent(new CustomEvent("aparte-conversation-select",{detail:{id:r.dataset.selectId},bubbles:!0,composed:!0})))};_onKeydown=t=>{let e=t.target;if(this._open?.menu.contains(e)){this._onMenuKeydown(t);return}if(e.matches("[data-rename-id]")){t.key==="Enter"?(t.preventDefault(),this._finishRename(!0,!0)):t.key==="Escape"&&(t.preventDefault(),this._finishRename(!1,!0));return}};_updateActiveState(){this.querySelectorAll("[data-conv-id]").forEach(e=>{let s=e.dataset.convId===this._activeId;e.classList.toggle("aparte-conv-item--active",s),e.querySelector("[data-select-id]")?.setAttribute("aria-current",s?"page":"false")})}};$(Ve);customElements.get("aparte-conversation-list")||customElements.define("aparte-conversation-list",Ve);var aa=n=>typeof n=="string"||typeof n=="object"&&n!==null&&typeof n.label=="string",Vr=n=>{try{let t=JSON.parse(n);return Array.isArray(t)?t.filter(aa):[]}catch{return console.warn('[aparte-suggestions] `suggestions` is not a JSON array. Use ["\u2026"] or [{"label": "\u2026", "prompt": "\u2026"}].'),[]}},Yr=n=>typeof n=="string"?n:n.label,Qr=n=>typeof n=="string"?n:n.prompt??n.label,Ye=class extends HTMLElement{static get observedAttributes(){return["suggestions","target","empty-only"]}_suggestions=[];_composer=null;_transcript=null;_transcriptObserver=null;_sent=!1;_wasEmpty=!0;_hidOwn=!1;_onSend=()=>{this.hasAttribute("empty-only")&&(this._transcript||this._watchTranscript(),this._sent=!0,this._applyEmptyOnly())};_applyEmptyOnly=()=>{let t=this._transcript?ia(this._transcript):!0;t&&!this._wasEmpty&&(this._sent=!1),this._wasEmpty=t,this._setHidden(!t||this._sent)};_onConfigChange=()=>{let t=this.querySelector(".aparte-suggestions");t&&t.setAttribute("aria-label",this._groupLabel())};get suggestions(){return this._suggestions}set suggestions(t){this._suggestions=typeof t=="string"?Vr(t):Array.isArray(t)?t.filter(aa):[],this.isConnected&&this._render()}connectedCallback(){this.hasAttribute("suggestions")&&this._readAttribute(),this._render(),this._watchComposer(),window.addEventListener("aparte-config-change",this._onConfigChange)}disconnectedCallback(){this._composer?.removeEventListener("aparte-send",this._onSend),this._composer=null,this._transcriptObserver?.disconnect(),this._transcriptObserver=null,this._transcript=null,window.removeEventListener("aparte-config-change",this._onConfigChange)}attributeChangedCallback(t){this.isConnected&&(t==="suggestions"?(this._readAttribute(),this._render()):t==="target"?this._watchComposer():t==="empty-only"&&(this._watchTranscript(),this.hasAttribute("empty-only")||(this._sent=!1,this._setHidden(!1))))}_groupLabel(){return k(this).t("suggestionsLabel")||"Suggested prompts"}_parsed=null;_readAttribute(){let t=this.getAttribute("suggestions");t===null||t===this._parsed||(this._parsed=t,this._suggestions=Vr(t))}_resolveComposer(){let t=this.closest("aparte-composer");if(t)return t;let e=this.getAttribute("target");if(e){let i=document.getElementById(e)?.querySelector("aparte-composer");if(i)return i;for(let r of document.querySelectorAll("aparte-composer[target]"))if(r.getAttribute("target")===e)return r}return document.querySelector("aparte-composer")}_watchComposer(){this._composer?.removeEventListener("aparte-send",this._onSend),this._composer=this._resolveComposer(),this._composer?.addEventListener("aparte-send",this._onSend),this._watchTranscript()}_resolveTranscript(){let t=this.getAttribute("target")??this._composer?.getAttribute("target")??null,e=Z(this._composer)??Z(this)??(t?document.getElementById(t):null);return e?e.matches("aparte-chat-viewport")?e:e.querySelector("aparte-chat-viewport"):null}_watchTranscript(){let t=this.hasAttribute("empty-only")?this._resolveTranscript():null;t!==this._transcript&&(this._transcriptObserver?.disconnect(),this._transcriptObserver=null,this._transcript=t,t&&(this._transcriptObserver=new MutationObserver(this._applyEmptyOnly),this._transcriptObserver.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["loading"]}))),this.hasAttribute("empty-only")&&this._applyEmptyOnly()}_setHidden(t){if(t){if(this.hidden)return;this.hidden=!0,this._hidOwn=!0}else this._hidOwn&&(this.hidden=!1,this._hidOwn=!1)}_render(){if(this.replaceChildren(),this._suggestions.length===0){this.setAttribute("data-empty","");return}this.removeAttribute("data-empty");let t=document.createElement("div");t.className="aparte-suggestions",t.setAttribute("role","group"),t.setAttribute("aria-label",this._groupLabel());for(let e of this._suggestions){let s=document.createElement("button");s.type="button",s.className="aparte-btn aparte-btn--surface aparte-btn--pill aparte-suggestion",s.textContent=Yr(e);let i=Qr(e);i!==s.textContent&&(s.title=i),s.addEventListener("click",()=>this._activate(e)),t.appendChild(s)}this.appendChild(t)}_activate(t){let e={label:Yr(t),prompt:Qr(t)};if(!this.dispatchEvent(new CustomEvent("aparte-suggestion",{detail:e,bubbles:!0,composed:!0,cancelable:!0})))return;let i=this._composer??this._resolveComposer();if(!i){console.warn("[aparte-suggestions] no <aparte-composer> to send through \u2014 put the element inside one, or point `target` at the chat it serves.");return}i!==this._composer&&this._watchComposer();let r=this.contains(document.activeElement);i.setValue(e.prompt),this.getAttribute("mode")==="fill"?i.focus():(i.submit(),r&&i.focus())}};$(Ye);customElements.get("aparte-suggestions")||customElements.define("aparte-suggestions",Ye);var Xr=(n,t)=>{let e=Number(n);return n!==null&&Number.isFinite(e)&&e>0&&e<=1?e:t},Xl=n=>(n instanceof Element?n.closest("aparte-chat, [data-aparte-chat]"):null)?.id||void 0,U=(n,t,e)=>{let s=document.createElement(n);return s.className=t,e!==void 0&&(s.textContent=e),s},Jr="http://www.w3.org/2000/svg",Jl=()=>{let n=document.createElementNS(Jr,"svg");n.setAttribute("class","aparte-context__ring"),n.setAttribute("viewBox","0 0 36 36");for(let t of["track","value"]){let e=document.createElementNS(Jr,"circle");e.setAttribute("class",`aparte-context__${t}`),e.setAttribute("cx","18"),e.setAttribute("cy","18"),e.setAttribute("r","15.5"),t==="value"&&e.setAttribute("pathLength","100"),n.appendChild(e)}return n},Zr=n=>!!n&&typeof n.getMessages=="function",Zl=n=>{if(!n)return null;if(Zr(n))return n;let t=n.viewport??n.querySelector("aparte-chat-viewport");return Zr(t)?t:null},tc=0,ec={system:0,tools:0,summary:0,messages:0},Qe=class extends HTMLElement{static get observedAttributes(){return["window","warn","danger","target","variant","used"]}_used=null;_level=null;_compactRequested=!1;_lastDone=null;_viewChanged=!1;_blank=!1;_overflow=!1;_compact=null;_failure="";_open=!1;_measured=null;_seen=null;_panelSignature="";_remember(t){let e=t instanceof Element?Z(t):null;e&&(this._seen=e)}_onDone=t=>{let e=t.detail;!e?.usage||!this._isMine(e.targetId)||(this._remember(t.target),this._used=Me(e.usage),this._lastDone={messageId:e.messageId,usage:e.usage},this._viewChanged=!1,this._blank=!1,this._overflow=!1,this._render(!0))};_onReset=t=>{this._isMine(Xl(t.target))&&(this._remember(t.target),this._used=null,this._lastDone=null,this._viewChanged=!1,this._overflow=!1,this._compact=null,this._blank=!0,this._render())};_onLoaded=t=>{let e=t.detail;if(!this._isMine(e?.targetId))return;this._remember(t.target),this._blank=!1,this._lastDone=null,this._viewChanged=!1,this._overflow=!1,this._compact=null;let r=[...t.target?.getMessages?.()??[]].reverse().find(a=>a.role==="assistant"&&a.usage);this._used=r?.usage?Me(r.usage):null,this._render()};_onCompactStart=t=>{let e=t.detail;this._isMine(e?.targetId)&&(this._compact="running",this._failure="",this._render())};_onCompacted=t=>{let e=t.detail;if(this._isMine(e?.targetId)){if(this._compactRequested=!1,this._compact=null,e?.skipped){this._render();return}this._viewChanged=!0,this._overflow=!1,this._messages()||(this._used=null),this._render()}};_onCompactError=t=>{let e=t.detail;this._isMine(e?.targetId)&&(this._compactRequested=!1,this._compact=e?.aborted?null:"failed",this._failure=e?.aborted?"":typeof e?.error=="string"?e.error:"",this._render())};_onMessageError=t=>{let e=t.detail;this._isMine(e?.targetId)&&e?.error?.code===H.USAGE_CONTEXT_EXCEEDED&&(this._remember(t.target),this._overflow=!0,this._render())};_onRerender=()=>this._render();get used(){return this._measured?.used??this._used}set used(t){t==null?this.removeAttribute("used"):this.setAttribute("used",String(t))}get window(){return this._window()}set window(t){t==null?this.removeAttribute("window"):this.setAttribute("window",String(t))}get level(){return this._level}get measure(){return this._measured}connectedCallback(){window.addEventListener("aparte-message-done",this._onDone),window.addEventListener("aparte-message-error",this._onMessageError),window.addEventListener("aparte-compact-start",this._onCompactStart),window.addEventListener("aparte-compact-done",this._onCompacted),window.addEventListener("aparte-compact-error",this._onCompactError),window.addEventListener("aparte-reset-done",this._onReset),window.addEventListener("aparte-conversation-loaded",this._onLoaded),window.addEventListener("aparte-config-change",this._onRerender),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),this._render()}disconnectedCallback(){window.removeEventListener("aparte-message-done",this._onDone),window.removeEventListener("aparte-message-error",this._onMessageError),window.removeEventListener("aparte-compact-start",this._onCompactStart),window.removeEventListener("aparte-compact-done",this._onCompacted),window.removeEventListener("aparte-compact-error",this._onCompactError),window.removeEventListener("aparte-reset-done",this._onReset),window.removeEventListener("aparte-conversation-loaded",this._onLoaded),window.removeEventListener("aparte-config-change",this._onRerender),this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),this._stopListeningWhileOpen()}attributeChangedCallback(t){if(t==="used"){let e=Number(this.getAttribute("used"));this._used=this.hasAttribute("used")&&Number.isFinite(e)&&e>=0?e:null}this.isConnected&&this._render()}_cfg(){return k(this._chat()??this)}_window(){let t=Number(this.getAttribute("window"));if(this.hasAttribute("window")&&Number.isFinite(t)&&t>0)return t;let e=this._cfg().getCurrentModel();return e?.contextWindow&&e.contextWindow>0?e.contextWindow:null}_ownTargetId(){let t=this.getAttribute("target");if(t)return t;let e=this.parentElement;for(;e;){if((e.tagName.toLowerCase()==="aparte-chat"||e.hasAttribute("data-aparte-chat"))&&e.id)return e.id;e=e.parentElement}}_isMine(t){let e=this._ownTargetId();return!t||!e||t===e}_chat(){let t=this.getAttribute("target");if(t){let i=this.getRootNode().getElementById?.(t)??document.getElementById(t);if(i)return i}let e=Z(this);return e||(this._seen?.isConnected?this._seen:null)}_messages(){let t=Zl(this._chat());if(!t)return null;try{return t.getMessages()}catch{return null}}_measure(t){let e=this._messages(),s=this._lastDone,i=e&&s?.messageId?e.map(a=>a.id===s.messageId&&!a.usage?{...a,usage:s.usage}:a):e,r=!!i?.some(a=>a.role==="assistant"&&a.usage);return i&&(r&&!this._blank||this._overflow&&i.length>0)?Or({messages:i,config:this._cfg(),windowOverride:t,viewChanged:this._viewChanged}):this._used===null?null:{window:t,used:this._used,estimated:!1,parts:{...ec},other:this._used}}_render(t=!1){let e=this._window(),s=e===null?null:this._measure(e);if(this._compact?this.setAttribute("data-compact",this._compact):this.removeAttribute("data-compact"),e===null||s===null){this._measured=null,this.setAttribute("data-empty",""),this.removeAttribute("data-level"),this._open=!1,this._stopListeningWhileOpen(),this._panelSignature="",this.replaceChildren(),this._level=null;return}this._measured=s,this.removeAttribute("data-empty");let i=s.used,r=Math.min(1,i/e),a=Xr(this.getAttribute("warn"),.75),o=Xr(this.getAttribute("danger"),.9),l=this._overflow||r>=o?"danger":r>=a?"warn":"ok";this.setAttribute("data-level",l);let c=this.getAttribute("variant")==="ring",d=this.querySelector(".aparte-context");d&&d.classList.contains("aparte-context--ring")!==c&&(this.replaceChildren(),d=null,this._panelSignature="");let u=this.querySelector('[role="meter"]'),h=this.querySelector(".aparte-context__text"),f=this.querySelector(".aparte-context__toggle"),_=this.querySelector(".aparte-context__name"),p=this.querySelector(".aparte-context__panel");(!d||!u||!h||!f||!_||!p)&&(d=U("div",c?"aparte-context aparte-context--ring":"aparte-context"),u=c?Jl():U("div","aparte-progress"),u.setAttribute("role","meter"),c||u.appendChild(U("div","aparte-progress__bar")),f=U("button","aparte-btn aparte-btn--ghost aparte-btn--sm aparte-context__toggle"),f.type="button",_=U("span","aparte-sr-only"),_.classList.add("aparte-context__name"),h=U("span","aparte-context__text"),f.append(_,h),p=U("div","aparte-context__panel aparte-popover"),p.id=`aparte-context-panel-${++tc}`,p.setAttribute("role","group"),p.hidden=!0,f.setAttribute("aria-controls",p.id),d.append(u,f,p),this.replaceChildren(d),this._panelSignature="");let m=this._cfg(),T=m.getLocale().tag||void 0,x=new Intl.NumberFormat(T,{notation:"compact",maximumFractionDigits:1}),R=s.estimated?"~":"",b=`${R}${x.format(i)} / ${x.format(e)}`,y=Math.round(r*100),g=m.t("contextLabel")||"Context window";if(c){let w=u.querySelector(".aparte-context__value");w?.style.setProperty("--aparte-context-ratio",String(y)),w?.classList.toggle("aparte-context__value--empty",y===0),d.title=b}else u.style.setProperty("--aparte-progress-value",String(y));if(u.setAttribute("aria-valuemin","0"),u.setAttribute("aria-valuemax",String(e)),u.setAttribute("aria-valuenow",String(i)),u.setAttribute("aria-label",`${g}: ${b}`),_.textContent=`${g}: `,f.setAttribute("aria-expanded",String(this._open)),h.textContent=c?`${R}${new Intl.NumberFormat(T,{style:"percent",maximumFractionDigits:0}).format(y/100)}`:b,p.setAttribute("aria-label",g),p.hidden=!this._open,this._open?this._renderPanel(p,s,e,x):this._panelSignature="",l!==this._level){this._level=l;let w=this._ownTargetId(),E={level:l,used:i,window:e,ratio:r,targetId:w};this.dispatchEvent(new CustomEvent("aparte-context-threshold",{detail:E,bubbles:!0,composed:!0})),l!=="danger"&&(this._compactRequested=!1)}t&&l==="danger"&&this.hasAttribute("auto-compact")&&!this._compactRequested&&(this._compactRequested=!0,window.dispatchEvent(new CustomEvent("aparte-compact",{detail:{targetId:this._ownTargetId(),auto:!0,window:e}})))}_renderPanel(t,e,s,i){let r=this._cfg(),a=r.getCompactor(),o=this._chat(),l=this._ownTargetId(),c=null;try{c=a?.preview?.({target:o,...l?{targetId:l}:{}})??null}catch{c=null}let{parts:d,used:u}=e,h=d.system+d.tools+d.summary+d.messages,f=h>u&&h>0?u/h:1,_=e.estimated?"~":"",p=[{key:"system",label:r.t("contextSystem")||"System prompt",tokens:d.system*f,approx:"~"},{key:"tools",label:r.t("contextTools")||"Tools",tokens:d.tools*f,approx:"~"},{key:"summary",label:r.t("contextSummary")||"Summary",tokens:d.summary*f,approx:"~"},{key:"messages",label:r.t("contextMessages")||"Messages",tokens:d.messages*f,approx:"~"},{key:"other",label:r.t("contextOther")||"Other",tokens:f<1?0:e.other,approx:"~"},{key:"free",label:r.t("contextFree")||"Free",tokens:Math.max(0,s-u),approx:_}],m=`${_}${i.format(u)} / ${i.format(s)}`,T=c&&c.tokens>0?(r.t("contextReclaim")||"Compacting now would free ~{n} tokens").replace("{n}",()=>i.format(Math.round(c.tokens))):"",x=!!a&&!!c&&this._compact===null,R=U("ul","aparte-context__rows");for(let v of p){let S=U("li","aparte-context__row");S.setAttribute("data-part",v.key),S.append(U("span","aparte-context__row-label",v.label)),S.append(U("span","aparte-context__row-value",`${v.approx}${i.format(Math.round(v.tokens))}`));let L=U("div","aparte-progress aparte-context__row-bar");L.setAttribute("aria-hidden","true"),L.style.setProperty("--aparte-progress-value",String(Math.round(Math.min(1,v.tokens/s)*100))),L.appendChild(U("div","aparte-progress__bar")),S.append(L),R.append(S)}let b=U("li","aparte-context__row aparte-context__row--total");b.setAttribute("data-part","total"),b.append(U("span","aparte-context__row-label",r.t("contextTotal")||"Total"),U("span","aparte-context__row-value",m)),R.append(b);let y=[R];if(this._compact==="running"){let v=U("p","aparte-context__status aparte-shimmer",r.t("checkpointPending")||"Summarising the context\u2026");v.setAttribute("role","status"),y.push(v)}else if(this._compact==="failed"){let v=U("p","aparte-context__status aparte-context__status--failed",r.t("checkpointFailed")||"Couldn't summarise the context");v.setAttribute("role","status"),this._failure&&(v.title=this._failure,v.appendChild(U("span","aparte-sr-only",`: ${this._failure}`))),y.push(v,this._action("retry",r.t("retry")||"Retry"))}T&&y.push(U("p","aparte-context__reclaim",T)),x&&y.push(this._action("compact",r.t("contextCompactNow")||"Compact now"));let g=U("div","aparte-context__content");if(g.append(...y),g.innerHTML===this._panelSignature)return;this._panelSignature=g.innerHTML;let w=document.activeElement,E=w&&t.contains(w)?w.getAttribute("data-context-action")??"":null;t.replaceChildren(...Array.from(g.childNodes)),E!==null&&((E?t.querySelector(`[data-context-action="${z(E)}"]`):null)??this.querySelector(".aparte-context__toggle"))?.focus()}_action(t,e){let s=U("button","aparte-btn aparte-btn--sm aparte-btn--surface aparte-context__action",e);return s.type="button",s.setAttribute("data-context-action",t),s}async _compactNow(t){let e=this._cfg().getCompactor(),s=this._ownTargetId();if(!e){window.dispatchEvent(new CustomEvent("aparte-compact",{detail:{targetId:s}}));return}this._compact="running",this._failure="",this._render();let i=null;try{let r=await e.compact({target:this._chat(),...s?{targetId:s}:{},force:!0,reason:t});r.ok?r.skipped||(this._viewChanged=!0):i=r.error}catch(r){i=r instanceof Error?r.message:String(r)}this._compact==="running"&&(this._compact=i===null?null:"failed",this._failure=i??""),this.isConnected&&this._render()}_onClick=t=>{let e=t.target,s=e?.closest?.("[data-context-action]");if(s){this._compactNow(s.getAttribute("data-context-action")==="retry"?"retry":"manual");return}e?.closest?.(".aparte-context__panel")||e?.closest?.(".aparte-context")&&this._setOpen(!this._open)};_setOpen(t,e=!1){t!==this._open&&(this._open=t,t?this._listenWhileOpen():this._stopListeningWhileOpen(),this._render(),t?this._place():e&&this.querySelector(".aparte-context__toggle")?.focus())}_onDocumentClick=t=>{t.composedPath().includes(this)||this._setOpen(!1)};_onKeydown=t=>{!this._open||t.key!=="Escape"||(t.preventDefault(),t.stopPropagation(),this._setOpen(!1,!0))};_onDocumentKeydown=t=>{t.key==="Escape"&&this._setOpen(!1,this.contains(document.activeElement))};_listenWhileOpen(){document.addEventListener("click",this._onDocumentClick),document.addEventListener("keydown",this._onDocumentKeydown)}_stopListeningWhileOpen(){document.removeEventListener("click",this._onDocumentClick),document.removeEventListener("keydown",this._onDocumentKeydown)}_place(){let t=this.querySelector(".aparte-context__panel");if(!t)return;t.removeAttribute("data-placement"),t.removeAttribute("data-align");let e=this.getBoundingClientRect(),s=t.getBoundingClientRect();s.height>0&&e.top<s.height&&t.setAttribute("data-placement","below"),s.width>0&&s.right>document.documentElement.clientWidth&&t.setAttribute("data-align","end")}};$(Qe);customElements.get("aparte-context")||customElements.define("aparte-context",Qe);var ta=60,sc=6,nc=150,ic=4,rc=1,Xe=class extends HTMLElement{static get observedAttributes(){return["target","every"]}_host=null;_mutations=null;_resizes=null;_intersections=null;_observedBubbles=[];_observedSurface=null;_rebuildQueued=!1;_pickQueued=!1;_currentId=null;_visible=new Map;_onScreen=new Set;_onScreenObserver=null;_held=null;_settleTimer=null;_settleSurface=null;_alignPasses=0;_written=new Map;_onConfigChange=()=>this._rebuild();_onSurfaceScroll=()=>this._bumpSettle();get currentMessageId(){return this._currentId}connectedCallback(){this.classList.contains("aparte-scroll-rail")||this.classList.add("aparte-scroll-rail"),this.getAttribute("role")||this.setAttribute("role","navigation"),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),window.addEventListener("aparte-config-change",this._onConfigChange),this._attach()}disconnectedCallback(){this._detach(),this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),window.removeEventListener("aparte-config-change",this._onConfigChange)}attributeChangedCallback(t){this.isConnected&&(t==="target"?this._attach():this._rebuild())}_findHost(){let t=this.getAttribute("target");if(t)return document.getElementById(t);let e=this.parentElement;for(;e;){if(e.tagName.toLowerCase()==="aparte-chat"||e.hasAttribute("data-aparte-chat"))return e;e=e.parentElement}return null}_attach(){if(this._detach(),this._host=this._findHost(),!this._host){this._rebuild();return}if(typeof MutationObserver<"u"&&(this._mutations=new MutationObserver(t=>{t.some(e=>!this.contains(e.target))&&this._queueRebuild()}),this._mutations.observe(this._host,{childList:!0,subtree:!0,characterData:!0})),typeof ResizeObserver<"u"){this._resizes=new ResizeObserver(()=>this._layout()),this._resizes.observe(this._host);let t=this._viewport();t&&this._resizes.observe(t)}this._rebuild()}_detach(){this._mutations?.disconnect(),this._mutations=null,this._resizes?.disconnect(),this._resizes=null,this._unobserve(),this._release(),this._host=null}_queueRebuild(){this._rebuildQueued||(this._rebuildQueued=!0,requestAnimationFrame(()=>{this._rebuildQueued=!1,this._rebuild()}))}_viewport(){return this._host?.querySelector("aparte-chat-viewport")??null}_scrollSurface(){let t=this._viewport();return t?t.querySelector(".aparte-viewport-container")??t:null}_bubbles(){let t=this._viewport();if(!t)return[];let e=this.getAttribute("every")==="message"?"message":"user",s=Array.from(t.querySelectorAll("aparte-chat-bubble[message-id]"));return e==="message"?s:s.filter(i=>i.getAttribute("data-role")==="user")}_excerpt(t){let s=((t.querySelector(".aparte-message-content")??t).textContent??"").replace(/\s+/g," ").trim();return s.length>ta?`${s.slice(0,ta-1).trimEnd()}\u2026`:s}_tickLabel(t){let e=k(this).getLocale(),s=t.getAttribute("data-role")==="user"?e.roleNameUser??"You":e.roleNameAssistant??"Assistant",i=this._excerpt(t);return i?`${s}: ${i}`:s}_list(){return this.querySelector(":scope > .aparte-scroll-rail__list")}_rebuild(){let t=this._bubbles(),s=k(this).getLocale().scrollRailLabel??"Conversation outline";if(this.getAttribute("aria-label")!==s&&this.setAttribute("aria-label",s),t.length<2){this.setAttribute("data-empty",""),this.replaceChildren(),this._unobserve(),this._currentId=null,this._write("--aparte-scroll-rail-hit-size","");return}this.removeAttribute("data-empty");let i=this._list();i||(i=document.createElement("ol"),i.className="aparte-scroll-rail__list",this.replaceChildren(i));let r=new Map;for(let l of Array.from(i.children)){let c=l.firstElementChild instanceof HTMLElement?l.firstElementChild.dataset.messageId:void 0;c&&r.set(c,l)}let a=new Set,o=0;for(let l of t){let c=l.getAttribute("message-id");a.add(c);let d=r.get(c);if(d)r.delete(c);else{d=document.createElement("li");let _=document.createElement("button");_.type="button",_.className="aparte-scroll-rail__tick",_.dataset.messageId=c,d.appendChild(_)}let u=d.firstElementChild,h=this._tickLabel(l);u.getAttribute("aria-label")!==h&&(u.setAttribute("aria-label",h),u.title=h),c===this._currentId?u.getAttribute("aria-current")!=="true"&&u.setAttribute("aria-current","true"):u.removeAttribute("aria-current");let f=i.children[o]??null;f!==d&&i.insertBefore(d,f),o++}for(let l of r.values())l.remove();this._currentId&&!a.has(this._currentId)&&(this._currentId=null),ac(this._observedBubbles,t)||this._observe(t),this._layout()}_observe(t){if(this._unobserve(),this._observedBubbles=t,typeof IntersectionObserver>"u")return;let e=this._scrollSurface();if(e){this._intersections=new IntersectionObserver(s=>{for(let i of s){let r=i.target.getAttribute("message-id");r&&this._visible.set(r,i.isIntersecting?i.intersectionRatio:0)}this._pickCurrent()},{root:e,rootMargin:"0px 0px -70% 0px",threshold:[0,.1,.25,.5,.75,1]}),this._onScreenObserver=new IntersectionObserver(s=>{for(let i of s){let r=i.target.getAttribute("message-id");r&&(i.isIntersecting?this._onScreen.add(r):this._onScreen.delete(r))}this._pickCurrent()},{root:e,threshold:[0]});for(let s of t)this._intersections.observe(s),this._onScreenObserver.observe(s);this._observedSurface=e,e.addEventListener("scroll",this._onRootScroll,{passive:!0})}}_unobserve(){this._intersections?.disconnect(),this._intersections=null,this._onScreenObserver?.disconnect(),this._onScreenObserver=null,this._observedSurface?.removeEventListener("scroll",this._onRootScroll),this._observedSurface=null,this._observedBubbles=[],this._visible.clear(),this._onScreen.clear()}_onRootScroll=()=>{this._pickQueued||(this._pickQueued=!0,requestAnimationFrame(()=>{this._pickQueued=!1,this._pickCurrent()}))};_atBottom(){let t=this._observedSurface;if(!t)return!1;let e=t.scrollHeight-t.clientHeight;return e>0&&e-t.scrollTop<=2}_pickCurrent(){if(this._held)return;let t=this._observedBubbles;if(t.length===0)return;let e=t[t.length-1].getAttribute("message-id");if(this._atBottom()||this._onScreen.has(e)){this._setCurrent(e);return}let s=null;for(let i of t){let r=i.getAttribute("message-id");(this._visible.get(r)??0)>0&&(s=r)}s!==null&&this._setCurrent(s)}_setCurrent(t){if(this._currentId!==t){this._currentId=t;for(let e of this.querySelectorAll(".aparte-scroll-rail__tick"))e.dataset.messageId===t?(e.setAttribute("aria-current","true"),this._reveal(e)):e.removeAttribute("aria-current")}}_reveal(t){let e=this.clientHeight;if(!e)return;let s=t.offsetTop,i=s+t.offsetHeight;s<this.scrollTop?this.scrollTop=s:i>this.scrollTop+e&&(this.scrollTop=i-e)}_write(t,e){this._written.get(t)!==e&&(this._written.set(t,e),e?this.style.setProperty(t,e):this.style.removeProperty(t))}_layout(){let t=this._host,e=this._viewport(),s=this._scrollSurface();if(t&&s&&this._write("--aparte-scroll-rail-bar",`${Math.max(0,s.offsetWidth-s.clientWidth)}px`),t&&e){let u=e.getBoundingClientRect(),h=t.getBoundingClientRect();u.height>0&&h.height>0&&(this._write("--aparte-scroll-rail-block-start",`${Math.max(0,Math.round(u.top-h.top))}px`),this._write("--aparte-scroll-rail-block-end",`${Math.max(0,Math.round(h.bottom-u.bottom))}px`))}let i=this._list()?.children.length??0,r=this.clientHeight;if(!i||!r){this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap","");return}let a=t??document.documentElement,o=getComputedStyle(a),l=parseFloat(o.getPropertyValue("--aparte-scroll-rail-hit-size"))||24,c=parseFloat(o.getPropertyValue("--aparte-scroll-rail-tick-thickness"))||2;if(i*l<=r){this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap","");return}let d=Math.max(sc,Math.floor(r/i));this._write("--aparte-scroll-rail-hit-size",`${d}px`),this._write("--aparte-scroll-rail-gap",`${Math.max(0,d-c)}px`)}_onClick=t=>{let e=t.target.closest(".aparte-scroll-rail__tick");if(!e||!this.contains(e))return;let s=e.dataset.messageId;s&&this.jumpTo(s)};_onKeydown=t=>{if(t.key!=="ArrowDown"&&t.key!=="ArrowUp"&&t.key!=="Home"&&t.key!=="End")return;let e=Array.from(this.querySelectorAll(".aparte-scroll-rail__tick")),s=e.indexOf(pt(this));if(s===-1)return;t.preventDefault();let i=t.key==="Home"?0:t.key==="End"?e.length-1:t.key==="ArrowDown"?Math.min(e.length-1,s+1):Math.max(0,s-1);e[i]?.focus()};jumpTo(t){if(!this.dispatchEvent(new CustomEvent("aparte-scroll-rail-jump",{detail:{messageId:t},bubbles:!0,composed:!0,cancelable:!0})))return;let s=this._bubbleOf(t);s&&(this._viewport()?.setAutoScroll?.(!1),this._scrollTo(s),this._setCurrent(t),this._hold(t))}_bubbleOf(t){return this._viewport()?.querySelector(`aparte-chat-bubble[message-id="${z(t)}"]`)??null}_scrollTo(t){let e=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches;t.scrollIntoView({block:"start",behavior:e?"auto":"smooth"})}_hold(t){this._release(),this._held=t,this._alignPasses=0,this._settleSurface=this._scrollSurface(),this._settleSurface?.addEventListener("scroll",this._onSurfaceScroll),this._bumpSettle()}_bumpSettle(){this._settleTimer!==null&&clearTimeout(this._settleTimer),this._settleTimer=setTimeout(()=>this._settle(),nc)}_settle(){let t=this._held,e=this._settleSurface,s=t?this._bubbleOf(t):null;if(t&&s&&e&&this._alignPasses<ic){let i=e.getBoundingClientRect().top+(parseFloat(getComputedStyle(e).scrollPaddingTop)||0),r=s.getBoundingClientRect().top-i;if(Math.abs(r)>rc){this._alignPasses++,this._scrollTo(s),this._bumpSettle();return}}this._release(),t&&this._setCurrent(t)}_release(){this._settleTimer!==null&&clearTimeout(this._settleTimer),this._settleTimer=null,this._settleSurface?.removeEventListener("scroll",this._onSurfaceScroll),this._settleSurface=null,this._held=null}};function ac(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}$(Xe);customElements.get("aparte-scroll-rail")||customElements.define("aparte-scroll-rail",Xe);var oc="(max-width: 48rem)",Je=class extends HTMLElement{static get observedAttributes(){return["collapsed","breakpoint"]}_media=null;_scrim=null;_opener=null;_lastCollapsed=null;_ready=!1;_closedByHost=!1;_hostIntentSeeded=!1;_auto=!1;_ownHidden=!1;_query="";_listWatch=null;get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",K(t))}get drawer(){return this.hasAttribute("data-drawer")}connectedCallback(){this.classList.contains("aparte-sidebar")||this.classList.add("aparte-sidebar"),this.getAttribute("role")||this.setAttribute("role","complementary"),this._relabel(),this._hostIntentSeeded||(this._closedByHost=this.collapsed,this._hostIntentSeeded=!0),this.addEventListener("input",this._onInput),typeof MutationObserver=="function"&&(this._listWatch=new MutationObserver(t=>{t.some(e=>e.target!==this)&&this._syncNoMatch()}),this._listWatch.observe(this,{subtree:!0,attributes:!0,attributeFilter:["data-no-match","loading"]})),document.addEventListener("keydown",this._onKeydown),document.addEventListener("click",this._onDocumentClick),window.addEventListener("aparte-config-change",this._onConfigChange),this._watchBreakpoint(),this._syncHidden(),this._lastCollapsed=this.collapsed,this.id||(this.id=`aparte-sidebar-${++lc}`),this._syncToggles(),this._ready=!0}_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t==="none"){this._applyDrawer(!1);return}if(typeof matchMedia!="function")return;let e=t?`(max-width: ${t})`:oc;this._media=matchMedia(e),this._media.addEventListener("change",this._onMediaChange),this._applyDrawer(this._media.matches)}disconnectedCallback(){this.removeEventListener("input",this._onInput),this._listWatch?.disconnect(),this._listWatch=null,document.removeEventListener("keydown",this._onKeydown),document.removeEventListener("click",this._onDocumentClick),window.removeEventListener("aparte-config-change",this._onConfigChange),this._media?.removeEventListener("change",this._onMediaChange),this._media=null,this._ready=!1}attributeChangedCallback(t){if(!this._ready)return;if(t==="breakpoint"){this._watchBreakpoint();return}if(t!=="collapsed")return;let e=this.collapsed;e!==this._lastCollapsed&&(this._lastCollapsed=e,!this._auto&&!this.drawer&&(this._closedByHost=e),this._syncScrim(),this._syncHidden(),this._syncToggles(),e&&this.drawer&&this._opener?.isConnected?(this._opener.focus(),this._opener=null):!e&&this.drawer&&this._focusFirst(),this.dispatchEvent(new CustomEvent("aparte-sidebar-toggle",{detail:{collapsed:e,drawer:this.drawer},bubbles:!0,composed:!0})))}open(t){t&&(this._opener=t),this.collapsed=!1}close(){this.collapsed=!0}toggle(t){this.collapsed?this.open(t):this.close()}_onMediaChange=t=>this._applyDrawer(t.matches);_applyDrawer(t){let e=this.drawer;this.toggleAttribute("data-drawer",t),this._auto=!0;try{t&&!e?this.collapsed=!0:!t&&e&&!this._closedByHost&&(this.collapsed=!1)}finally{this._auto=!1}this._syncScrim(),this._syncHidden(),this._syncToggles()}_syncToggles(){let t="[data-aparte-sidebar-toggle]",e=yt(this),s=e===document?Array.from(document.querySelectorAll(t)):[...e.querySelectorAll(t),...document.querySelectorAll(t)];for(let i of s)this._drives(i)&&(i.setAttribute("aria-expanded",String(!this.collapsed)),i.setAttribute("aria-controls",this.id))}_drives(t){let e=t.getAttribute("data-aparte-sidebar-toggle");return e?e===this.id:dc(t)===this}_syncHidden(){this.collapsed?(this.toggleAttribute("inert",!0),this.setAttribute("aria-hidden","true"),this._ownHidden=!0):this._ownHidden&&(this.removeAttribute("inert"),this.removeAttribute("aria-hidden"),this._ownHidden=!1)}_focusFirst(){ea(this)[0]?.focus()}_syncScrim(){let t=this.drawer&&!this.collapsed;t&&!this._scrim?(this._scrim=document.createElement("div"),this._scrim.className="aparte-sidebar__scrim",this._scrim.setAttribute("aria-hidden","true"),this._scrim.addEventListener("click",()=>this.close()),this.appendChild(this._scrim)):!t&&this._scrim&&(this._scrim.remove(),this._scrim=null)}_onKeydown=t=>{if(!(!this.drawer||this.collapsed)){if(t.key==="Escape"){t.preventDefault(),this.close();return}if(t.key==="Tab"){let e=ea(this);if(e.length===0)return;let s=e[0],i=e[e.length-1],r=pt(this);this.contains(r)?t.shiftKey&&r===s?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),s.focus()):(t.preventDefault(),s.focus())}}};_onDocumentClick=t=>{let e=ht(t)?.closest?.("[data-aparte-sidebar-toggle]");e&&this._drives(e)&&this.toggle(e)};_onInput=t=>{let e=t.target;e?.matches?.("[data-aparte-sidebar-search]")&&this.filter(e.value)};filter(t){this._query=t;let e=0,s=!1;for(let i of this._lists())typeof i.filter=="function"?e+=i.filter(t):(e+=fn(i,Ke(t)),s=!0);return s&&typeof customElements<"u"&&customElements.whenDefined("aparte-conversation-list").then(()=>{if(this._query===t)for(let i of this._lists())i.filter?.(t);this._syncNoMatch()}),this._syncNoMatch(),e}_lists(){return Array.from(this.querySelectorAll("aparte-conversation-list"))}_syncNoMatch(){let t=Ke(this._query),e=t!==""&&this._lists().every(s=>typeof s.filter=="function"?s.hasAttribute("data-no-match"):!s.hasAttribute("loading")&&fn(s,t)===0);this.toggleAttribute("data-no-match",e)}_onConfigChange=()=>this._relabel();_relabel(){if(this.hasAttribute("aria-label")&&this.dataset.ownLabel!=="locale")return;let t=k(this).getLocale();this.setAttribute("aria-label",t.sidebarLabel??"Conversations"),this.dataset.ownLabel="locale"}},lc=0,cc=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function ea(n){return Array.from(n.querySelectorAll(cc)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}function dc(n){return n.closest("aparte-sidebar")??yt(n).querySelector("aparte-sidebar")??document.querySelector("aparte-sidebar")}$(Je);customElements.get("aparte-sidebar")||customElements.define("aparte-sidebar",Je);function sa(n,t,e){return Number.isFinite(n)?n<t?t:n>e?e:n:t}function uc(n){let t=Number.isFinite(n.startPercent)?n.startPercent:0;if(!Number.isFinite(n.containerPx)||n.containerPx<=0)return sa(t,0,100);let i=((!n.vertical&&n.rtl)!==(n.primaryEnd===!0)?-1:1)*n.deltaPx*100/n.containerPx;return sa(t+i,0,100)}function na(n,t,e,s,i=!1){if(n==="Home")return-100;if(n==="End")return 100;let r=(t?10:1)*(i?-1:1);return s?n==="ArrowUp"?-r:n==="ArrowDown"?r:null:n==="ArrowLeft"?e?r:-r:n==="ArrowRight"?e?-r:r:null}var hc="(max-width: 48rem)",Xt=38,pc=300;function Jt(n,t){let e=Number.parseFloat(n??"");return Number.isFinite(e)?e<0?0:e>100?100:e:t}var Ze=class n extends HTMLElement{static get observedAttributes(){return["position","orientation","primary","collapsed","breakpoint","pane","disabled","label","single"]}_handle=null;_scrim=null;_media=null;_observer=null;_measureRafId=null;_observedPx=0;static _paneIdSeq=0;_position=Xt;_initialPosition=Xt;_initialCaptured=!1;_preCollapsePosition=null;_lastPosition=null;_lastCollapsed=null;_lastPane=null;_source="api";_ready=!1;_dragging=!1;_captured=!1;_moved=!1;_pointerId=null;_dragStartPercent=Xt;_dragOriginPx=0;_dragContainerPx=0;_keying=!1;get position(){return this._position}set position(t){let e=Jt(String(t),this._position);this.isConnected&&e===this._lastPosition||(this._position=e,this._setLive(e),this.isConnected&&this._commit("api"))}get orientation(){return this.getAttribute("orientation")==="vertical"?"vertical":"horizontal"}set orientation(t){this.setAttribute("orientation",t)}get primary(){return this.getAttribute("primary")==="end"?"end":"start"}set primary(t){this.setAttribute("primary",t)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",K(t))}get pane(){return this.getAttribute("pane")==="end"?"end":"start"}set pane(t){this.setAttribute("pane",t)}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",K(t))}get stacked(){return this.hasAttribute("data-stacked")||this.hasAttribute("single")||this.classList.contains("aparte-split--only-start")||this.classList.contains("aparte-split--only-end")}get single(){return this.hasAttribute("single")}set single(t){this.toggleAttribute("single",K(t))}collapse(){this.collapsed=!0}expand(){this.collapsed=!1}toggleCollapse(){this.collapsed=!this.collapsed}showPane(t){this.pane=t}reset(){this._position=this._initialPosition,this._setLive(this._position),this.isConnected&&this._commit("api")}connectedCallback(){this.classList.contains("aparte-split")||this.classList.add("aparte-split"),this._handle=this._ensureHandle();let t=this.getAttribute("position");t!==null?(this._position=Jt(t,Xt),this._setLive(this._position)):this._position=Jt(getComputedStyle(this).getPropertyValue("--aparte-split-position"),Xt),this._initialCaptured||(this._initialPosition=this._position,this._initialCaptured=!0),this.collapsed&&(this._lastCollapsed!==!0&&(this._preCollapsePosition=this._position),this._position=0,this._setLive(0)),this._lastPosition=this._position,this._lastCollapsed=this.collapsed,this._lastPane=this.pane,this._stampHandle(),this._relabel(),this._measureBounds(),this._handle.addEventListener("pointerdown",this._onPointerDown),this._handle.addEventListener("dblclick",this._onDoubleClick),this._handle.addEventListener("focusout",this._onFocusOut),this.addEventListener("keydown",this._onKeydown),this.addEventListener("keyup",this._onKeyup),document.addEventListener("click",this._onDocumentClick),window.addEventListener("aparte-config-change",this._onConfigChange),this._watchBreakpoint(),this._watchSize(),this._ready=!0,this._syncPaneControls()}disconnectedCallback(){this._handle?.removeEventListener("pointerdown",this._onPointerDown),this._handle?.removeEventListener("dblclick",this._onDoubleClick),this._handle?.removeEventListener("focusout",this._onFocusOut),this.removeEventListener("keydown",this._onKeydown),this.removeEventListener("keyup",this._onKeyup),document.removeEventListener("click",this._onDocumentClick),window.removeEventListener("aparte-config-change",this._onConfigChange),this._releasePointer(),this._media?.removeEventListener("change",this._onMediaChange),this._media=null,this._observer?.disconnect(),this._observer=null,this._measureRafId!==null&&(cancelAnimationFrame(this._measureRafId),this._measureRafId=null),this._removeScrim(),this._handle?.removeAttribute("data-dragging"),this._dragging=!1,this._keying=!1,this._ready=!1}attributeChangedCallback(t){if(this._ready)switch(t){case"position":{let e=Jt(this.getAttribute("position"),this._position);if(e===this._lastPosition)return;this._position=e,this._setLive(e),this._commit();return}case"collapsed":{let e=this.collapsed;if(e===this._lastCollapsed)return;this._lastCollapsed=e,e?(this._preCollapsePosition=this._position,this._position=0):this._position=this._preCollapsePosition??this._initialPosition,this._setLive(this._position),this._commit();return}case"pane":{let e=this.pane;if(this._syncPaneControls(),e===this._lastPane)return;this._lastPane=e,this._commit();return}case"orientation":case"primary":this._stampHandle(),this._measureBounds();return;case"disabled":this.disabled&&this._dragging&&this._endDrag("pointer",this._dragStartPercent),this._stampHandle();return;case"single":this.single&&this._dragging&&this._endDrag("pointer",this._dragStartPercent),this._stampHandle(),this._syncPaneControls();return;case"breakpoint":this._watchBreakpoint();return;case"label":this._relabel()}}_ensureHandle(){let t=Array.from(this.children).find(i=>i instanceof HTMLElement&&i.classList.contains("aparte-split__handle"));if(t){if(this.children[1]!==t){let i=Array.from(this.children).filter(r=>r!==t)[1]??null;this.insertBefore(t,i)}return t}let e=document.createElement("div");e.className="aparte-split__handle";let s=this.children[1]??null;return s?this.insertBefore(e,s):this.appendChild(e),e}_panes(){return Array.from(this.children).filter(t=>t instanceof HTMLElement&&!t.classList.contains("aparte-split__handle"))}_primaryPane(){let t=this._panes();return(this.primary==="end"?t[t.length-1]:t[0])??null}_stampHandle(){let t=this._handle;if(!t)return;t.setAttribute("role","separator"),t.setAttribute("aria-orientation",this.orientation==="vertical"?"horizontal":"vertical"),this.disabled||this.stacked?t.removeAttribute("tabindex"):t.setAttribute("tabindex","0"),t.setAttribute("aria-valuenow",String(Math.round(this._achievedPercent())));let e=this._primaryPane();e&&(e.id||(e.id=`aparte-split-pane-${++n._paneIdSeq}`),t.setAttribute("aria-controls",e.id))}_measure(t){let e=t.getBoundingClientRect();return this.orientation==="vertical"?e.height:e.width}_achievedPercent(){if(this.stacked)return this._position;let t=this._measure(this),e=this._primaryPane();return!e||!(t>0)?this._position:Math.max(0,Math.min(100,this._measure(e)/t*100))}_measureBounds(){let t=this._handle;if(!t||this._dragging||this.stacked)return;let e=this._primaryPane(),s=this._measure(this);if(!e||!(s>0)){t.setAttribute("aria-valuemin","0"),t.setAttribute("aria-valuemax","100");return}let i=this.style.getPropertyValue("--aparte-split-position");this.style.setProperty("--aparte-split-position","0%");let r=this._measure(e)/s*100;this.style.setProperty("--aparte-split-position","100%");let a=this._measure(e)/s*100;i?this.style.setProperty("--aparte-split-position",i):this.style.removeProperty("--aparte-split-position"),t.setAttribute("aria-valuemin",String(Math.round(r))),t.setAttribute("aria-valuemax",String(Math.round(a))),t.setAttribute("aria-valuenow",String(Math.round(this._achievedPercent())))}_watchSize(){typeof ResizeObserver=="function"&&(this._observer=new ResizeObserver(()=>{let t=this._measure(this);Math.abs(t-this._observedPx)<=1||(this._observedPx=t,this._measureRafId===null&&(this._measureRafId=requestAnimationFrame(()=>{this._measureRafId=null,this._measureBounds()})))}),this._observer.observe(this))}_setLive(t){this.style.setProperty("--aparte-split-position",`${Math.round(t*1e3)/1e3}%`)}_commit(t=this._source){let e=Math.round(this._achievedPercent());this._position=e,this._setLive(e),this._lastPosition=e,this.getAttribute("position")!==String(e)&&this.setAttribute("position",String(e)),this._handle?.setAttribute("aria-valuenow",String(e)),this.dispatchEvent(new CustomEvent("aparte-split-resize",{detail:{position:e,collapsed:this.collapsed,stacked:this.stacked,pane:this.pane,orientation:this.orientation,source:t},bubbles:!0,composed:!0}))}_rtl(){return getComputedStyle(this).direction==="rtl"}_onPointerDown=t=>{this.disabled||this.stacked||this._dragging||t.button>0||(t.preventDefault(),this._handle?.focus(),this._dragging=!0,this._captured=!1,this._moved=!1,this._pointerId=t.pointerId,this._dragStartPercent=this._position,this._dragOriginPx=this.orientation==="vertical"?t.clientY:t.clientX,this._dragContainerPx=this._measure(this),this._handle?.setAttribute("data-dragging",""),this._addScrim(),window.addEventListener("pointermove",this._onPointerMove),window.addEventListener("pointerup",this._onPointerUp),window.addEventListener("pointercancel",this._onPointerCancel))};_isOurPointer(t){return this._pointerId===null||t.pointerId===this._pointerId}_onPointerMove=t=>{if(!this._dragging||!this._isOurPointer(t))return;if(t.buttons===0){this._endDrag("pointer");return}if(!this._captured&&this._pointerId!==null){this._captured=!0;try{this._handle?.setPointerCapture(this._pointerId)}catch{}}let e=this.orientation==="vertical"?t.clientY:t.clientX;this._position=uc({startPercent:this._dragStartPercent,deltaPx:e-this._dragOriginPx,containerPx:this._dragContainerPx,rtl:this._rtl(),vertical:this.orientation==="vertical",primaryEnd:this.primary==="end"}),this._moved=!0,this._setLive(this._position)};_onPointerUp=t=>{this._isOurPointer(t)&&this._endDrag("pointer")};_onPointerCancel=t=>{this._isOurPointer(t)&&this._endDrag("pointer")};_endDrag(t,e){if(!this._dragging)return;let s=this._moved;this._dragging=!1,this._moved=!1,this._releasePointer(),this._handle?.removeAttribute("data-dragging"),this._removeScrim(!s),e!==void 0&&(this._position=e,this._setLive(e)),!(!s&&e===void 0)&&(this._measureBounds(),this._commit(t))}_releasePointer(){if(window.removeEventListener("pointermove",this._onPointerMove),window.removeEventListener("pointerup",this._onPointerUp),window.removeEventListener("pointercancel",this._onPointerCancel),this._captured&&this._pointerId!==null)try{this._handle?.releasePointerCapture(this._pointerId)}catch{}this._captured=!1,this._pointerId=null}_addScrim(){if(this._scrim||!this._handle)return;let t=document.createElement("div");t.className="aparte-split__scrim",t.setAttribute("aria-hidden","true"),this._handle.appendChild(t),this._scrim=t}_removeScrim(t=!1){let e=this._scrim;if(this._scrim=null,!!e){if(!t){e.remove();return}e.style.pointerEvents="none",setTimeout(()=>e.remove(),pc)}}_onDoubleClick=()=>{this.disabled||this.stacked||this.reset()};_onKeydown=t=>{if(this._dragging&&t.key==="Escape"){t.preventDefault(),this._endDrag("pointer",this._dragStartPercent);return}if(this.disabled||this.stacked||t.target!==this._handle)return;if(t.key==="Enter"){t.preventDefault(),this._source="keyboard";try{this.toggleCollapse()}finally{this._source="api"}return}let e=na(t.key,t.shiftKey,this._rtl(),this.orientation==="vertical",this.primary==="end");e!==null&&(t.preventDefault(),this._keying=!0,this._position=Jt(String(this._position+e),this._position),this._setLive(this._position))};_onKeyup=t=>{!this._keying||t.target!==this._handle||na(t.key,t.shiftKey,this._rtl(),this.orientation==="vertical")!==null&&(this._keying=!1,this._commit("keyboard"))};_onFocusOut=()=>{this._keying&&(this._keying=!1,this._commit("keyboard"))};_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t==="none"){this._applyStacked(!1);return}if(typeof matchMedia!="function")return;let e=t?`(max-width: ${t})`:hc;this._media=matchMedia(e),this._media.addEventListener("change",this._onMediaChange),this._applyStacked(this._media.matches)}_onMediaChange=t=>this._applyStacked(t.matches);_applyStacked(t){let e=this.hasAttribute("data-stacked");t&&!e&&this._dragging&&this._endDrag("pointer",this._dragStartPercent),this.toggleAttribute("data-stacked",t),t!==e&&this._syncPaneControls(),t&&!e?this.hasAttribute("pane")||this.showPane("start"):!t&&e&&this.removeAttribute("pane"),this._lastPane=this.pane,this._stampHandle(),t!==e&&this._measureBounds()}_onDocumentClick=t=>{let e=ht(t)?.closest?.("[data-aparte-split-pane]");if(!e)return;let s=(e.getAttribute("data-aparte-split-pane")??"").trim(),i=s==="start"||s==="end"?s:null,r=i?"":s;if(r){if(r!==this.id)return}else if((e.closest("aparte-split")??yt(e).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this)return;this.showPane(i??(this.pane==="start"?"end":"start"))};_syncPaneControls(){let t=new Set([yt(this),document]);for(let e of t)for(let s of e.querySelectorAll("[data-aparte-split-pane]")){let i=(s.getAttribute("data-aparte-split-pane")??"").trim();i!=="start"&&i!=="end"||s.localName!=="button"&&s.getAttribute("role")!=="button"||(s.closest("aparte-split")??yt(s).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this||(this.stacked?s.setAttribute("aria-pressed",String(i===this.pane)):s.removeAttribute("aria-pressed"))}}_onConfigChange=()=>this._relabel();_relabel(){let t=this._handle;if(!t||t.hasAttribute("aria-labelledby")||t.hasAttribute("aria-label")&&t.dataset.ownLabel!=="locale")return;let e=k(this).getLocale();t.setAttribute("aria-label",this.getAttribute("label")??e.splitHandleLabel??"Resize the panes"),t.dataset.ownLabel="locale"}};$(Ze);customElements.get("aparte-split")||customElements.define("aparte-split",Ze);var fc="(max-width: 30rem), (max-height: 30rem)",_c=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),ts=class extends HTMLElement{static get observedAttributes(){return["open","label","breakpoint"]}_button=null;_childWatch=null;_hostWatch=null;_media=null;_lastOpen=null;_ready=!1;get open(){return this.hasAttribute("open")}set open(t){this.toggleAttribute("open",K(t))}get sheet(){return this.hasAttribute("data-sheet")}connectedCallback(){this.classList.contains("aparte-launcher")||this.classList.add("aparte-launcher"),this._button||(this._button=document.createElement("button"),this._button.type="button",this._button.addEventListener("click",this._onButtonClick)),this.appendChild(this._button),typeof MutationObserver=="function"&&(this._childWatch??=new MutationObserver(()=>this._keepButton()),this._childWatch.observe(this,{childList:!0}),this._hostWatch??=new MutationObserver(()=>this._renderButton()),this._hostWatch.observe(this,{attributes:!0,attributeFilter:[Kt],subtree:!0})),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),window.addEventListener("aparte-config-change",this._onConfigChange),this._watchBreakpoint(),this._lastOpen=this.open,this._renderButton(),this._ready=!0}disconnectedCallback(){this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),window.removeEventListener("aparte-config-change",this._onConfigChange),this._childWatch?.disconnect(),this._hostWatch?.disconnect(),this._media?.removeEventListener("change",this._onMediaChange),this._media=null,this._ready=!1}attributeChangedCallback(t){if(!this._ready)return;if(t==="breakpoint"){this._watchBreakpoint();return}if(this._renderButton(),t!=="open")return;let e=this.open;e!==this._lastOpen&&(this._lastOpen=e,!e&&this._button&&this.contains(pt(this))&&this._button.focus(),this._announce())}_announce(){this.dispatchEvent(new CustomEvent("aparte-launcher-toggle",{detail:{open:this.open,sheet:this.sheet},bubbles:!0,composed:!0}))}show(){this.open=!0}close(){this.open=!1}toggle(){this.open=!this.open}_onButtonClick=()=>{let t=!this.open;this.toggle(),t&&this._focusChat()};_onConfigChange=()=>this._renderButton();_config(){return k(this.querySelector(`[${Kt}]`)??this)}_keepButton(){this._button&&this._button.parentNode!==this&&this.appendChild(this._button)}_renderButton(){let t=this._button;if(!t)return;this._keepButton();let e=this._config(),s=e.getLocale(),i=this.open,r=i?"":(this.getAttribute("label")??"").trim(),a=r?"aparte-btn--pill":"aparte-btn--circle";t.className=["aparte-btn","aparte-btn--primary","aparte-btn--solid","aparte-btn--lg",a,"aparte-launcher__button"].join(" "),t.setAttribute("aria-expanded",String(i)),r?t.removeAttribute("aria-label"):t.setAttribute("aria-label",i?s.launcherClose??"Close the chat":s.launcherOpen??"Open the chat");let o=document.createElement("span");o.className="aparte-launcher__icon",o.setAttribute("aria-hidden","true"),o.innerHTML=i?e.getIcon("launcherClose")??e.getIcon("close"):e.getIcon("launcherOpen")??e.getIcon("messageSquare");let l=[o];if(r){let c=document.createElement("span");c.className="aparte-launcher__label",c.textContent=r,l.push(c)}t.replaceChildren(...l)}_onMediaChange=t=>this._applySheet(t.matches);_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t==="none"||typeof matchMedia!="function"){this._applySheet(!1);return}this._media=matchMedia(t?`(max-width: ${t})`:fc),this._media.addEventListener("change",this._onMediaChange),this._applySheet(this._media.matches)}_applySheet(t){t!==this.sheet&&(this.toggleAttribute("data-sheet",t),this._ready&&this.open&&this._announce())}_focusables(){return Array.from(this.querySelectorAll(_c)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}_focusChat(){(Array.from(this.querySelectorAll('[role="textbox"]:not([aria-disabled="true"])')).find(s=>!s.closest("[hidden]")&&s.checkVisibility?.()!==!1)??this._focusables().find(s=>s!==this._button))?.focus()}_onClick=t=>{let e=ht(t)?.closest?.("[data-aparte-launcher-close]");e&&this.contains(e)&&this.close()};_inModalDialog(t){let e=ht(t)?.closest?.("dialog[open]");if(!e||!this.contains(e))return!1;try{return e.matches(":modal")}catch{return!0}}_onKeydown=t=>{if(!this.open)return;if(t.key==="Escape"){if(t.defaultPrevented||t.isComposing||t.keyCode===229||this._inModalDialog(t))return;t.preventDefault(),this.close();return}if(t.key!=="Tab"||!this.sheet)return;let e=this._focusables();if(e.length===0)return;let s=e[0],i=e[e.length-1],r=pt(this);t.shiftKey&&r===s?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),s.focus())}};$(ts);customElements.get("aparte-launcher")||customElements.define("aparte-launcher",ts);typeof document<"u"&&$r();export{H as a,Y as b,G as c,to as d,k as e,M as f,qt as g,Q as h,Ht as i,yl as j,z as k,Br as l,Ns as m};
206
- //# sourceMappingURL=chunk-VTTH7HGO.js.map
206
+ //# sourceMappingURL=chunk-NKYV5B7Q.js.map