1import{u as _}from"./chunk-VJGBCIFP.js";import"./chunk-XCPXRTXT.js";import"./chunk-XJLSI5BW.js";import"./chunk-ZOYOJ6FT.js";import"./chunk-6KHOHYTW.js";var L=50,x=500,E=4e4,I=class{constructor(t){this._element=t,this._triggerQuestionPersonaId=t.dataset.triggerQuestionPersonaId||"",this._chatPersonaId=t.dataset.chatPersonaId||"",this._articleId=t.dataset.articleId||"",this._articleUrl=t.dataset.articleUrl||"",this._triggerQuestionContext=t.dataset.triggerQuestionContext?JSON.parse(t.dataset.triggerQuestionContext):{},this._chatContext=t.dataset.chatContext?JSON.parse(t.dataset.chatContext):{},this._maxHeight=t.dataset.maxHeight,this._suggestionsContainer=t.querySelector(".chatbot__suggestion-list"),this._chatBox=t.querySelector(".chatbot"),this._messagesContainer=t.querySelector(".chatbot__messages"),this._input=t.querySelector(".chatbot__input"),this._form=t.querySelector(".chatbot__form"),this._resetBtn=t.querySelector(".chatbot__reset-btn"),this._resetBtnWrapper=t.querySelector(".chatbot__reset-btn-wrapper"),this._isLoading=!1,this._seenArticleIds=new Set,this._chatPersonaId?this._wireEvents():(this._chatBox&&this._chatBox.classList.add("hidden"),this._form&&this._form.classList.add("hidden")),this._triggerQuestionPersonaId&&this._loadSuggestions()}_wireEvents(){this._form&&(this._form.addEventListener("submit",t=>{if(t.preventDefault(),!this._input)return;let i=this._input.value.trim();!i||this._isLoading||this._submitQuestion(i)}),this._resetBtn&&this._resetBtn.addEventListener("click",()=>this._reset()),this._startChatOnFirstInteraction())}_startChatOnFirstInteraction(){if(!this._input)return;let t=()=>{this._input.removeEventListener("focus",t),this._input.removeEventListener("keydown",t),this._ensureChat()};this._input.addEventListener("focus",t,{once:!1}),this._input.addEventListener("keydown",t,{once:!1})}async _pollJob(t){let i=Date.now()+E,e=L;for(;Date.now()<i;){await new Promise(o=>setTimeout(o,e)),e=Math.min(e*2,x);let s=await fetch(`/api/atom/status/${t}`);if(!s.ok)throw new Error("Polling error: "+await s.text());let n=await s.json();if(n.status==="done")return n.result;if(n.status==="error")throw new Error(n.error||"Job failed")}throw new Error("Job timed out")}async _fetchReadMore(t){if(!t||!t.length)return null;try{let i="/api/atom-chat/read-more?articleid="+encodeURIComponent(this._articleId)+"&references="+encodeURIComponent(JSON.stringify(t)),e=await fetch(i);return e.ok?(await e.json()).html||null:(console.warn("[chatbot] fetchReadMore failed",e.status,await e.text()),null)}catch(i){_(i)}}async _postAndPoll(t,i){let e=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!e.ok)throw new Error("API error: "+await e.text());let{jobId:s}=await e.json();return this._pollJob(s)}async _loadSuggestions(){try{let t=await this._callOneShot(this._triggerQuestionPersonaId,this._articleUrl,this._triggerQuestionContext),i=t&&t.replies&&t.replies[0]&&t.replies[0].content,e=[];try{let s=i.replace(/```json|```/g,"").trim(),n=JSON.parse(s);e=Array.isArray(n&&n.questions)?n.questions:Array.isArray(n)?n:[]}catch{}if(e.length)e.forEach(s=>{let n=typeof s=="string"?s:s&&s.question;n&&this._appendSuggestionChip(n,s&&s.answer)});else{let s=this._suggestionsContainer&&this._suggestionsContainer.closest(".chatbot__suggestions");s&&s.classList.add("hidden")}}catch(t){_(t)}finally{this._suggestionsContainer&&this._suggestionsContainer.querySelectorAll(".chatbot__suggestion-chip--skeleton").forEach(t=>{t.remove()})}}_appendSuggestionChip(t,i){if(!this._suggestionsContainer)return;let e=document.createElement("button");e.type="button",e.className="chatbot__suggestion-chip",e.innerHTML='<span class="chatbot__chip-icon" aria-hidden="true">\u2726</span> '+this._escapeHtml(t),e.addEventListener("click",()=>{i?this._submitCachedAnswer(t,i):this._submitQuestion(t);let n=this._suggestionsContainer&&this._suggestionsContainer.closest(".chatbot__suggestions");n&&n.classList.add("chatbot__suggestions--minimised")});let s=this._suggestionsContainer.querySelector(".chatbot__suggestion-chip--skeleton");s?(this._suggestionsContainer.insertBefore(e,s),s.remove()):this._suggestionsContainer.appendChild(e)}_reset(){this._chatId=void 0,this._seenArticleIds=new Set,this._messagesContainer&&(this._messagesContainer.innerHTML=""),this._chatBox&&(this._chatBox.hidden=!0),this._input&&(this._input.value="");let t=this._element.querySelector(".chatbot__suggestions");t&&t.classList.remove("chatbot__suggestions--minimised"),this._resetBtnWrapper&&(this._resetBtnWrapper.hidden=!0)}_submitCachedAnswer(t,i){if(!this._chatPersonaId)return;this._chatBox&&this._chatBox.hidden&&(this._chatBox.hidden=!1),this._input&&(this._input.value=""),this._addMessage(t,"user");let e=i&&typeof i=="object",s=e?i.Content||i.content||"":i,n=e?i.references||[]:[],o=e?i.followUpQuestions||[]:[],{content:a,references:u}=this._filterAndRenumberReferences(s,n);s=a;let m=this._addMessage("","assistant");this._typewriteContent(s,m).then(()=>{o.length&&this._renderFollowUpQuestions(o,m)}
1).catch(h=>_(h));let p=u.filter(h=>!this._seenArticleIds.has(h.id));p.length&&this._fetchReadMore(p).then(h=>{if(h&&this._messagesContainer){p.forEach(C=>this._seenArticleIds.add(C.id));let w=document.createElement("div");w.className="chatbot__readmore-wrapper",w.innerHTML=h,this._messagesContainer.appendChild(w),this._scrollToBottom()}}).catch(h=>_(h)),this._resetBtnWrapper&&(this._resetBtnWrapper.hidden=!1),this._syncCachedAnswer(t,s)}async _syncCachedAnswer(t,i){this._syncPromise=(async()=>{try{await this._ensureChat(),await this._postAndPoll("/api/atom/add-message",{chatId:this._chatId,messages:[{role:"user",content:t},{role:"assistant",content:i}]})}catch(e){_(e)}finally{this._syncPromise=null}})()}_submitQuestion(t){this._chatPersonaId&&(this._chatBox&&this._chatBox.hidden&&(this._chatBox.hidden=!1),this._input&&(this._input.value=""),this._addMessage(t,"user"),this._resetBtnWrapper&&(this._resetBtnWrapper.hidden=!1),this._clearFollowUpQuestions(),this._sendMessage(t))}_addMessage(t,i,e=[]){let s=document.createElement("div");return s.className="chatbot__message chatbot__message--"+i,i==="loading"?(s.setAttribute("aria-label","Laddar svar\u2026"),s.innerHTML='<span class="chatbot__dot" aria-hidden="true"></span><span class="chatbot__dot" aria-hidden="true"></span><span class="chatbot__dot" aria-hidden="true"></span>'):s.innerHTML=i==="assistant"?this._formatContent(t):this._escapeHtml(t),this._messagesContainer&&this._messagesContainer.appendChild(s),this._scrollToBottom(!0),s}async _ensureChat(){if(!this._chatId){if(this._ensureChatPromise)return this._ensureChatPromise;this._ensureChatPromise=(async()=>{let t=await this._postAndPoll("/api/atom/create",{personaId:this._chatPersonaId,context:this._chatContext});if(!t||!t.chatId)throw new Error("Kunde inte skapa chatt");this._chatId=t.chatId})();try{await this._ensureChatPromise}finally{this._ensureChatPromise=null}}}async _sendMessage(t){if(this._isLoading)return;this._isLoading=!0,this._element.classList.add("chatbot-container--loading");let i=this._addMessage("","loading"),e=null;try{await this._ensureChat();let s=await fetch("/api/atom/process-stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chatId:this._chatId,message:t,context:this._chatContext})});if(!s.ok)throw new Error("Stream error: "+await s.text());if(!s.body)throw new Error("No response body");let n='<span class="chatbot__cursor" aria-hidden="true"></span>',o="",a="",u=[],m=!1,p=!1,h=async()=>{for(;!m||u.length;){if(!u.length){await new Promise(l=>setTimeout(l,16));continue}let c=u.shift()||"";o+=c,c.trim()&&(e||(i.remove(),e=this._addMessage("","assistant")),e.innerHTML=this._formatContent(o)+n,this._scrollToBottom(),await new Promise(l=>setTimeout(l,20+Math.random()*20)))}p=!0},w=s.body.getReader(),C=new TextDecoder,y="";for(h().catch(c=>_(c));;){let{done:c,value:l}=await w.read();if(c)break;y+=C.decode(l,{stream:!0});let f=y.split(` 2`);y=f.pop()||"";for(let r of f){if(!r.startsWith("data: "))continue;let d=r.slice(6).trim();if(!d||d==="[DONE]")continue;let g;try{g=JSON.parse(d)}catch{continue}let b=g.choices&&g.choices[0]&&g.choices[0].delta;b&&(b.content&&u.push(...b.content.split(/(\s+)/)),b.properties&&(a+=b.properties))}}for(m=!0;!p;)await new Promise(c=>setTimeout(c,16));if(i.remove(),!e)this._addMessage("(Tomt svar)","assistant");else{e.innerHTML=this._formatContent(o);let c=[],l=[];try{let r=JSON.parse(a);c=r.references||[],l=r.followUpQuestions||[]}catch{}l.length&&this._renderFollowUpQuestions(l,e);let f=c.filter(r=>!this._seenArticleIds.has(r.id));f.length&&this._fetchReadMore(f).then(r=>{if(r&&this._messagesContainer){f.forEach(g=>this._seenArticleIds.add(g.id));let d=document.createElement("div");d.className="chatbot__readmore-wrapper",d.innerHTML=r,this._messagesContainer.appendChild(d),this._scrollToBottom(!0)}}).catch(r=>_(r))}}catch(s){_(s),i.remove(),e||this._addMessage("N\xE5got gick fel. F\xF6rs\xF6k igen senare.","assistant")}finally{this._isLoading=!1,this._element.classList.remove("chatbot-container--loading")}}_renderFollowUpQuestions(t,i){let e=document.createElement("div");
2e.className="chatbot__followup-questions";let s=this;t.forEach(n=>{let o=n.replace(/^â¦\s*/,"").trim(),a=document.createElement("button");a.type="button",a.className="chatbot__followup-chip",a.innerHTML='<span class="chatbot__chip-icon" aria-hidden="true">\u2726</span> '+s._escapeHtml(o),a.addEventListener("click",()=>{s._clearFollowUpQuestions(),s._submitQuestion(o)}),e.appendChild(a)}),this._messagesContainer&&this._messagesContainer.appendChild(e),this._scrollToBottom(!0)}_clearFollowUpQuestions(){this._messagesContainer&&this._messagesContainer.querySelectorAll(".chatbot__followup-questions").forEach(t=>t.remove())}async _callOneShot(t,i,e={}){return this._postAndPoll("/api/atom/one-shot",{personaId:t,message:i,context:e})}async _typewriteContent(t,i){let e=t.split(/(\s+)/),s="",n='<span class="chatbot__cursor" aria-hidden="true"></span>';for(let o of e)s+=o,i.innerHTML=this._formatContent(s)+n,this._scrollToBottom(),o.trim()&&await new Promise(a=>setTimeout(a,20+Math.random()*20));i.innerHTML=this._formatContent(t)}_scrollToBottom(t){if(!this._messagesContainer)return;if(this._maxHeight==="none"){let e=this._messagesContainer.closest(".modal");e&&(e.scrollTop=e.scrollHeight);return}let i=this._messagesContainer;!t&&i.scrollHeight-i.scrollTop-i.clientHeight>100||(i.scrollTop=i.scrollHeight)}_formatContent(t){return this._escapeHtml(t).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/\[(\d+)\]/g,'<sup class="chatbot__ref">$1</sup>').replace(/\n/g,"<br>")}_filterAndRenumberReferences(t,i){if(!i.length||!this._articleId)return{content:t,references:i};let e=[],s={};for(let o of i)o.id!==this._articleId&&(e.push(o),s[o.indexNumber]=e.length);if(e.length===i.length)return{content:t,references:i};let n=t;for(let[o,a]of Object.entries(s))n=n.replace(new RegExp(`\\[${o}\\]`,"g"),`[__REF_${a}__]`);for(let o of i)s[o.indexNumber]||(n=n.replace(new RegExp(`\\[${o.indexNumber}\\]`,"g"),""));return n=n.replace(/\[__REF_(\d+)__\]/g,"[$1]"),n=n.replace(/,\s*och\b/g," och"),n=n.replace(/\s{2,}/g," "),{content:n.trim(),references:e}}_escapeHtml(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}_linkify(t){let i=/https?:\/\/[^\s<>"]+/g;return this._escapeHtml(t).replace(i,s=>'<a href="'+s.replace(/&/g,"&")+'" target="_blank" rel="noopener noreferrer">'+s+"</a>")}};export{I as default}; 3//# sourceMappingURL=chatbot-module-V5MQ55BQ.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.