@dori-ai/dori-side-widget 1.13.197 → 1.13.199

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.
@@ -0,0 +1 @@
1
+ import{A as e,c as t,f as n,p as i}from"../widget.js";import{r,S as s,U as o}from"./store-font-B5B6CNk6.js";import{S as a}from"./anchors-B_5p2Z47.js";function l(e,t){t.buffer+=e.replace(/\r\n?/g,"\n");const n=[];let i=t.buffer.indexOf("\n\n");for(;-1!==i;){const e=t.buffer.slice(0,i);t.buffer=t.buffer.slice(i+2);let r="message";const s=[];for(const t of e.split("\n"))t.startsWith("event:")?r=t.slice(6).trim():t.startsWith("data:")&&s.push(t.slice(5).replace(/^ /,""));s.length&&n.push({event:r,data:s.join("\n")}),i=t.buffer.indexOf("\n\n")}return n}const c=(e=window)=>e.Shopify?.routes?.root||"/";class d extends Error{constructor(e){super(`AI search unavailable (${e})`),this.status=e}}const p=t=>`${e}/ai-search/${encodeURIComponent(t)}`;let h=null;const u=e=>{h=e},f=()=>h?{"X-Dori-Preview":h}:{};async function g(e,t,n,i,r){const s=new URLSearchParams({q:t,mode:n});i.currency&&s.set("currency",i.currency),i.country&&s.set("country",i.country);const o=await fetch(`${p(e)}/suggest?${s}`,{signal:r,headers:f()});if(!o.ok)throw new d(o.status);return(await o.json()).products??[]}async function m(e,t,n){try{const i=t.endsWith("/")?t:`${t}/`,r=new URLSearchParams({q:e,"resources[type]":"collection","resources[limit]":"2"}),s=await fetch(`${i}search/suggest.json?${r}`,{signal:n});if(!s.ok)return[];const o=await s.json();return(o.resources?.results?.collections??[]).filter(e=>!!e.title&&!!e.url).map(e=>({title:e.title,url:e.url}))}catch{return[]}}const x="Cancel",v="AI search",y="Search all products",w="Preview: only you see AI search",b=new Set(["results","answer","not_found","fallback"]),k="dori-ai-search",$='header, [role="banner"], [id*="header" i], [class*="header" i]';function q(e,t){if(null==e)return!1;try{const n=new URL(e||"/",t);return n.origin===t&&/\/search\/?$/.test(n.pathname)}catch{return!1}}const S=e=>String(e??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[e])),A=(e=!1,t=18)=>`<svg class="spark${e?" live":""}" width="${t}" height="${t}" viewBox="0 0 24 24" aria-hidden="true"><path class="s1" d="M10 4Q11.76 10.24 18 12Q11.76 13.76 10 20Q8.24 13.76 2 12Q8.24 10.24 10 4Z" fill="currentColor"/><path class="s2" d="M19 1.5Q19.77 4.23 22.5 5Q19.77 5.77 19 8.5Q18.23 5.77 15.5 5Q18.23 4.23 19 1.5Z" fill="currentColor"/></svg>`;function M(e,t,n){if(null==e||!Number.isFinite(e))return"";const i=(t||n.currency||"").split(" ")[0].toUpperCase(),r=Number.isInteger(e)?0:2;try{if(i)return new Intl.NumberFormat(n.locale||void 0,{style:"currency",currency:i,minimumFractionDigits:r,maximumFractionDigits:2}).format(e)}catch{}return`${e.toFixed(r)}${i?` ${i}`:""}`}function z(e,t){if(!e)return"#";if(/^https?:\/\//.test(e))return e;if(e.startsWith("//"))return"#";const n=e.startsWith("/")?e:`/${e}`,i=t.root.endsWith("/")?t.root:`${t.root}/`;return"/"===i?n:`${i.slice(0,-1)}${n}`}const L=(e,t)=>z(`/search?q=${encodeURIComponent(e)}&options%5Bprefix%5D=last`,t);function P(e,t){return e?/cdn\.shopify\.com|\/cdn\/shop\//.test(e)?`${e}${e.includes("?")?"&":"?"}width=${t}`:e:""}function E(e,t){const n=M(e.price,e.currency,t),i=e.price_unit?` / ${S(e.price_unit)}`:"",r=e.compare_at?` <s>${S(M(e.compare_at,e.currency,t))}</s>`:"";return`${S(n)}${i}${r}`}const j=(e,t)=>`<div class="grid">${e.map(e=>function(e,t){const n=e.image?`<img src="${S(P(e.image,400))}" alt="" loading="lazy">`:"";return`<a class="card" href="${S(z(e.url,t))}" data-id="${S(e.id)}"><div class="ph">${n}</div>`+(e.brand?`<div class="br">${S(e.brand)}</div>`:"")+`<div class="nm">${S(e.name)}</div><div class="pr">${E(e,t)}${e.sold_out?'<span class="so">Sold out</span>':""}</div></a>`}(e,t)).join("")}</div>`;function C(e){return`<a class="colrow" href="${S((t=e.url,t&&(/^https?:\/\//.test(t)||t.startsWith("/")&&!t.startsWith("//"))?t:"#"))}">${S(e.title)}</a>`;var t}const F=(e,t)=>`<div class="stp${t?" done":""}"><span class="ic">${t?'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12.5 4.5 4.5L19 7.5"/></svg>':""}</span><span class="tx">${S(e)}</span></div>`;function R(e,t,n){return null!=e.cursor?`<div class="loader">${t.loadingMore?'<span class="spin"></span>':""}</div>`:`<div class="end"><a class="more" href="${S(L(t.asked,n))}">${y}</a></div>`}function I(e,t,n,i){return`<div class="empty"><h2>${S(e)}</h2><a class="more" href="${S(L(t.asked,n))}">${y}</a></div>`+(i.length?`<div class="popular"><div class="sech">Popular right now</div>${j(i,n)}</div>`:"")}function N(e,t){return"typing"===e.phase?function(e,t){const n=e.q.trim();if(!n)return"";const i=e=>e===n||n.startsWith(e),r=i(e.collectionsFor)?e.collections.slice(0,2):[],s=i(e.suggestedFor)?e.suggestions.slice(0,4):[];return function(e){return`<button class="airow" data-act="enter">${A()}<span class="lab">${v}</span><span class="q">“${S(e)}”</span><span class="key"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 5v7a3 3 0 0 1-3 3H6"/><path d="m10 11-4 4 4 4"/></svg></span></button>`}(n)+(r.length?`<div class="sech">Collections</div><div class="rows">${r.map(C).join("")}</div>`:"")+(s.length?`<div class="sech">Products</div><div class="rows">${s.map((e,n)=>function(e,t,n){const i=e.image?`<img src="${S(P(e.image,120))}" alt="" loading="lazy">`:'<span class="noimg"></span>';return`<a class="row" href="${S(z(e.url,t))}" data-id="${S(e.id)}" data-i="${n}">${i}<span class="meta"><span class="nm">${S(e.name)}</span><span class="pr">${E(e,t)}</span></span></a>`}(e,t,n)).join("")}</div>`:"")}(e,t):"working"!==e.phase&&e.result?function(e,t){const n=e.result;switch(n.type){case"results":{const s=n.chips.length?`<div class="chips">${n.chips.map(e=>`<button class="chip" data-drop="${S(e.key)}" aria-label="Remove">${S(function(e,t){if("price"===e.kind){const n=e.min?M(e.min,e.currency,t):"",i=e.max?M(e.max,e.currency,t):"";return n&&i?`${n} to ${i}`:i?`Under ${i}`:`From ${n}`}return e.value??""}(e,t))}<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg></button>`).join("")}</div>`:"",o=n.note?.currency||t.currency;return s+(n.note?`<div class="note">${S((i=M(n.note.under,o,t),r=null!=n.note.from?M(n.note.from,o,t):null,r?`Nothing under ${i}. Closest from ${r}`:`Nothing under ${i}`))}</div>`:"")+j(n.products,t)+R(n,e,t)}case"fallback":return n.products.length?j(n.products,t)+R(n,e,t):I(`Nothing found for “${e.asked}”`,e,t,[]);case"not_found":return I(`No ${n.noun} found`,e,t,n.popular);case"answer":{if("none"===n.kind)return I("No answer in the store's help pages",e,t,[]);const i=n.text&&"entry"!==n.kind?`<div class="ansh">${A(!1,13)}Answer</div><p class="anst">${S(n.text)}</p>`:"";return`<div class="ans">${i}<div class="src${i?"":" alone"}"><div class="sech">${"page"===n.entry.source?"From the store's pages":"From the store's FAQ"}</div><div class="fq">${S(n.entry.question)}</div><div class="fa">${S(n.entry.answer)}</div></div></div>`}}var i,r}(e,t):function(e){const t=`<div class="aih">${A(!0)}<span class="shim">${v}</span></div>`,n=e.plan?[F(e.plan.label,!0),F("faq"===e.plan.kind?"Checking the store's help pages":(s=e.plan.products,s?`Searching ${s.toLocaleString()} products`:"Searching the products"),!1)]:[F((r=e.asked,`Reading “${r}”`),!1)],i="faq"===e.plan?.kind?'<div class="ans"><span class="skl sk" style="width:92%"></span><span class="skl sk" style="width:70%"></span></div>':`<div class="grid">${Array.from({length:4},()=>'<div class="card skel"><div class="ph"></div><span class="skl sk" style="width:80%"></span><span class="skl sk" style="width:40%"></span></div>').join("")}</div>`;var r,s;return`<div class="aib">${t}<div class="stps">${n.join("")}</div></div>${i}`}(e)}const _="dori-ai-search-last";let O=null;class T{constructor(e){this.config=e,this.state=((e="")=>({q:e,phase:"typing",suggestions:[],collections:[],suggestedFor:"",collectionsFor:"",asked:"",rid:null,drop:[],plan:null,result:null,loadingMore:!1}))(),this.shopper=function(e=window){const t=e.Shopify;return{currency:t?.currency?.active||void 0,country:t?.country||void 0,language:t?.locale||document.documentElement.lang||void 0}}(),this.ctx={locale:navigator.language||"en",currency:this.shopper.currency||"",root:c()},this.host=document.createElement("div"),this.host.id=k,this.host.style.setProperty("display","block","important");const t=this.host.attachShadow({mode:"open"}),n=getComputedStyle(document.body).color||"#111",i=r(document.body);i&&this.host.style.setProperty(s,i),this.host.style.fontFamily=o,t.innerHTML=`<style>\n:host{all:initial}\n*{box-sizing:border-box}\n.wrap{position:fixed;inset:0;z-index:2147483647;color:var(--ink,#111);font-size:14px;line-height:1.35;-webkit-font-smoothing:antialiased}\n.scrim{position:absolute;inset:0;background:rgba(0,0,0,.32);animation:fadein .16s ease both}\n.panel{position:absolute;inset:0;background:#fff;display:flex;flex-direction:column;animation:fadein .16s ease both}\na{color:inherit;text-decoration:none}\nbutton{font:inherit;color:inherit}\n.sbar{display:flex;align-items:center;gap:10px;padding:10px 14px;border-bottom:1px solid var(--line)}\n.field{flex:1;display:flex;align-items:center;gap:8px;height:44px;border-radius:8px;background:#f5f5f5;padding:0 12px;border:1px solid #e6e6e6;min-width:0}\n.field svg{flex:none;color:#777}\n.field input{flex:1;min-width:0;border:0;outline:0;background:none;font:inherit;font-size:16px;color:var(--ink);-webkit-appearance:none;appearance:none}\n.field input::-webkit-search-cancel-button{display:none}\n.cancel{border:0;background:none;font-size:15px;cursor:pointer;padding:6px 2px}\n.cancel .x{display:none}\n.pv{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 14px;font-size:13px;line-height:1.3;background:#fff6d6;color:#4d3b00;border-bottom:1px solid #f0e2a8}\n.pv a{flex:none;text-decoration:underline;white-space:nowrap}\n.body{flex:1;overflow-y:auto;overscroll-behavior:contain;min-height:120px}\n.body:empty{min-height:0}\n.spark{flex:none;display:block}\n.spark.live .s1{transform-origin:10px 12px;animation:pulse 1.3s ease-in-out infinite}\n.spark.live .s2{transform-origin:19px 5px;animation:twinkle 1.3s ease-in-out infinite}\n@keyframes pulse{50%{transform:scale(.76)}}\n@keyframes twinkle{0%,100%{opacity:.2;transform:scale(.55)}50%{opacity:1;transform:scale(1)}}\n.airow{display:flex;align-items:center;gap:10px;width:calc(100% - 24px);margin:10px 12px 2px;padding:12px;border:0;border-radius:12px;background:var(--ai);cursor:pointer;text-align:left;transition:transform .12s ease}\n.airow:active{transform:scale(.975)}\n.airow .lab{font-weight:600;white-space:nowrap;font-size:15px}\n.airow .q{min-width:0;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#5c5c5c;font-size:15px}\n.airow .key{flex:none;display:inline-flex;align-items:center;justify-content:center;width:28px;height:24px;border-radius:7px;background:#fff;border:1px solid var(--line);color:#555}\n.sech{font-weight:600;font-size:11px;line-height:1;letter-spacing:.12em;text-transform:uppercase;color:#777;margin:16px 14px 6px}\n.rows{display:flex;flex-direction:column}\n.row{display:flex;align-items:center;gap:12px;padding:7px 14px}\n.row img,.row .noimg{width:46px;height:46px;object-fit:contain;background:#f6f6f6;border-radius:6px;flex:none}\n.row .meta{min-width:0;flex:1;display:flex;flex-direction:column}\n.row .nm{font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.row .pr{font-size:13px;color:#555;margin-top:2px}\n.colrow{display:block;padding:8px 14px;font-size:14px}\n.aib{padding:16px 16px 0}\n.aih{display:flex;align-items:center;gap:8px;font-weight:600;font-size:15.5px}\n.shim{background:linear-gradient(90deg,var(--ink) 0%,var(--ink) 38%,#c4c4c4 50%,var(--ink) 62%,var(--ink) 100%);background-size:260% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:shim 1.7s linear infinite}\n@keyframes shim{from{background-position:100% 0}to{background-position:-160% 0}}\n.stps{margin:10px 0 0 1px;display:flex;flex-direction:column;gap:8px}\n.stp{display:flex;align-items:center;gap:9px;font-size:14px;color:#6b6b6b;animation:fadein .24s ease both}\n.stp .ic{width:15px;height:15px;flex:none;border-radius:50%;border:1.7px solid #d2d2d2;border-top-color:var(--ink);animation:spin .8s linear infinite;display:flex;align-items:center;justify-content:center}\n.stp.done{color:var(--ink)}\n.stp.done .ic{border:0;animation:none}\n.stp .tx{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n@keyframes spin{to{transform:rotate(360deg)}}\n.chips{display:flex;flex-wrap:wrap;gap:6px;padding:10px 14px 0}\n.chip{display:inline-flex;align-items:center;gap:7px;font-size:13px;border:1px solid var(--ink);border-radius:999px;padding:5px 11px;cursor:pointer;background:#fff}\n.note{margin:10px 14px 0;font-size:13px;color:#6b6b6b}\n.grid{display:grid;grid-template-columns:1fr 1fr;gap:18px 10px;padding:14px 14px 20px}\n.card{min-width:0;display:block}\n.card .ph{aspect-ratio:1/1;background:#f6f6f6;border-radius:6px;overflow:hidden}\n.card .ph img{width:100%;height:100%;object-fit:contain;display:block}\n.card .br{font-size:10.5px;font-weight:500;line-height:1.2;letter-spacing:.12em;text-transform:uppercase;color:#777;margin-top:8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.card .nm{font-size:13.5px;line-height:1.3;margin-top:3px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}\n.card .pr{font-size:13.5px;margin-top:4px}\n.card .pr s,.row .pr s{color:#8a8a8a;margin-left:4px}\n.card .so{font-size:11px;color:#a33;margin-left:6px}\n.card.skel .ph,.sk{background:linear-gradient(90deg,#f3f3f3,#e9e9e9,#f3f3f3);background-size:200% 100%;animation:sh 1.2s linear infinite}\n.skl{display:block;height:10px;border-radius:5px;margin-top:9px}\n@keyframes sh{to{background-position:-200% 0}}\n.ans{padding:18px 16px 24px}\n.ansh{display:flex;align-items:center;gap:6px;font-weight:600;font-size:11px;line-height:1;letter-spacing:.12em;text-transform:uppercase;color:#777}\n.anst{margin:10px 0 0;font-size:16.5px;line-height:1.5}\n.src{margin-top:20px;border-top:1px solid var(--line);padding-top:16px}\n.src.alone{margin-top:0;border-top:0;padding-top:0}\n.src .sech{margin:0 0 9px}\n.src .fq{font-weight:500;font-size:15px;line-height:1.3}\n.src .fa{margin-top:6px;font-size:13.5px;line-height:1.5;color:#555;white-space:pre-line}\n.empty{padding:36px 20px 20px;text-align:center}\n.empty h2{margin:0;font-weight:500;font-size:21px;line-height:1.25}\n.more{display:inline-block;margin-top:12px;font-size:13.5px;color:#6b6b6b;text-decoration:underline}\n.end{text-align:center;padding:0 14px 28px}\n.loader{display:flex;justify-content:center;padding:4px 0 28px;min-height:40px}\n.spin{width:18px;height:18px;border-radius:50%;border:2px solid #ddd;border-top-color:var(--ink);animation:spin .8s linear infinite}\n.popular{border-top:1px solid var(--line);margin:6px 14px 0;padding-top:14px}\n.popular .sech{margin:0 0 2px}\n.popular .grid{padding:12px 0 28px}\n@keyframes fadein{from{opacity:0}to{opacity:1}}\n@media (min-width:750px){\n .scrim{background:rgba(0,0,0,.18)}\n .panel{inset:auto;top:var(--top,16px);left:var(--left,16px);width:var(--w,min(760px,100vw - 32px));max-height:calc(100vh - var(--top,16px) - 16px);border-radius:12px;overflow:hidden;box-shadow:0 0 0 1px rgba(0,0,0,.06),0 14px 40px rgba(0,0,0,.16);animation:drop .14s ease-out both}\n .sbar{height:56px;padding:0 8px 0 16px;gap:6px;border-bottom:0}\n .field{height:56px;padding:0;gap:10px;border:0;border-radius:0;background:none}\n .body:not(:empty){border-top:1px solid var(--line)}\n .pv{padding:8px 16px}\n .pv + .body:not(:empty){border-top:0}\n .cancel{display:flex;align-items:center;justify-content:center;width:36px;height:36px;padding:0;border-radius:8px;color:#6b6b6b}\n .cancel:hover{background:#f2f2f2;color:var(--ink)}\n .cancel .t{display:none}\n .cancel .x{display:block}\n .grid{grid-template-columns:repeat(4,minmax(0,1fr))}\n .narrow .grid{grid-template-columns:repeat(3,minmax(0,1fr))}\n}\n@keyframes drop{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none}}\n@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}\n</style><div class="wrap" style="--ink:${n};--ai:color-mix(in srgb, ${n} 6%, #fff);--line:#eaeaea" hidden><div class="scrim"></div><div class="panel" role="dialog" aria-modal="true" aria-label="${v}"><form class="sbar" role="search"><label class="field"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/></svg><input type="search" enterkeyhint="search" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="What are you looking for?"></label><button type="button" class="cancel" aria-label="${x}"><span class="t">${x}</span><svg class="x" width="18" height="18" viewBox="0 0 18 18" aria-hidden="true"><path d="M4.5 4.5l9 9M13.5 4.5l-9 9" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg></button></form>`+(e.preview?`<div class="pv"><span>${w}</span><a class="pvl" target="_blank" rel="noopener">Your usual results</a></div>`:"")+'<div class="body"></div></div></div>',this.input=t.querySelector("input"),this.body=t.querySelector(".body"),this.syncPreviewBar(),t.querySelector("form").addEventListener("submit",e=>{e.preventDefault(),this.search()}),this.input.addEventListener("input",()=>this.typed()),t.querySelector(".cancel").addEventListener("click",()=>this.close()),t.querySelector(".scrim").addEventListener("click",()=>this.close()),this.body.addEventListener("click",e=>this.clicked(e)),this.body.addEventListener("scroll",()=>this.scrolled(),{passive:!0}),window.addEventListener("popstate",this.onPop),window.addEventListener("resize",this.onResize,{passive:!0}),document.addEventListener("keydown",this.onKey,!0),document.documentElement.appendChild(this.host)}host;input;body;state;ctx;shopper;timers=[];suggestAbort=null;searchAbort=null;moreAbort=null;pausedFor="";isOpen=!1;pushed=!1;overflow="";started=0;anchor=null;notice=null;get tag(){return this.config.preview?{preview:!0}:{}}get wrap(){return this.host.shadowRoot.querySelector(".wrap")}place(){const e=this.host.shadowRoot.querySelector(".panel");if(!window.matchMedia("(min-width: 750px)").matches)return e.removeAttribute("style"),void e.classList.remove("narrow");let t=this.anchor&&this.anchor.isConnected?this.anchor:null,n=t?.getBoundingClientRect();(!n||n.width<=0)&&(t=function(){for(const e of document.querySelectorAll(a)){if(e.closest(`#${k}`))continue;const t=e.getBoundingClientRect();if(t.width>0&&t.height>0&&t.top<window.innerHeight/3)return e}return null}(),n=t?.getBoundingClientRect());const i=function(e,t,n){const i=t-32;if(!e||e.width<=0||e.height<=0){const e=Math.min(760,i);return{top:16,left:Math.round((t-e)/2),width:e}}const r=e.width>=240,s=Math.round(Math.min(i,r?Math.max(e.width+16,560):760)),o=r?e.left-8:(t-s)/2,a=e.top+e.height/2-28;return{top:Math.round(Math.min(Math.max(a,8),Math.max(8,n-240))),left:Math.round(Math.min(Math.max(o,16),t-16-s)),width:s}}(n??null,window.innerWidth,window.innerHeight);e.style.setProperty("--top",`${i.top}px`),e.style.setProperty("--left",`${i.left}px`),e.style.setProperty("--w",`${i.width}px`),e.classList.toggle("narrow",i.width<860)}onResize=()=>{this.isOpen&&this.place()};open(e,n,i=null){if(!this.isOpen){this.isOpen=!0,this.anchor=i,this.wrap.hidden=!1,this.overflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden",this.place();try{history.pushState({...history.state||{},doriAiSearch:!0},""),this.pushed=!0}catch{this.pushed=!1}t("ai_search_open",{run:n,...this.tag})}e&&e!==this.input.value&&(this.input.value=e,this.typed()),n||this.input.focus(),n&&e.trim()&&this.search()}restore(e){this.isOpen=!0;try{history.replaceState({...history.state||{},doriAiSearch:!1},""),history.pushState({...history.state||{},doriAiSearch:!0},""),this.pushed=!0}catch{this.pushed=!1}this.wrap.hidden=!1,this.overflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden",this.anchor=null,this.place(),this.input.value=e.q,this.dispatch({type:"restore",q:e.q,rid:e.rid,result:e.result,drop:e.drop})}close(e=!1){this.isOpen&&(this.isOpen=!1,this.cancelAll(),this.wrap.hidden=!0,document.documentElement.style.overflow=this.overflow,this.pushed&&!e&&history.state?.doriAiSearch&&(this.pushed=!1,history.back()),this.pushed=!1)}destroy(){this.close(),window.removeEventListener("popstate",this.onPop),window.removeEventListener("resize",this.onResize),document.removeEventListener("keydown",this.onKey,!0),this.host.remove()}onKey=e=>{this.isOpen&&"Escape"===e.key&&(e.stopPropagation(),this.close())};onPop=()=>{this.isOpen&&!history.state?.doriAiSearch&&this.close(!0)};syncPreviewBar(){const e=this.host.shadowRoot,t=e.querySelector(".pvl");if(!t)return;const n=this.input.value.trim();t.setAttribute("href",function(e,t,n,i){const r=t.find(e=>q(e.action,n));if(!r)return i;const s=new URL(r.action||"/search",n);for(const[o,a]of r.hidden)"q"!==o&&s.searchParams.set(o,a);return s.searchParams.set("q",e),s.pathname+s.search}(n,[...document.querySelectorAll("form")].map(e=>({action:e.getAttribute("action"),hidden:[...e.querySelectorAll('input[type="hidden"][name]')].map(e=>[e.name,e.value])})),location.origin,L(n,this.ctx)));const i="done"===this.state.phase&&"fallback"===this.state.result?.type&&!this.notice;e.querySelector(".pv span").textContent=i?"Preview: AI didn't run for this search, so these are plain results":w}dispatch(e){this.state=function(e,t){switch(t.type){case"input":return{...e,q:t.q,phase:"typing",rid:null,plan:null,result:null,loadingMore:!1};case"suggested":return t.q!==e.q.trim()||"typing"!==e.phase?e:t.collections?{...e,suggestions:t.products,suggestedFor:t.q,collections:t.collections,collectionsFor:t.q}:{...e,suggestions:t.products,suggestedFor:t.q};case"enter":return{...e,phase:"working",asked:e.q.trim(),rid:t.rid,drop:t.drop??[],plan:null,result:null,loadingMore:!1};case"server":return t.rid!==e.rid||"working"!==e.phase?e:"plan"===t.event.type?{...e,plan:t.event}:b.has(t.event.type)?{...e,phase:"done",result:t.event}:e;case"failed":return t.rid!==e.rid||"working"!==e.phase?e:{...e,phase:"done",result:{type:"fallback",products:[],cursor:null}};case"loading_more":return t.rid!==e.rid?e:{...e,loadingMore:!0};case"more":{const n=e.result;if(t.rid!==e.rid||!n||"results"!==n.type&&"fallback"!==n.type)return e;const i=new Set(n.products.map(e=>e.id)),r=[...n.products,...t.products.filter(e=>!i.has(e.id))];return{...e,loadingMore:!1,result:{...n,products:r,cursor:t.cursor}}}case"restore":return{...e,q:t.q,asked:t.q,rid:t.rid,drop:t.drop,phase:"done",result:t.result,plan:null,loadingMore:!1}}}(this.state,e),this.syncPreviewBar();const t=this.body.scrollTop;this.body.innerHTML=this.notice&&"done"===this.state.phase?`<div class="empty"><h2>${this.notice}</h2></div>`:N(this.state,this.ctx),"done"===this.state.phase&&(this.body.scrollTop=t)}cancelAll(){this.timers.forEach(e=>clearTimeout(e)),this.timers=[];for(const e of[this.suggestAbort,this.searchAbort,this.moreAbort])e?.abort();this.suggestAbort=this.searchAbort=this.moreAbort=null}typed(){this.cancelAll(),this.body.scrollTop=0,this.dispatch({type:"input",q:this.input.value});const e=this.input.value.trim();if(!e)return;this.pausedFor="";const t=new AbortController;this.suggestAbort=t,this.timers.push(window.setTimeout(()=>{g(this.config.sharingId,e,"key",this.shopper,t.signal).then(t=>{this.pausedFor!==e&&this.dispatch({type:"suggested",q:e,products:t})}).catch(()=>{})},80)),this.timers.push(window.setTimeout(()=>{Promise.all([g(this.config.sharingId,e,"pause",this.shopper,t.signal),m(e,this.ctx.root,t.signal)]).then(([t,n])=>{this.pausedFor=e,this.dispatch({type:"suggested",q:e,products:t,collections:n})}).catch(()=>{})},350))}search(e=[]){const i=this.input.value.trim();if(!i)return;this.cancelAll();const r=function(){const e=globalThis.crypto;if(e?.randomUUID)return e.randomUUID();const t=Array.from({length:16},()=>Math.floor(256*Math.random()));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=t.map(e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}();this.notice=null,this.started=performance.now(),this.dispatch({type:"enter",rid:r,drop:e}),this.input.blur(),this.body.scrollTop=0;const s=new AbortController;this.searchAbort=s,async function(e,t,n,i){const r=await fetch(`${p(e)}/search`,{method:"POST",headers:{"Content-Type":"application/json",...f()},body:JSON.stringify(t),signal:i});if(!r.ok||!r.body)throw new d(r.status);const s=r.body.getReader(),o=new TextDecoder,a={buffer:""};for(;;){const{done:e,value:t}=await s.read(),i=e?o.decode()+"\n\n":o.decode(t,{stream:!0});for(const r of l(i,a))try{n(JSON.parse(r.data))}catch{}if(e)return}}(this.config.sharingId,{q:i,rid:r,drop:e,...this.shopper},e=>{this.dispatch({type:"server",rid:r,event:e}),"plan"!==e.type&&t("ai_search_enter",{outcome:e.type,ms:Math.round(performance.now()-this.started),count:"products"in e&&Array.isArray(e.products)?e.products.length:void 0,...this.tag})},s.signal).then(()=>this.dispatch({type:"failed",rid:r})).catch(e=>{if(!s.signal.aborted){if(e instanceof d){const s=(t=e.status,this.config.preview?404===t?{notice:'This preview link no longer works. Open "Try it on your store" in Dori again.',forget:!0}:{notice:"No more preview searches for now. Try again later.",forget:!1}:"leave");return"leave"===s?(this.close(),void location.assign(L(i,this.ctx))):(s.forget&&n(),this.notice=s.notice,void this.dispatch({type:"failed",rid:r}))}var t;this.dispatch({type:"failed",rid:r})}})}loadMore(){const e=this.state.result,t=this.state.rid;if(!t||this.state.loadingMore||!e||"results"!==e.type&&"fallback"!==e.type||null==e.cursor)return;this.dispatch({type:"loading_more",rid:t});const n=new AbortController;this.moreAbort=n,async function(e,t,n,i){const r=await fetch(`${p(e)}/more?${new URLSearchParams({rid:t,cursor:String(n)})}`,{signal:i,headers:f()});if(!r.ok)throw new d(r.status);return await r.json()}(this.config.sharingId,t,e.cursor,n.signal).then(e=>this.dispatch({type:"more",rid:t,products:e.products,cursor:e.cursor})).catch(()=>{n.signal.aborted||this.dispatch({type:"more",rid:t,products:[],cursor:null})})}scrolled(){const e=this.body;e.scrollTop+e.clientHeight>e.scrollHeight-500&&this.loadMore()}clicked(e){const n=e.target;if(n.closest("[data-act='enter']"))return e.preventDefault(),void this.search();const i=n.closest("[data-drop]");if(i)return e.preventDefault(),void this.search([...this.state.drop,i.dataset.drop]);const r=n.closest("a.card, a.row");r&&(t("ai_search_click",{phase:this.state.phase,outcome:this.state.result?.type,id:r.dataset.id,...this.tag}),this.save())}save(){const e=this.state;if("done"!==e.phase||!e.result||!e.rid)return;const t={q:e.asked,rid:e.rid,drop:e.drop,result:e.result,url:location.href,at:Date.now()};try{sessionStorage.setItem(_,JSON.stringify(t))}catch{}}}let U=null,D=null,B=null;function W(e,t,n=null){return!(!e||!0!==e.feature_flags?.ai_search&&!n||t)}function Q(e,t,n,i){return i||(n?t:e?null:t)}function H(e,t,n=null){const r=window,s=Q(!0===e?.feature_flags?.ai_search,n,i(),B);if(!W(e,!0===r.Shopify?.designMode,s))return U?.(),U=null,D=null,B=null,u(null),O?.destroy(),void(O=null);B=s,u(s),D={sharingId:t,preview:!!s},U||(U=function(e,t,n){const i=e=>{const i=e.target;if(!i||"FORM"!==i.tagName||!q(i.getAttribute("action"),n))return;e.preventDefault(),e.stopImmediatePropagation();const r=i.querySelector('input[name="q"]');t(r?.value??"",!0,r??i)},r=e=>{const i=e.target;i&&"INPUT"===i.tagName&&i.matches('input[type="search"], input[name="q"]')&&(i.form?q(i.form.getAttribute("action"),n):i.closest?.($))&&(i.blur?.(),t(i.value??"",!1,i))},s=e=>{const i=e;if(i.defaultPrevented||0!==(i.button??0)||i.metaKey||i.ctrlKey||i.shiftKey||i.altKey)return;const r=e.target;if(!r?.closest)return;const s=r.closest(a);if(!s||"INPUT"===s.tagName)return;if(s.closest(`#${k}`))return;if("FORM"===s.tagName||r.closest("form"))return;if(!("A"===s.tagName?q(s.getAttribute("href"),n):s.closest($)))return;e.preventDefault(),e.stopImmediatePropagation();const o="A"===s.tagName?function(e,t){if(!e)return"";try{return new URL(e,t).searchParams.get("q")??""}catch{return""}}(s.getAttribute("href"),n):"";t(o,!!o,s)};return e.addEventListener("submit",i,!0),e.addEventListener("focusin",r,!0),e.addEventListener("click",s,!0),()=>{e.removeEventListener("submit",i,!0),e.removeEventListener("focusin",r,!0),e.removeEventListener("click",s,!0)}}(window,(e,t,n)=>D&&function(e,t,n,i=null){O||(O=new T(D)),O.open(t,n,i)}(0,e,t,n),location.origin),function(e){let t=null;try{t=JSON.parse(sessionStorage.getItem(_)||"null")}catch{t=null}const n=history.state,i=n?.doriAiSearch?function(e,t,n){return!e||e.url!==t||n-e.at>18e5?null:e}(t,location.href,Date.now()):null;i&&(O||(O=new T(e)),O.restore(i))}(D))}export{H as applyAiSearch,Q as keyForPage,W as wantsAiSearch};
Binary file
Binary file