https://ninjatransfers.com/cdn/shop/t/1064/assets/ai-chat-sandbox.js?v=17743223880029571861789084303
1(function(){"use strict";if(window.__aiChatSandboxInit)return;window.__aiChatSandboxInit=!0;var SKELETON_COUNT=3,AI_BATCH_SIZE=3,AI_MAX_IMAGES=3,SINGLE_SELECT_PATHS=["/products/vinyl-stickers","/products/bumper-stickers","/products/truck-stickers","/products/indoor-floor-graphics","/products/outdoor-floor-graphics","/products/window-clings","/products/low-tac-wall-graphics","/products/custom-magnets","/products/custom-soft-vinyl-keychains"];function isSingleSelectMode(){var path=window.location&&window.location.pathname||"";path.length>1&&path.charAt(path.length-1)==="/"&&(path=path.slice(0,-1));for(var i=0;i<SINGLE_SELECT_PATHS.length;i++)if(path===SINGLE_SELECT_PATHS[i])return!0;return!1}function openAiZoom(src,onUse){if(src){var modal=document.getElementById("ai-pop-zoom-modal");modal||(modal=document.createElement("div"),modal.id="ai-pop-zoom-modal",modal.className="ai-pop-zoom",modal.innerHTML='<div class="ai-pop-zoom__backdrop" data-ai-zoom-close></div><div class="ai-pop-zoom__dialog" role="dialog" aria-modal="true" aria-label="Design preview"><button type="button" class="ai-pop-zoom__close" data-ai-zoom-close aria-label="Close preview"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button><img class="ai-pop-zoom__img" alt="Design preview"><button type="button" class="ai-pop-zoom__use" data-ai-zoom-use>Use This Design →</button></div>',document.body.appendChild(modal),modal.querySelector("[data-ai-zoom-use]").addEventListener("click",function(e){e.preventDefault();var fn=modal.__onUse;closeAiZoom(),typeof fn=="function"&&fn()}),modal.addEventListener("click",function(e){e.target&&e.target.closest&&e.target.closest(".ai-pop-zoom__img")||closeAiZoom()}),document.addEventListener("keydown",function(e){e.key==="Escape"&&closeAiZoom()}));var zimg=modal.querySelector(".ai-pop-zoom__img");modal.__onUse=typeof onUse=="function"?onUse:null,modal.classList.toggle("has-use",!!modal.__onUse),modal.classList.add("is-loading"),zimg.onload=zimg.onerror=function(){modal.classList.remove("is-loading")},zimg.src=src,zimg.complete&&zimg.naturalWidth&&modal.classList.remove("is-loading"),modal.classList.add("is-open"),document.body.classList.add("ai-pop-zoom-open")}}function closeAiZoom(){var modal=document.getElementById("ai-pop-zoom-modal");modal&&modal.classList.remove("is-open"),document.body.classList.remove("ai-pop-zoom-open")}var PILL_PROMPTS={gym:'A modern logo of a bold dumbbell icon in bright electric blue, hot pink, and neon yellow with text that says "Common Ground Athletics" on a pure white background',mama:'A bold modern design of a large floral bouquet in vivid pink, coral, and sage with text that says "Mama" in chunky serif on a white background',party:'A vibrant party design of streamers and stars in hot pink, electric orange, neon green, and bright blue with text that says "Let\'s Party" in wavy groovy letters on a pure white background'},PILL_IMAGE_SETS={gym:["https://ninjauploads-production.imgix.net/a3a8811c0707512c500b4337b1cbd5801eb8f3a721ad2544fb7cce8f675d758e____image_1780430781887_545.png?trim=colorUnlessAlpha&w=2000","https://ninjauploads-production.imgix.net/3e67ee6a61a6891639bf6c2ecbb8c64ad6d1b5c37645f69fc80587c757ef1d15____image_1780430820896_525.png?trim=colorUnlessAlpha&w=2000","https://ninjauploads-production.imgix.net/f77a8eac814f6478a1203f7b363f5db5ce10fccdce03371111d3610ee947ac78____image_1780430840270_190.png?trim=colorUnlessAlpha&w=2000"],mama:["https://ninjauploads-production.imgix.net/732ae824daa1c0aa6e7da4093aab334c5517d94b9a48ac4bd0331e92a318ee2f____image_1780430667741_923.png?trim=colorUnlessAlpha&w=2000","https://ninjauploads-production.imgix.net/4fb5bc31443ede2ce1c725785b5202617b3a22e7e6f4171b5ab368e166c8b537____image_1780430685691_187.png?trim=colorUnlessAlpha&w=2000","https://ninjauploads-production.imgix.net/30cd361986746ac1387fe6245f3c1482b987da91f689cf85d29a4304ac4b98f5____image_1780430702864_542.png?trim=colorUnlessAlpha&w=2000"],party:["https://ninjauploads-production.imgix.net/dcdf2c88bb7486e53d618c3560f81c098f317d8d3d97be2747ebacc372c7ebfc____image_1780428185450_973.png?trim=colorUnlessAlpha&w=2000","https://ninjauploads-
1production.imgix.net/cd13ffc36cfb8a587eb55cd9d886e1e364ba85477f6e08f48319285e8342511c____image_1780428588278_435.png?trim=colorUnlessAlpha&w=2000","https://ninjauploads-production.imgix.net/5eb7b78bc6677a05f994e1612d3fb12ff188e440f0724484a3d5693fa84df245____image_1780428622803_1.png?trim=colorUnlessAlpha&w=2000"]};function normalizePillKey(s){return(s||"").replace(/\s+/g," ").trim().toLowerCase()}var PILL_IMAGE_MAP={};Object.keys(PILL_PROMPTS).forEach(function(slug){PILL_IMAGE_MAP[normalizePillKey(PILL_PROMPTS[slug])]=PILL_IMAGE_SETS[slug].map(function(url,i){return{url:url,thumbnailUrl:url,fileName:slug+"-design-"+(i+1)+".png"}})});function getPillImages(prompt){return PILL_IMAGE_MAP[normalizePillKey(prompt)]||null}function realGenerate(prompt,batchSize){var maxImages=batchSize||AI_MAX_IMAGES;return new Promise(function(resolve,reject){var nativeInput=document.getElementById("AISearchInput"),nativeForm=document.querySelector("#generative-ai-dialog > form"),imagesEl=document.getElementById("generative-ai-images");if(!nativeInput||!nativeForm||!imagesEl){reject(new Error("AI dialog not in DOM"));return}imagesEl.innerHTML="";var preExisting=new Set,resolved=!1,stallTimer=null,settleTimer=null;function readFigures(){for(var figs=imagesEl.querySelectorAll("figure"),newImages=[],i=0;i<figs.length;i++){var f=figs[i],url=f.dataset.url;!url||preExisting.has(url)||newImages.push({url:url,thumbnailUrl:f.querySelector("img")&&f.querySelector("img").src||url,fileName:f.dataset.fileName||"ai-image-"+Date.now()+"-"+i+".png",__figure:f})}return newImages.slice(0,maxImages)}function finish(){if(!resolved){resolved=!0,clearTimeout(stallTimer),clearTimeout(settleTimer);try{mo.disconnect()}catch(_){}var newImages=readFigures();resolve({stats:{remainingRequest:Number.MAX_SAFE_INTEGER},existing:[],newImages:newImages})}}var mo=new MutationObserver(function(){if(clearTimeout(settleTimer),imagesEl.querySelectorAll("figure").length!==0){var loader=document.getElementById("generative-ai-dialog-loader"),loaderDone=!loader||!loader.classList.contains("show"),delay=loaderDone?50:350;settleTimer=setTimeout(finish,delay)}});mo.observe(imagesEl,{childList:!0}),stallTimer=setTimeout(function(){if(!resolved){resolved=!0;try{mo.disconnect()}catch(_){}reject(new Error("AI generate timed out"))}},6e4);var loaderEl=document.getElementById("generative-ai-dialog-loader");if(loaderEl){var loaderObs=new MutationObserver(function(){if(resolved){loaderObs.disconnect();return}!loaderEl.classList.contains("show")&&imagesEl.querySelectorAll("figure").length>0&&(loaderObs.disconnect(),finish())});loaderObs.observe(loaderEl,{attributes:!0,attributeFilter:["class"]})}batchSize&&nativeForm.setAttribute("data-batch-size",String(batchSize)),nativeInput.value=prompt,nativeInput.dispatchEvent(new Event("input",{bubbles:!0})),nativeInput.dispatchEvent(new Event("change",{bubbles:!0}));var jq=window.jQuery||window.$;try{jq&&typeof jq(nativeForm).trigger=="function"?jq(nativeForm).trigger("submit"):typeof nativeForm.requestSubmit=="function"?nativeForm.requestSubmit():nativeForm.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0}))}catch(err){if(resolved)return;resolved=!0,clearTimeout(stallTimer);try{mo.disconnect()}catch(_){}reject(err)}})}function realInsertToCanvas(tile,image,instanceKey,cascadeIndex){return tile.classList&&tile.classList.contains("is-loading")?Promise.resolve():(tile.classList&&tile.classList.add("is-loading"),instanceKey==="ds"?insertOntoFabricCanvas(tile,image,cascadeIndex):instanceKey==="aipage"?stashAndHandoff(image):insertViaCartPipeline(tile,image))}function stashAndHandoff(image){try{sessionStorage.setItem("dtf:pending-ai-uploads:v1",JSON.stringify({items:[{url:image.url,thumbnailUrl:image.thumbnailUrl||image.url,fileName:image.fileName||""}],ts:Date.now()}))}catch(_){}var t=document.createElement("div");return t.style.cssText='position:fixed;left:50%;bottom:32px;transform:translateX(-50%);background:#0f172a;color:#fff;font:600 14px/1.2 "DM Sans",system-ui,sans-serif;padding:14px 22px;border-radius:999px;box-shadow:0 12px 32px rgba(15,23,42,0.25);z-index:99999;pointer-events:none;',t.textContent="Sending design to your DTF order\u2026",document.body.appendChild(t),setTimeout(function(){window.location.assign("/products/dtf-transfers")},250),Promise.resolve()}function insertMultipleViaCartPipeline(entries){var loader=document.getElementById("generative-ai-dialog-loader"),form=document.querySelector("#generative-ai-dialog > form");return loader&&loader.classList.add("show"),form&&form.setAttribute("disabled","disabled"),Promise.resolve().then(function(){var urls=entries.map(function(e){return e.url}
1).filter(Boolean);if(urls.length){if(typeof window.createFileObjectFromUrl=="function"&&(typeof window.multiFilesManageByURL=="function"||typeof window.singleFileManageByURL=="function")){var files=urls.map(function(u){var detail=window.createFileObjectFromUrl(u);return detail.fileURL=u,detail.isAIImage=!0,detail}),_uploadType=typeof window.uploadType!="undefined"?window.uploadType:"",addToCart=function(){return typeof window.singleFileAddToCart=="function"?Promise.resolve(window.singleFileAddToCart()):Promise.resolve()};if(files.length===1)if(_uploadType==="multi"&&typeof window.multiFilesManageByURL=="function")window.multiFilesManageByURL(files);else{if(typeof window.singleFileManageByURL=="function")return addToCart().then(function(){window.singleFileManageByURL(files[0])});typeof window.multiFilesManageByURL=="function"&&window.multiFilesManageByURL(files)}else if(typeof window.multiFilesManageByURL=="function"){if(_uploadType==="single")return addToCart().then(function(){window.multiFilesManageByURL(files)});window.multiFilesManageByURL(files)}return}return Promise.all(urls.map(function(u,i){var entry=entries[i],fileName=entry&&entry.fileName||"ai-image-"+Date.now()+"-"+Math.floor(Math.random()*1e4)+".png";return fetch(u).then(function(r){var type=r.headers.get("Content-Type")||"image/png";return r.arrayBuffer().then(function(ab){var blob=new Blob([ab],{type:type}),file=new File([blob],fileName,{type:type});return file.isAIImage=!0,file})})})).then(function(files2){typeof window.manageFiles=="function"&&window.manageFiles(files2)})}}).then(function(){window.isAIImage=!0;var dialog=document.getElementById("generative-ai-dialog");if(dialog&&typeof dialog.close=="function")try{dialog.close()}catch(_){}}).catch(function(err){console.error("ai-chat-sandbox multi-cart insert failed",err)}).then(function(){loader&&loader.classList.remove("show"),form&&form.removeAttribute("disabled")})}function insertViaCartPipeline(tile,image){var loader=document.getElementById("generative-ai-dialog-loader"),form=document.querySelector("#generative-ai-dialog > form");loader&&loader.classList.add("show"),form&&form.setAttribute("disabled","disabled");var jq=window.jQuery||window.$,url=image.url,fileName=image.fileName||"ai-image-"+Date.now()+"-"+Math.floor(Math.random()*1e4)+".png";if(document.querySelector("multi-upload-wrapper.active")&&typeof window.createFileObjectFromUrl=="function"&&typeof window.multiFilesManageByURL=="function"){try{var beforeBlocks=jq?jq("multi-upload uploaded-files-block").length:0,detail=window.createFileObjectFromUrl(url);detail.fileURL=url,detail.isAIImage=!0,window.multiFilesManageByURL([detail]),setTimeout(function(){typeof window.setFocusOfMultiUpload=="function"&&window.setFocusOfMultiUpload(beforeBlocks)},600)}catch(e){console.error("ai-chat-sandbox multi-mode insert failed",e)}loader&&loader.classList.remove("show"),form&&form.removeAttribute("disabled"),tile.classList&&tile.classList.remove("is-loading");var dialog=document.getElementById("generative-ai-dialog");if(dialog&&typeof dialog.close=="function")try{dialog.close()}catch(_){}return Promise.resolve()}return fetch(url).then(function(response){var type=response.headers.get("Content-Type")||"image/png";return response.arrayBuffer().then(function(ab){return{type:type,buffer:ab}})}).then(function(data){var blob=new Blob([data.buffer],{type:data.type}),file=new File([blob],fileName,{type:data.type}),addToCartPromise=Promise.resolve();return jq&&jq("upload-controls master-upload").hasClass("hidden")&&typeof window.singleFileAddToCart=="function"&&(addToCartPromise=window.singleFileAddToCart()),addToCartPromise.then(function(){return file})}).then(function(file){var isNewBySize=jq?jq("upload-controls").length:0;isNewBySize>0&&typeof window.manageFiles=="function"?(file.isAIImage=!0,window.manageFiles([file])):typeof window.uploadFile=="function"&&(jq&&jq(".step__2").hasClass("hidden")?window.uploadFile(file):window.uploadFile(file,"second_image")),window.isAIImage=!0;var dialog2=document.getElementById("generative-ai-dialog");if(dialog2&&typeof dialog2.close=="function")try{dialog2.close()}catch(_){}}).catch(function(err){console.error("ai-chat-sandbox cart insert failed",err)}).then(function(){loader&&loader.classList.remove("show"),form&&form.removeAttribute("disabled"),tile.classList&&tile.classList.remove("is-loading")})}
1function insertOntoFabricCanvas(tile,image,cascadeIndex){var url=image.url,fileName=image.fileName||"ai-image-"+Date.now()+"-"+Math.floor(Math.random()*1e4)+".png",cascadeOffset=cascadeIndex&&cascadeIndex>0?cascadeIndex*30:0;return fetch(url).then(function(r){return r.blob()}).then(function(blob){var fileType=blob.type||"image/png";if(typeof window.getPresignedUploadUrl!="function")throw new Error("getPresignedUploadUrl unavailable");return window.getPresignedUploadUrl(fileName,fileType).then(function(presign){if(!presign||!presign.url||!presign.sourceUrl)throw new Error("Invalid presigned URL");return fetch(presign.url,{method:"PUT",headers:{"Content-Type":fileType},body:blob}).then(function(uploadRes){if(!uploadRes.ok)throw new Error("Upload failed");return presign.sourceUrl})})}).then(function(uploadedUrl){var canvas=window.fabricCanvas;if(!canvas)throw new Error("Canvas not ready");if(typeof window.fabric=="undefined"||!window.fabric.Image)throw new Error("fabric.Image unavailable");return new Promise(function(resolve,reject){window.fabric.Image.fromURL(uploadedUrl,function(fabricImg){if(!fabricImg){reject(new Error("fabric.Image.fromURL returned null"));return}var maxSize=300,scale=Math.min(maxSize/fabricImg.width,maxSize/fabricImg.height,1);fabricImg.set({scaleX:scale,scaleY:scale,selectable:!0,hasControls:!0}),fabricImg._originalUrl=uploadedUrl,fabricImg._bgRemoved=!1,fabricImg._aiGenerated=!0,typeof window.addObjectToCanvas=="function"?window.addObjectToCanvas(fabricImg,canvas):(canvas.add(fabricImg),canvas.setActiveObject(fabricImg),canvas.requestRenderAll()),cascadeOffset>0&&(fabricImg.set({left:(fabricImg.left||0)+cascadeOffset,top:(fabricImg.top||0)+cascadeOffset}),fabricImg.setCoords(),canvas.requestRenderAll()),resolve()},{crossOrigin:"anonymous"})})}).catch(function(err){console.error("ai-chat-sandbox canvas insert failed",err)}).then(function(){tile.classList&&tile.classList.remove("is-loading")})}var HISTORY_KEY_BASE="ninjaAiHistory",HISTORY_TTL_MS=720*60*60*1e3,HISTORY_MAX=30;(function(){try{if(localStorage.getItem(HISTORY_KEY_BASE))return;var merged=[];if(["ds","dtfut","default"].forEach(function(k){var raw=localStorage.getItem(HISTORY_KEY_BASE+":"+k);if(raw)try{merged=merged.concat(JSON.parse(raw)||[])}catch(_){}}),!merged.length)return;var seen={};merged=merged.filter(function(e){return!e||!e.url||seen[e.url]?!1:(seen[e.url]=1,!0)}),merged.sort(function(a,b){return(b.savedAt||0)-(a.savedAt||0)}),localStorage.setItem(HISTORY_KEY_BASE,JSON.stringify(merged.slice(0,HISTORY_MAX)))}catch(_){}})();function loadHistory(_instanceKey){try{var raw=localStorage.getItem(HISTORY_KEY_BASE),list=raw?JSON.parse(raw):[],cutoff=Date.now()-HISTORY_TTL_MS;return list.filter(function(e){return e&&e.savedAt&&e.savedAt>cutoff})}catch(_){return[]}}function saveHistory(_instanceKey,list){try{localStorage.setItem(HISTORY_KEY_BASE,JSON.stringify(list.slice(0,HISTORY_MAX)))}catch(_){}try{document.dispatchEvent(new CustomEvent("ninjaAiHistory:changed"))}catch(_){}}function rehostEditedImage(srcUrl){var NINJA_IMGIX_HOST="ninjauploads-production.imgix.net";return typeof window.getPresignedUploadUrl!="function"?Promise.reject(new Error("getPresignedUploadUrl unavailable")):fetch(srcUrl).then(function(r){if(!r.ok)throw new Error("Fetch edited image failed ("+r.status+")");return r.blob()}).then(function(blob){var fileType=blob.type||"image/png",key="ai-edit____image_"+Date.now()+"_"+Math.floor(Math.random()*1e3)+".png";return window.getPresignedUploadUrl(key,fileType).then(function(presign){if(!presign||!presign.url||!presign.sourceUrl)throw new Error("Invalid presigned URL");return fetch(presign.url,{method:"PUT",headers:{"Content-Type":fileType},body:blob}).then(function(uploadRes){if(!uploadRes.ok)throw new Error("Upload failed ("+uploadRes.status+")");return{url:"https://"+NINJA_IMGIX_HOST+"/"+key,fileName:key}})})})}function attach(container){if(container.__aiChatBound)return;container.__aiChatBound=!0;var panel=container.querySelector("[data-ai-panel]")||container,batchSize=parseInt(panel.getAttribute("data-ai-batch"),10)||AI_BATCH_SIZE,isV2=panel.classList.contains("ai-chat--v2"),textarea=container.querySelector("[data-ai-prompt]"),errorBox=container.querySelector("[data-ai-error]"),generateBtn=container.querySelector("[data-ai-generate]"),thread=container.querySelector("[data-ai-thread]"),pillsRow=container.querySelector("[data-ai-pills]"),history=container.querySelector("[data-ai-history]"),historyGrid=container.querySelector("[data-ai-history-grid]"),historyClear=container.querySelector("[data-ai-history-clear]"),historyToggle=container.querySelector("[data-ai-history-toggle]"),historyToggleLabel=container.querySelector("[data-ai-history-toggle-label]"),clearBtn=container.querySelector("[data-ai-clear]");
1if(!panel||!textarea||!generateBtn||!thread)return;var wrap=textarea.closest(".ai-chat-input-wrap"),countEl=container.querySelector("[data-ai-count]"),maxLen=parseInt(textarea.getAttribute("maxlength"),10)||0;function syncCount(){countEl&&(countEl.textContent=textarea.value.length+(maxLen?" / "+maxLen:""))}textarea.addEventListener("input",syncCount),syncCount();var instanceKey=container.getAttribute("data-ai-instance")||"default",editSourceUrl=null,sendLabelEl=generateBtn.querySelector(".ai-chat-send-label"),defaultPromptPlaceholder=textarea.getAttribute("placeholder")||"";function hasEditAffordance(){return typeof window.nbEditRequest=="function"}var EDIT_DONE_MSG="Each prompt makes a fresh set of designs. To refine one, hit Edit and describe your change.",NOEDIT_DONE_MSG="Each prompt generates a completely new image. To make changes, describe the full image again with your updates.";function generationDoneMsg(){return hasEditAffordance()?EDIT_DONE_MSG:NOEDIT_DONE_MSG}var NARROW_BREAKPOINT=500,forceNarrow=panel.getAttribute("data-ai-narrow-mode")==="force";function syncNarrow(){if(forceNarrow){panel.classList.add("ai-chat--narrow");return}var w=panel.getBoundingClientRect().width,bp=isV2?600:NARROW_BREAKPOINT;panel.classList.toggle("ai-chat--narrow",w>0&&w<bp-1)}syncNarrow();try{new ResizeObserver(syncNarrow).observe(panel)}catch(_){}if(isV2){var composerEl0=container.querySelector(".ai-chat-composer");if(composerEl0){var regenEl=document.createElement("div");regenEl.className="ai-chat-v2__regen",regenEl.innerHTML='<button type="button" class="ai-chat-v2__regen-btn"><svg class="ai-chat-v2__regen-ico" viewBox="0 0 24 24" width="15" height="15" aria-hidden="true" focusable="false"><polyline points="23 4 23 10 17 10" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>Generate new</button>',thread.appendChild(regenEl);var restart=function(prefill){var cap=thread.querySelector(".ai-chat-v2__caption"),last=cap&&cap.dataset.prompt||"";exitEditMode(),clearThreadResults(),panel.classList.remove("is-regen","has-results"),textarea.value=prefill?last:"",syncCount(),autosizeTextarea(),updateGenerateEnabled();try{textarea.focus(),prefill&&textarea.setSelectionRange(textarea.value.length,textarea.value.length)}catch(_){}};regenEl.querySelector(".ai-chat-v2__regen-btn").addEventListener("click",function(){restart(!1)}),panel.addEventListener("ai-chat:reset",function(){generateBtn.classList.contains("is-loading")||!panel.classList.contains("has-results")&&!editSourceUrl&&!textarea.value||restart(!1)})}}isV2&&document.addEventListener("click",function(e){if(panel.classList.contains("is-editing")){var t=e.target;!t||!t.closest||t.closest(".ai-chat-composer")||t.closest(".ai-pop-tile-edit")||t.closest(".ai-pop-zoom")||exitEditMode()}});var leftArrow=null,rightArrow=null;if(historyGrid){var scroller=document.createElement("div");scroller.className="ai-chat-history-scroller",historyGrid.parentNode.insertBefore(scroller,historyGrid),scroller.appendChild(historyGrid),leftArrow=document.createElement("button"),leftArrow.type="button",leftArrow.className="ai-chat-history-arrow ai-chat-history-arrow--left",leftArrow.setAttribute("aria-label","Scroll left"),leftArrow.innerHTML='<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><path d="M10 12L6 8l4-4"/></svg>',rightArrow=document.createElement("button"),rightArrow.type="button",rightArrow.className="ai-chat-history-arrow ai-chat-history-arrow--right",rightArrow.setAttribute("aria-label","Scroll right"),rightArrow.innerHTML='<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><path d="M6 4l4 4-4 4"/></svg>',scroller.appendChild(leftArrow),scroller.appendChild(rightArrow);var stepFor=function(){return Math.max(160,Math.round(historyGrid.clientWidth*.6))};leftArrow.addEventListener("click",function(){smoothScrollBy(historyGrid,-stepFor())}),rightArrow.addEventListener("click",function(){smoothScrollBy(historyGrid,stepFor(
1))}),historyGrid.addEventListener("scroll",function(){updateArrowVisibility()},{passive:!0});try{new ResizeObserver(function(){updateArrowVisibility()}).observe(historyGrid)}catch(_){}}function updateArrowVisibility(){if(!(!historyGrid||!leftArrow||!rightArrow)){var max=historyGrid.scrollWidth-historyGrid.clientWidth,x=historyGrid.scrollLeft;leftArrow.classList.toggle("is-visible",x>4),rightArrow.classList.toggle("is-visible",max>4&&x<max-4)}}function smoothScrollBy(el,delta){var start=el.scrollLeft,max=el.scrollWidth-el.clientWidth,target=Math.max(0,Math.min(start+delta,max)),duration=220,startTime=performance.now();function step(){var t=Math.min(1,(performance.now()-startTime)/duration),ease=t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;el.scrollLeft=start+(target-start)*ease,t<1?setTimeout(step,16):updateArrowVisibility()}step()}var anchorGrid=null;function scrollThreadToBottom(){var target=thread.scrollHeight-thread.clientHeight;if(anchorGrid&&anchorGrid.isConnected){var gridTop=anchorGrid.getBoundingClientRect().top-thread.getBoundingClientRect().top+thread.scrollTop-8;target=Math.min(target,Math.max(0,gridTop))}thread.scrollTop=target;try{if(window.matchMedia&&window.matchMedia("(max-width: 749px)").matches){for(var node=panel;node&&node!==document.body;){var cs=window.getComputedStyle(node);cs&&(cs.overflowY==="auto"||cs.overflowY==="scroll")&&(node.scrollTop=node.scrollHeight),node=node.parentElement}var scrollTarget=panel.querySelector("[data-ai-history]")||panel.querySelector(".ai-chat-history")||panel.querySelector(".ai-chat-composer")||panel.querySelector("[data-ai-prompt]");scrollTarget&&typeof scrollTarget.scrollIntoView=="function"&&scrollTarget.scrollIntoView({block:"end",behavior:"smooth"})}}catch(_){}}function updateScrolledState(){var distanceFromBottom=thread.scrollHeight-thread.scrollTop-thread.clientHeight,isScrolled=thread.scrollTop>4&&distanceFromBottom>4;panel.classList.toggle("is-scrolled",isScrolled)}thread.addEventListener("scroll",updateScrolledState,{passive:!0});function autosizeTextarea(){if(isV2&&wrap){if(wrap.classList.remove("is-multiline"),!textarea.value.trim()){textarea.style.height="";return}textarea.style.height="0px",textarea.style.height=textarea.scrollHeight+"px";return}if(textarea.style.height="auto",!textarea.value.trim()){wrap&&(wrap.classList.remove("is-multiline"),!wrap.__singleLineHeight&&textarea.scrollHeight>0&&(wrap.__singleLineHeight=textarea.scrollHeight));return}if(!wrap){textarea.style.height=textarea.scrollHeight+"px";return}var singleH=wrap.__singleLineHeight||32;wrap.classList.remove("is-multiline");var rowH=textarea.scrollHeight;rowH>singleH+4?(wrap.classList.add("is-multiline"),textarea.style.height=textarea.scrollHeight+"px"):textarea.style.height=rowH+"px"}var _typewriterTimer=null;function appendUserMessage(promptText){var msg=document.createElement("div");if(isV2){msg.className="ai-chat-v2__caption",msg.dataset.prompt=promptText;var badge=document.createElement("span");badge.className="ai-chat-v2__badge",badge.setAttribute("aria-hidden","true"),badge.innerHTML='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2 13.6 9.1 20.5 11 13.6 12.9 12 20 10.4 12.9 3.5 11 10.4 9.1 12 2Z"/><path d="M19 3 19.7 5.3 22 6 19.7 6.7 19 9 18.3 6.7 16 6 18.3 5.3 19 3Z" opacity=".75"/></svg>';var chip=document.createElement("span");chip.className="ai-chat-v2__caption-text",chip.title=promptText;var eyebrow=document.createElement("small");eyebrow.className="ai-chat-v2__caption-eyebrow",eyebrow.textContent="Your prompt";var big=document.createElement("b");return big.className="ai-chat-v2__caption-prompt",big.textContent=promptText,chip.appendChild(eyebrow),chip.appendChild(big),msg.appendChild(badge),msg.appendChild(chip),regenEl&&msg.appendChild(regenEl),thread.appendChild(msg),anchorGrid=null,scrollThreadToBottom(),msg}msg.className="ai-chat-msg ai-chat-msg--user";var bubble=document.createElement("div");return bubble.className="ai-chat-bubble",bubble.textContent=promptText,msg.appendChild(bubble),thread.appendChild(msg),anchorGrid=null,scrollThreadToBottom(),msg}function appendAiMessage(skeletonCount){var msg=document.createElement("div");msg.className="ai-chat-msg ai-chat-msg--ai";var grid=document.createElement("div");grid.className="ai-pop-grid";for(var n=skeletonCount||batchSize,i=0;i<n;i++){var sk=document.createElement("div");sk.className="ai-pop-tile is-skeleton",grid.appendChild(sk)}return msg.appendChild(grid),thread.appendChild(msg),panel.classList.add("has-results"),anchorGrid=grid,scrollThreadToBottom(),{msg:msg,grid:grid}}function clearThreadResults(){regenEl&®enEl.parentNode&&thread.appendChild(regenEl),Array.prototype.forEach.call(thread.querySelectorAll(".ai-chat-msg, .ai-chat-v2__caption"),function(el){el.parentNode&&el.parentNode.removeChild(el)}),anchorGrid=null}function lastConceptGrid(){var grids=thread.querySelectorAll(".ai-pop-grid");return grids.length?grids[grids.length-1]:null}
1function gridStep(grid){var c=grid.children;return c.length>1?c[1].offsetLeft-c[0].offsetLeft:grid.clientWidth}function revealGridStart(grid){try{grid.scrollTo({left:0,behavior:"smooth"})}catch(_){grid.scrollLeft=0}}function updateNavState(grid){var msg=grid.parentNode;if(msg){var prev=msg.querySelector(".ai-chat-v2__nav--prev"),next=msg.querySelector(".ai-chat-v2__nav--next"),max=grid.scrollWidth-grid.clientWidth-1;prev&&(prev.disabled=grid.scrollLeft<=0),next&&(next.disabled=grid.scrollLeft>=max)}}function syncConceptNav(grid){if(!(!isV2||!grid)){var msg=grid.parentNode;if(msg){var visible=panel.classList.contains("ai-chat--narrow")?2:3,more=grid.children.length>visible;msg.classList.toggle("has-more",more),more&&(msg.querySelector(".ai-chat-v2__nav")||(["prev","next"].forEach(function(dir){var b=document.createElement("button");b.type="button",b.className="ai-chat-v2__nav ai-chat-v2__nav--"+dir,b.setAttribute("aria-label",dir==="prev"?"Previous concepts":"More concepts"),b.innerHTML='<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="'+(dir==="prev"?"M10 3L5 8l5 5":"M6 3l5 5-5 5")+'"/></svg>',b.addEventListener("click",function(){var step=gridStep(grid);try{grid.scrollBy({left:dir==="prev"?-step:step,behavior:"smooth"})}catch(_){grid.scrollLeft+=dir==="prev"?-step:step}}),msg.appendChild(b)}),grid.addEventListener("scroll",function(){updateNavState(grid)},{passive:!0})),updateNavState(grid))}}}function appendAiTextMessage(text,onDone){var msg=document.createElement("div");if(isV2)return onDone&&onDone(),msg;msg.className="ai-chat-msg ai-chat-msg--ai";var bubble=document.createElement("div");bubble.className="ai-chat-bubble",msg.appendChild(bubble),thread.appendChild(msg),_typewriterTimer&&clearTimeout(_typewriterTimer);var i=0,SPEED=6;function step(){if(i>=text.length){onDone&&onDone();return}bubble.textContent=text.slice(0,++i),scrollThreadToBottom(),_typewriterTimer=setTimeout(step,SPEED)}return step(),msg}function fillGrid(grid,images,prompt){if(grid.innerHTML="",!images.length){showGridError(grid,"No images returned \u2014 try describing your design differently.",null);return}if(images.forEach(function(img){grid.appendChild(createTile(img))}),isV2){syncConceptNav(grid);var imgs=grid.querySelectorAll("img"),pendingImgs=imgs.length,oneImg=function(){--pendingImgs<=0&&panel.classList.add("is-regen")};pendingImgs||panel.classList.add("is-regen"),Array.prototype.forEach.call(imgs,function(im){if(im.complete&&im.naturalWidth){oneImg();return}im.addEventListener("load",oneImg,{once:!0}),im.addEventListener("error",oneImg,{once:!0})})}anchorGrid=grid,Array.prototype.forEach.call(grid.querySelectorAll("img"),function(im){im.complete||im.addEventListener("load",scrollThreadToBottom,{once:!0})}),addToHistory(images,prompt)}function addToHistory(images,prompt){if(history){var existing=loadHistory(instanceKey),next=images.map(function(img){return{url:img.url,thumbnailUrl:img.thumbnailUrl||img.url,fileName:img.fileName||"",prompt:prompt||"",savedAt:Date.now()}}).concat(existing),seen={};next=next.filter(function(e){return!e||!e.url||seen[e.url]?!1:(seen[e.url]=1,!0)}),saveHistory(instanceKey,next),renderHistory(),isV2||setHistoryCollapsed(!1)}}var selection=new Set;function renderHistory(){if(!(!history||!historyGrid)){var list=loadHistory(instanceKey);historyGrid.innerHTML="";var urls=new Set(list.map(function(e){return e.url}));if(Array.from(selection).forEach(function(u){urls.has(u)||selection.delete(u)}),!list.length){updateSelectionBar();return}list.forEach(function(entry){var tile=document.createElement("button");tile.type="button",tile.className="ai-chat-history-tile",tile.dataset.url=entry.url,selection.has(entry.url)&&tile.classList.add("is-selected");var img=document.createElement("img");img.src=entry.thumbnailUrl,img.alt="AI generation",tile.appendChild(img);var select=document.createElement("button");if(select.type="button",select.className="ai-chat-history-tile-select",selection.has(entry.url)?(select.classList.add("is-selected"),select.setAttribute("aria-pressed","true")):select.setAttribute("aria-pressed","fal
1se"),select.setAttribute("aria-label",selection.has(entry.url)?"Deselect AI image":"Select AI image"),select.innerHTML='<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3.5 8 6.5 11 12.5 5"/></svg>',select.addEventListener("click",function(e){e.stopPropagation();var isSelected;selection.has(entry.url)?(selection.delete(entry.url),isSelected=!1):(isSingleSelectMode()&&selection.size>0&&(selection.clear(),historyGrid&&historyGrid.querySelectorAll(".ai-chat-history-tile.is-selected").forEach(function(t){t.classList.remove("is-selected");var sel=t.querySelector(".ai-chat-history-tile-select");sel&&(sel.classList.remove("is-selected"),sel.setAttribute("aria-pressed","false"),sel.setAttribute("aria-label","Select AI image"))})),selection.add(entry.url),isSelected=!0),tile.classList.toggle("is-selected",isSelected),select.classList.toggle("is-selected",isSelected),select.setAttribute("aria-pressed",isSelected?"true":"false"),select.setAttribute("aria-label",isSelected?"Deselect AI image":"Select AI image"),updateSelectionBar()}),tile.appendChild(select),hasEditAffordance()){var histEdit=document.createElement("button");histEdit.type="button",histEdit.className="ai-chat-history-tile-edit",histEdit.setAttribute("aria-label","Edit this image"),histEdit.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>',histEdit.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),enterEditMode(entry.url,entry.thumbnailUrl||entry.url)}),tile.appendChild(histEdit)}var remove=document.createElement("span");remove.className="ai-chat-history-tile-remove",remove.setAttribute("role","button"),remove.setAttribute("aria-label","Remove from history"),remove.tabIndex=0,remove.textContent="\xD7";var removeEntry=function(e){e.stopPropagation();var next=loadHistory(instanceKey).filter(function(x){return x.url!==entry.url});saveHistory(instanceKey,next),selection.delete(entry.url),renderHistory()};remove.addEventListener("click",removeEntry),remove.addEventListener("keydown",function(e){(e.key==="Enter"||e.key===" ")&&removeEntry(e)}),tile.appendChild(remove),tile.addEventListener("click",function(){var isSelected;selection.has(entry.url)?(selection.delete(entry.url),isSelected=!1):(isSingleSelectMode()&&selection.size>0&&(selection.clear(),historyGrid&&historyGrid.querySelectorAll(".ai-chat-history-tile.is-selected").forEach(function(t){t.classList.remove("is-selected");var sel=t.querySelector(".ai-chat-history-tile-select");sel&&(sel.classList.remove("is-selected"),sel.setAttribute("aria-pressed","false"),sel.setAttribute("aria-label","Select AI image"))})),selection.add(entry.url),isSelected=!0),tile.classList.toggle("is-selected",isSelected),select.classList.toggle("is-selected",isSelected),select.setAttribute("aria-pressed",isSelected?"true":"false"),select.setAttribute("aria-label",isSelected?"Deselect AI image":"Select AI image"),updateSelectionBar()}),historyGrid.appendChild(tile)}),updateSelectionBar(),updateArrowVisibility()}}function buildHandoffUrl(productPath,entries){if(entries.length===1)return productPath+"?file="+encodeURIComponent(entries[0].url);var payload=entries.map(function(e,i){return{id:"ai-"+Date.now()+"-"+i,name:e.fileName||"ai-image-"+(i+1)+".png",fileURL:e.url}});return productPath+"?my_designs_selection="+encodeURIComponent(JSON.stringify(payload))}function showHandoffToast(count){var t=document.createElement("div");t.style.cssText='position:fixed;left:50%;bottom:32px;transform:translateX(-50%);background:#0f172a;color:#fff;font:600 14px/1.2 "DM Sans",system-ui,sans-serif;padding:14px 22px;border-radius:999px;box-shadow:0 12px 32px rgba(15,23,42,0.25);z-index:99999;pointer-events:none;',t.textContent="Sending "+count+" design"+(count===1?"":"s")+"\u2026",document.body.appendChild(t)}function navigateToHandoff(productPath,entries){var url=buildHandoffUrl(productPath,entries);return showHandoffToast(entries.length),setTimeout(function(){window.location.assign(url)},250),Promise.resolve()}var selectionBar=null;function ensureSelectionBar(){if(selectionBar)return selectionBar;var bar=document.createElement("div");return bar.className="ai-chat-history-selection-bar",bar.setAttribute("role","regi
1on"),bar.setAttribute("aria-label","AI image selection actions"),bar.innerHTML='<span class="ai-chat-history-selection-bar__count" data-ai-selection-count>0 selected</span><button type="button" class="ai-chat-history-selection-bar__clear" data-ai-selection-clear>Deselect all</button><button type="button" class="ai-chat-history-selection-bar__cta" data-ai-selection-cta><span data-ai-selection-cta-label>Use Designs</span></button><button type="button" class="ai-chat-history-selection-bar__cta-secondary" data-ai-selection-cta-secondary style="display:none"><span data-ai-selection-cta-secondary-label>Other Ordering Options</span></button>',history.appendChild(bar),bar.querySelector("[data-ai-selection-clear]").addEventListener("click",function(){selection.clear(),renderHistory()}),bar.querySelector("[data-ai-selection-cta]").addEventListener("click",function(ev){ev.stopPropagation();var urls=Array.from(selection);if(urls.length){var seenUrls={},entries=loadHistory(instanceKey).filter(function(e){return!e||!selection.has(e.url)||seenUrls[e.url]?!1:(seenUrls[e.url]=1,!0)}),done=function(){selection.clear(),renderHistory()};instanceKey==="aipage"?navigateToHandoff("/products/dtf-transfers",entries).then(done):instanceKey==="dtfut"?entries.length===1?insertViaCartPipeline(document.createElement("div"),{url:entries[0].url,thumbnailUrl:entries[0].thumbnailUrl,fileName:entries[0].fileName,prompt:entries[0].prompt}).then(done):(document.dispatchEvent(new CustomEvent("md-picker:use-designs",{bubbles:!0,detail:{items:entries.map(function(entry){return{file:entry.url,fileName:entry.fileName||"ai-image.png",id:"ai-"+(entry.ts||Date.now()),isAIImage:!0}})}})),done()):Promise.all(entries.map(function(entry,idx){return realInsertToCanvas(document.createElement("div"),{url:entry.url,thumbnailUrl:entry.thumbnailUrl,fileName:entry.fileName,prompt:entry.prompt},instanceKey,idx)})).then(done)}}),bar.querySelector("[data-ai-selection-cta-secondary]").addEventListener("click",function(ev){if(ev.stopPropagation(),instanceKey==="aipage"){var urls=Array.from(selection);if(urls.length){var seenUrls={},entries=loadHistory(instanceKey).filter(function(e){return!e||!selection.has(e.url)||seenUrls[e.url]?!1:(seenUrls[e.url]=1,!0)}),done=function(){selection.clear(),renderHistory()};entries.length===1?document.dispatchEvent(new CustomEvent("aip-oo:open",{detail:{imageUrl:entries[0].url}})):navigateToHandoff("/products/uv-dtf-stickers-decals-by-size",entries).then(done)}}}),selectionBar=bar,bar}function updateSelectionBar(){var count=selection.size;if(!count){selectionBar&&selectionBar.classList.remove("is-visible"),history&&history.classList.remove("is-selecting");return}var bar=ensureSelectionBar();bar.querySelector("[data-ai-selection-count]").textContent=count+" items selected";var primaryLabel=bar.querySelector("[data-ai-selection-cta-label]"),secondaryBtn=bar.querySelector("[data-ai-selection-cta-secondary]"),secondaryLabel=bar.querySelector("[data-ai-selection-cta-secondary-label]");instanceKey==="aipage"?(primaryLabel.textContent="Order as DTF",secondaryLabel.textContent=count===1?"Other Ordering Options":"Order as UV DTF",secondaryBtn.style.display=""):(primaryLabel.textContent=count===1?"Use Design":"Use Designs",secondaryBtn.style.display="none"),bar.classList.add("is-visible"),history.classList.add("is-selecting")}function createTile(image){var tile=document.createElement("div");tile.className="ai-pop-tile",tile.dataset.url=image.url,selection.has(image.url)&&tile.classList.add("is-selected");var img=document.createElement("img");img.src=image.thumbnailUrl||image.url,img.alt="AI generation",tile.appendChild(img);var cta=document.createElement("span");cta.className="ai-pop-tile-cta",cta.innerHTML='Use this design<svg class="ai-pop-tile-cta__arrow" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 8h10M9 4l4 4-4 4"/></svg>',tile.appendChild(cta);var zoom=document.createElement("button");if(zoom.type="button",zoom.className="ai-pop-tile-zoom",zoom.setAttribute("aria-label","Preview full size"),zoom.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/></svg>',zoom.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),openAiZoom(image.url||image.thumbnailUrl||img.src,function(){tile.click()})}),tile.appendChild(zoom),hasEditAffordance()){var editBtn=document.createElement("button");editBtn.type="button",editBtn.className="ai-pop-tile-edit",editBtn.setAttribute("aria-label","Edit this image"),editBtn.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>'+(isV2?'<span class="ai-pop-tile-edit__long">Edit design with AI</span><span class="ai-pop-tile-edit__short">Edit with AI</span>':"<span>Edit</span>"),editBtn.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),enterEditMode(image.url,image.thumbnailUrl||img.src)}),tile.appendChild(editBtn)}return tile.addEventListener("click",function(){if(instanceKey==="aipage"){var url=image.url;if(selection.has(url))selection.delete(url),tile.classList.remove("is-selected");else{if(isSingleSelectMode()&&selection.size>0){var prev=Array.from(selection);selection.clear(),prev.forEach(function(u){var t=document.querySelector('.ai-pop-tile[data-url="'+u+'"]');t&&t.classList.remove("is-selected")})}selection.add(url),tile.classList.add("is-selected")}renderHistory(),updateSelectionBar();return}realInsertToCanvas(tile,image,instanceKey)}),tile}
1function showGridError(grid,message,onRetry){var msgEl=grid.parentNode;msgEl&&msgEl.removeChild(grid);var wrap2=document.createElement("div");wrap2.style.cssText="display:flex;flex-direction:column;gap:8px;align-items:flex-start";var bubble=document.createElement("div");if(bubble.className="ai-chat-bubble",bubble.textContent=message,wrap2.appendChild(bubble),onRetry){var btn=document.createElement("button");btn.type="button",btn.className="ai-chat-retry-btn",btn.textContent="Try again",btn.addEventListener("click",function(){msgEl&&msgEl.removeChild(wrap2);var newGrid=document.createElement("div");newGrid.className="ai-pop-grid";for(var i=0;i<batchSize;i++){var sk=document.createElement("div");sk.className="ai-pop-tile is-skeleton",newGrid.appendChild(sk)}msgEl&&msgEl.appendChild(newGrid),anchorGrid=newGrid,onRetry(newGrid)}),wrap2.appendChild(btn)}msgEl&&msgEl.appendChild(wrap2),scrollThreadToBottom()}function runGenerationIntoGrid(prompt,grid){var hadResults=!1;realGenerate(prompt,batchSize).then(function(res){var stats=res.stats||{},existing=res.existing||[],newImages=res.newImages||[],remaining=stats.remainingRequest?Math.ceil(stats.remainingRequest/batchSize):Number.MAX_SAFE_INTEGER;if(remaining<=0){showGridError(grid,"You've reached the AI generation limit. Try again later.",null);return}var combined=existing.concat(newImages);fillGrid(grid,combined,prompt),hadResults=combined.length>0,scrollThreadToBottom()}).catch(function(err){console.error("AI chat generate failed",err),showGridError(grid,"Generation failed \u2014 please try again.",function(newGrid){generateBtn.classList.add("is-loading"),generateBtn.disabled=!0,runGenerationIntoGrid(prompt,newGrid)})}).then(function(){hadResults&&appendAiTextMessage(generationDoneMsg()),generateBtn.classList.remove("is-loading"),updateGenerateEnabled()})}function generate(){var prompt=(textarea.value||"").trim();if(errorBox&&(errorBox.textContent=""),!!prompt){if(editSourceUrl){runEdit(prompt,editSourceUrl);return}generateBtn.classList.add("is-loading"),generateBtn.disabled=!0,isV2&&clearThreadResults(),appendUserMessage(prompt),textarea.value="",syncCount(),autosizeTextarea(),appendAiTextMessage("Generating your Images");var ctx=appendAiMessage();runGenerationIntoGrid(prompt,ctx.grid)}}function showEditChip(thumbUrl){var composer=container.querySelector(".ai-chat-composer");if(composer){var chip=composer.querySelector("[data-ai-edit-chip]");if(!chip){chip=document.createElement("div"),chip.className="ai-chat-edit-chip",chip.setAttribute("data-ai-edit-chip",""),chip.innerHTML='<img class="ai-chat-edit-chip__thumb" alt="Editing this image"><span class="ai-chat-edit-chip__label">Editing this image</span><button type="button" class="ai-chat-edit-chip__cancel" aria-label="Cancel edit"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true"><path d="M3 3l10 10M13 3L3 13"/></svg></button>';var wrapEl=composer.querySelector(".ai-chat-input-wrap");composer.insertBefore(chip,wrapEl||composer.firstChild),chip.querySelector(".ai-chat-edit-chip__cancel").addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),exitEditMode()})}var thumb=chip.querySelector(".ai-chat-edit-chip__thumb");thumb&&(thumb.src=thumbUrl||""),chip.style.display=isV2?"none":"flex"}}function armTouchTap(btn,fn){if(!(!btn||btn.__v2TouchTap||!("ontouchstart"in window))){btn.__v2TouchTap=!0;var start=null;btn.addEventListener("touchstart",function(e){var t=e.touches&&e.touches[0];start=t?{x:t.clientX,y:t.clientY}:null},{passive:!0}),btn.addEventListener("touchend",function(e){if(!(!isV2||!editSourceUrl||btn.disabled)){var t=e.changedTouches&&e.changedTouches[0];if(!(start&&t&&(Math.abs(t.clientX-start.x)>12||Math.abs(t.clientY-start.y)>12))){e.preventDefault();try{textarea.blur()}catch(_){}fn()}}})}}var composerHome=null;function inlineComposerFor(srcUrl){var composerEl=container.querySelector(".ai-chat-composer"),tiles=thread.querySelectorAll(".ai-pop-tile"),editTile=null;if(Array.prototype.forEach.call(tiles,function(t){t.classList.remove("is-editing"),!editTile&&t.dataset.url===srcUrl&&(editTile=t)}),!(!editTile||!composerEl)){editTile.classList.add("is-editing"),composerHome||(composerHome={parent:composerEl.parentNode,next:composerEl.nextSibling});var msgEl=editTile.parentNode&&editTile.parentNode.parentNode;msgEl&&msgEl.parentNode?msgEl.parentNode.insertBefore(composerEl,msgEl.nextSibling):editTile.appendChild(composerEl),composerEl.classList.add("ai-chat-composer--inline","ai-chat-composer--below");var wrapEl=composerEl.querySelector(".ai-chat-input-wrap");if(wrapEl&&!wrapEl.querySelector("[data-ai-v2-cancel]")){var cancelBtn=document.createElement("button");cancelBtn.type="button",cancelBtn.className="ai-chat-v2__cancel",cancelBtn.setAttribute("data-ai-v2-cancel",""),cancelBtn.textContent="Cancel",cancelBtn.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),exitEditMode()}),armTouchTap(cancelBtn,exitEditMode),wrapEl.appendChild(cancelBtn)}composerEl.__v2Stop||(composerEl.addEventListener("click",function(e){e.stopPropagation()}),composerEl.__v2Stop=!0),panel.classList.add("is-editing")}}function restoreComposer(){Array.prototype.forEach.call(thread.querySelectorAll(".ai-pop-tile.is-editing"),function(t){t.classList.remove("is-editing")});var composerEl=container.querySelector(".ai-chat-composer");composerEl&&composerHome&&composerEl.classList.contains("ai-chat-composer--inline")&&(composerHome.parent.insertBefore(composerEl,composerHome.next),composerEl.classList.remove("ai-chat-composer--inline","ai-chat-composer--below")),panel.classList.remove("is-editing")}function enterEditMode(srcUrl,thumbUrl){if(srcUrl){if(isV2&&editSourceUrl===srcUrl&&panel.classList.contains("is-editing")){exitEditMode();return}if(editSourceUrl=srcUrl,showEditChip(thumbUrl||srcUrl),isV2&&inlineComposerFor(srcUrl),sendLabelEl&&(sendLabelEl.textContent=isV2?"Apply edit":"Edit",sendLabelEl.hasAttribute("data-loading")&&sendLabelEl.setAttribute("data-loading","Editing\u2026")),textarea.setAttribute("placeholder",isV2?"What should change? e.g. make the dog a husky, add snow\u2026":"Describe your change\u2026"),textarea.value="",syncCount(),autosizeTextarea(),updateGenerateEnabled(),isV2){var box=container.querySelector(".ai-chat-composer--inline");if(box&&typeof box.scrollIntoView=="function")try{box.scrollIntoView({block:"center"})}catch(_){box.scrollIntoView()}try{textarea.focus({preventScroll:!0})}catch(_){try{textarea.focus()}catch(__){}}}else{try{textarea.focus()}catch(_){}scrollThreadToBottom()}}}function exitEditMode(){editSourceUrl=null,isV2&&restoreComposer();var chip=container.querySelector("[data-ai-edit-chip]");chip&&(chip.style.display="none"),sendLabelEl&&(sendLabelEl.textContent=generateBtn.getAttribute("data-ai-generate-label")||"Generate",sendLabelEl.hasAttribute("data-loading")&&sendLabelEl.setAttribute("data-loading","Generating\u2026")),textarea.setAttribute("placeholder",defaultPromptPlaceholder),updateGenerateEnabled()}function runEdit(prompt,srcUrl){if(typeof window.canUseAiRequest=="function"&&!window.canUseAiRequest()){errorBox&&(errorBox.textContent="You have reached your AI limit for today.");return}if(typeof window.nbEditRequest!="function"){errorBox&&(errorBox.textContent="AI editing is unavailable right now.");return}generateBtn.classList.add("is-loading"),generateBtn.disabled=!0;var rowGrid=isV2?lastConceptGrid():null;if(rowGrid){var capEl=thread.querySelector(".ai-chat-v2__caption");if(capEl){capEl.dataset.prompt=prompt;var capPrompt=capEl.querySelector(".ai-chat-v2__caption-prompt"),capText=capEl.querySelector(".ai-chat-v2__caption-text");capPrompt&&(capPrompt.textContent=prompt),capText&&(capText.title=prompt)}textarea.value="",syncCount(),autosizeTextarea(),exitEditMode();var skel=document.createElement("div");skel.className="ai-pop-tile is-skeleton",rowGrid.insertBefore(skel,rowGrid.firstChild),syncConceptNav(rowGrid),revealGridStart(rowGrid),window.nbEditRequest(srcUrl,prompt).then(function(falUrl){return rehostEditedImage(falUrl)}).then(function(hosted){var img={url:hosted.url,thumbnailUrl:hosted.url,fileName:hosted.fileName},tile=createTile(img);skel.parentNode===rowGrid?rowGrid.replaceChild(tile,skel):rowGrid.insertBefore(tile,rowGrid.firstChild),addToHistory([img],prompt),syncConceptNav(rowGrid),revealGridStart(rowGrid)}).catch(function(err){console.error("ai-chat-sandbox edit failed",err),skel.parentNode&&skel.parentNode.removeChild(skel),syncConceptNav(rowGrid),errorBox&&(errorBox.textContent="Edit failed \u2014 try again, or describe a new design.")}).then(function(){generateBtn.classList.remove("is-loading"),updateGenerateEnabled()});return}appendUserMessage(prompt),textarea.value="",syncCount(),autosizeTextarea(),exitEditMode(),appendAiTextMessage("Editing your image");var ctx=appendAiMessage(1),grid=ctx.grid;window.nbEditRequest(srcUrl,prompt).then(function(falUrl){return rehostEditedImage(falUrl)}).then(function(hosted){fillGrid(grid,[{url:hosted.url,thumbnailUrl:hosted.url,fileName:hosted.fileName}],prompt),appendAiTextMessage("Edited image ready \u2014 refine it again or tap \u201CUse this design.\u201D"),generateBtn.classList.remove("is-loading"),updateGenerateEnabled(),scrollThreadToBottom()}).catch(function(err){console.error("ai-chat-sandbox edit failed",err),showGridError(gr
1id,"Edit failed \u2014 try again, or describe a new design.",null),generateBtn.classList.remove("is-loading"),updateGenerateEnabled()})}function updateGenerateEnabled(){var hasText=!!textarea.value.trim();generateBtn.disabled=!hasText,generateBtn.classList.toggle("is-empty",!hasText),wrap&&wrap.classList.toggle("has-text",hasText),clearBtn&&(clearBtn.hidden=!hasText)}function fakeGenerate(prompt,skeletonDelay){generateBtn.classList.add("is-loading"),generateBtn.disabled=!0,isV2&&clearThreadResults(),appendUserMessage(prompt),textarea.value="",syncCount(),autosizeTextarea();var startTime=Date.now(),MIN_LOAD_MS=skeletonDelay||1e3,PILL_CAP=3;appendAiTextMessage("Generating your Images");var ctx=appendAiMessage(),grid=ctx.grid;function renderInto(images){var elapsed=Date.now()-startTime,wait=Math.max(0,MIN_LOAD_MS-elapsed);setTimeout(function(){fillGrid(grid,images,prompt),appendAiTextMessage(generationDoneMsg()),generateBtn.classList.remove("is-loading"),updateGenerateEnabled(),scrollThreadToBottom()},wait)}var pinned=getPillImages(prompt);if(pinned){renderInto(pinned.slice(0,PILL_CAP));return}var AI_HOST="https://www.rushordertees.com/design";fetch(AI_HOST+"/studio/getGenerativeAiUploads.php?prompt="+encodeURIComponent(prompt),{credentials:"include"}).then(function(r){return r.ok?r.json():[]}).catch(function(){return[]}).then(function(data){var cutoffSec=(Date.now()-HISTORY_TTL_MS)/1e3,arr=(Array.isArray(data)?data:[]).filter(function(img){return!img.created_at||img.created_at>cutoffSec}).slice(0,PILL_CAP),images;if(arr.length)images=arr.map(function(img){return{url:img.url,thumbnailUrl:img.thumbnailUrl||img.url,fileName:img.fileName||""}});else{var seed=(prompt||"demo").toLowerCase().replace(/\W+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"demo";images=[1,2,3].map(function(n){var url="https://picsum.photos/seed/"+seed+"-"+n+"/512/512";return{url:url,thumbnailUrl:url,fileName:seed+"-"+n+".jpg"}})}renderInto(images)})}updateGenerateEnabled(),autosizeTextarea(),requestAnimationFrame(autosizeTextarea),renderHistory(),isV2?setHistoryCollapsed(!0):loadHistory(instanceKey).length>0&&setHistoryCollapsed(!1),document.addEventListener("ninjaAiHistory:changed",renderHistory),pillsRow&&pillsRow.querySelectorAll("[data-ai-pill-prompt]").forEach(function(pill){pill.addEventListener("click",function(){var prompt=pill.getAttribute("data-ai-pill-prompt")||"";fakeGenerate(prompt,2500)})}),historyClear&&historyClear.addEventListener("click",function(){saveHistory(instanceKey,[]),renderHistory()});function setHistoryCollapsed(collapsed){history&&history.classList.toggle("is-collapsed",collapsed),panel.classList.toggle("is-history-open",!collapsed),collapsed||(updateArrowVisibility(),requestAnimationFrame(function(){requestAnimationFrame(updateArrowVisibility)})),historyToggle&&(historyToggle.setAttribute("aria-expanded",collapsed?"false":"true"),historyToggle.setAttribute("aria-label",collapsed?"Show recently generated":"Hide recently generated"),historyToggleLabel&&(historyToggleLabel.textContent=collapsed?isV2?"Show Recently Generated":"Show":"Hide"))}historyToggle&&historyToggle.addEventListener("click",function(){setHistoryCollapsed(!history.classList.contains("is-collapsed"))});var historyHead=container.querySelector(".ai-chat-history-head");historyHead&&history&&(historyHead.style.cursor="pointer",historyHead.addEventListener("click",function(e){e.target.closest("[data-ai-history-toggle]")||setHistoryCollapsed(!history.classList.contains("is-collapsed"))})),wrap&&wrap.addEventListener("click",function(e){e.target.closest(".ai-chat-send")||textarea.focus()}),generateBtn.addEventListener("click",function(e){e.preventDefault(),generate()}),armTouchTap(generateBtn,generate),clearBtn&&clearBtn.addEventListener("click",function(){textarea.value="",syncCount(),autosizeTextarea(),updateGenerateEnabled(),textarea.focus()}),textarea.addEventListener("input",function(){autosizeTextarea(),errorBox&&errorBox.textContent&&(errorBox.textContent=""),updateGenerateEnabled()}),textarea.addEventListener("keydown",function(e){e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),generate()),e.key==="Escape"&&isV2&&editSourceUrl&&(e.preventDefault(),exitEditMode())});var instance=panel.getAttribute("data-ai-instance");function focusPrompt(){setTimeout(function(){try{textarea.focus()}catch(_){}},60)}if(instance==="aipage")focusPrompt();else if(instance==="dtfut")document.addEventListener("dtfut:tab-change",function(e){e.detail&&e.detail.name==="ai"&&requestAnimationFrame(function(){syncNarrow(),autosizeTextarea(),focusPrompt()})});else{window.__dsAiCssHooked||(window.__dsAiCssHooked=!0,document.addEventListener("click",function(e){e.target.closest&&e.target.closest("#ai-panel-btn, #ai-panel-btn-2")&&window.__ensureAiCss&&!window.__aiCssLoaded&&window.__ensureAiCss()}));var _panelVisible=!1,_visObs=new IntersectionObserver(function(entries){entries.forEac
1h(function(entry){entry.isIntersecting&&!_panelVisible?(_panelVisible=!0,focusPrompt(),requestAnimationFrame(autosizeTextarea)):entry.isIntersecting||(_panelVisible=!1)})},{threshold:.1});_visObs.observe(panel)}}function bootAll(){document.querySelectorAll(".ai-chat[data-ai-instance]").forEach(attach)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",bootAll):bootAll(),document.addEventListener("shopify:section:load",bootAll),document.addEventListener("shopify:block:select",bootAll);try{var _panelObserver=new MutationObserver(function(records){for(var i=0;i<records.length;i++)for(var added=records[i].addedNodes,j=0;j<added.length;j++){var node=added[j];if(!(!node||node.nodeType!==1)){if(node.matches&&node.matches(".ai-chat[data-ai-instance]"))attach(node);else if(node.querySelectorAll)for(var panels=node.querySelectorAll(".ai-chat[data-ai-instance]"),k=0;k<panels.length;k++)attach(panels[k])}}});_panelObserver.observe(document.body,{childList:!0,subtree:!0})}catch(_){}})(); 2//# sourceMappingURL=/cdn/shop/t/1064/assets/ai-chat-sandbox.js.map?v=17743223880029571861789084303
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.