@uploadcare/ai-enhancer 0.1.1 → 0.1.3

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,444 @@
1
+ "use strict";var pt=Object.defineProperty;var $e=i=>{throw TypeError(i)};var ft=(i,e,t)=>e in i?pt(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var v=(i,e,t)=>ft(i,typeof e!="symbol"?e+"":e,t),oe=(i,e,t)=>e.has(i)||$e("Cannot "+t);var E=(i,e,t)=>(oe(i,e,"read from private field"),t?t.call(i):e.get(i)),ae=(i,e,t)=>e.has(i)?$e("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Ue=(i,e,t,r)=>(oe(i,e,"write to private field"),r?r.call(i,t):e.set(i,t),t),G=(i,e,t)=>(oe(i,e,"access private method"),t);const h=require("lit"),n=require("lit/decorators.js"),k=require("lit/directives/class-map.js"),H=require("./errors.cjs"),J=require("lit/directives/unsafe-svg.js"),Ze=require("lit/html.js"),Z=require("lit/directive.js"),Qe=require("lit/async-directive.js"),mt=require("lit/directives/repeat.js"),_t=require("lit/directives/if-defined.js"),z="original";function P(i){return i!=null&&i!==z}function ue(i,e){return i===z||e===z?i===e:kt(i,e)}const et=[[2,3],[3,2],[1,1],[9,16],[16,9]],gt=[3,2],vt={"1:1":"ai-enhancer-aspect-square","2:3":"ai-enhancer-aspect-tall","3:2":"ai-enhancer-aspect-wide","4:5":"ai-enhancer-aspect-portrait","5:4":"ai-enhancer-aspect-landscape","9:16":"ai-enhancer-aspect-vertical","16:9":"ai-enhancer-aspect-widescreen"},bt=.1,yt=10;function Q(i){const[e,t]=i;if(!Number.isFinite(e)||!Number.isFinite(t)||e<=0||t<=0)return!1;const r=e/t;return r>=bt&&r<=yt}function V(i){return`${i[0]}:${i[1]}`}function wt(i){return vt[V(i)]??null}function xt(i){return{value:i,labelKey:wt(i)}}function Et(i){const e=[];for(const t of i.split(/[\s,]+/)){const r=t.trim();if(!r)continue;const s=r.indexOf(":");if(s===-1)continue;const o=Number(r.slice(0,s)),a=Number(r.slice(s+1)),l=[o,a];Q(l)&&e.push(l)}return e}function kt(i,e){return i[0]===e[0]&&i[1]===e[1]}function Rt(i){const[e,t]=i,r=12,s=e>=t?r:r*(e/t),o=t>=e?r:r*(t/e),a=(16-s)/2,l=(16-o)/2;return`<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect x="${a.toFixed(2)}" y="${l.toFixed(2)}" width="${s.toFixed(2)}" height="${o.toFixed(2)}" rx="1.5" stroke="currentColor" stroke-width="1.4"/></svg>`}class ee extends Error{constructor(e,t,r){super(t),this.name="AiProviderError",this.errorCode=e,this.errorSource=r}}function St(i){const e=i==null?void 0:i.error;return!!e&&typeof e=="object"&&typeof e.error_code=="string"}async function W(i,e){}async function Te(i,e){const t=await i.text().catch(()=>"");let r=null;if(t)try{r=JSON.parse(t)}catch{}if(St(r)){const{error_code:s,content:o}=r.error;throw new ee(s,o??s)}if(!i.ok)throw new Error(`Uploadcare ${e} failed (${i.status} ${i.statusText})${t?`: ${t}`:""}`);return r}class At{constructor(e){if(!e.publicKey)throw new Error("UploadcareApiClient: publicKey is required");this.publicKey=e.publicKey,this.baseUrl=e.baseUrl??"https://upload.uploadcare.com",this.doFetch=e.fetch??globalThis.fetch.bind(globalThis)}async generate(e){const t={pub_key:this.publicKey,prompt:e.prompt,aspect_ratio:[e.aspectRatio[0],e.aspectRatio[1]],filename:e.filename};return e.store!==void 0&&(t.store=e.store),e.metadata&&(t.metadata=e.metadata),await W(),this.startJob(new URL("/derivative/image/generate/",this.baseUrl),t,"generate",e.signal)}async edit(e){const t={pub_key:this.publicKey,prompt:e.prompt,source:e.source,filename:e.filename};return e.aspectRatio&&(t.aspect_ratio=[e.aspectRatio[0],e.aspectRatio[1]]),e.store!==void 0&&(t.store=e.store),e.metadata&&(t.metadata=e.metadata),await W(),this.startJob(new URL("/derivative/image/edit/",this.baseUrl),t,"edit",e.signal)}async getJobStatus(e,t){const r=new URL("/derivative/status/",this.baseUrl);r.searchParams.set("pub_key",this.publicKey),r.searchParams.set("job_id",e);const s=await this.doFetch(r.href,{method:"GET",headers:{Accept:"application/json"},signal:t}),o=await Te(s,"generate status");return await W(),o}async startJob(e,t,r,s){const o=await this.doFetch(e.href,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t),signal:s}),a=await Te(o,r);return await W(),a}}const tt="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Ct=new RegExp(`^${tt}$`,"i"),$t=new RegExp(`^(${tt})~([0-9]+)$`,"i");function ve(i){return i.replace(/\/+$/,"")}function de(i,e="size"){return typeof i=="number"?String(i):i.replace("%","p")}function it(i,e,t="dimensions"){const r=i==null?"":de(i,`${t} width`),s=e==null?"":de(e,`${t} height`);return`${r}x${s}`}function Pe(i,e){return typeof i=="number"?String(i):de(i,e)}function Ut(i,e="alignment"){return typeof i=="string"?i:`${Pe(i.x,`${e} x`)},${Pe(i.y,`${e} y`)}`}const Tt=["video","document","gif2video"],Pt=/\/(https?:\/\/.+)$/i;function Mt(i){return i!=null&&Tt.includes(i)}function rt(i){var f;let e;try{e=new URL(i)}catch{throw new TypeError(`Invalid URL: "${i}"`)}const t=`${e.protocol}//${e.host}`,r=e.pathname,s=(f=r.match(Pt))==null?void 0:f[1];if(s!==void 0){const g=r.slice(0,r.length-s.length);return{kind:"proxy",origin:t,operations:ne(Me(g),"proxy prefix"),sourceUrl:s+e.search+e.hash}}const o=r.endsWith("/"),a=Me(r),l=a.shift();if(l===void 0)throw new TypeError(`Not a CDN URL (empty path): "${i}"`);const c={origin:t,search:e.search,hash:e.hash},u=l.match($t);if((u==null?void 0:u[1])!==void 0){const g={uuid:u[1],count:Number(u[2])};if(a[0]==="nth"){const w=Number(a[1]);if(!Number.isInteger(w))throw new TypeError(`Invalid group element index in "${i}"`);a.splice(0,2);const x=Fe(a,o);return{kind:"group-element",...c,group:g,nth:w,operations:ne(a,i),filename:x}}if(a.length>0)throw new TypeError(`Unexpected path after group id in "${i}"`);return{kind:"group",...c,group:g}}if(!Ct.test(l))throw new TypeError(`Not a CDN URL (no uuid, group or proxy source): "${i}"`);let d=null;Mt(a[0])&&(d=a[0],a.shift());const p=Fe(a,o);return{kind:"file",...c,uuid:l,conversion:d,operations:ne(a,i),filename:p}}function Me(i){return i.split("/").filter(e=>e!=="")}function Fe(i,e){return e||i.length===0?null:i.pop()??null}function ne(i,e){const t=[];let r=0;for(;r<i.length;){if(i[r]!=="-")throw new TypeError(`Unexpected path segment "${i[r]}" in "${e}"`);r+=1;const s=i[r];if(s==null||s==="-")throw new TypeError(`Missing operation name in "${e}"`);r+=1;const o=[];for(;r<i.length;){const a=i[r];if(a===void 0||a==="-")break;o.push(a),r+=1}t.push({name:s,params:o})}return t}function st(i){return i.map(e=>`-/${[e.name,...e.params].join("/")}/`).join("")}function ot(i){const e=ve(i.origin),t=st(i.operations??[]);if("sourceUrl"in i&&i.sourceUrl!=null)return`${e}/${t}${i.sourceUrl}`;const r=("search"in i?i.search:"")??"",s=("hash"in i?i.hash:"")??"";if("group"in i&&i.group!=null){let o=`${e}/${i.group.uuid}~${i.group.count}/`;return i.nth!=null&&(o+=`nth/${i.nth}/${t}${i.filename??""}`),o+r+s}if("uuid"in i&&i.uuid!=null){const o=i.conversion!=null?`${i.conversion}/`:"";return`${e}/${i.uuid}/${o}${t}${i.filename??""}${r}${s}`}throw new TypeError("serializeCdnUrl requires one of: uuid, group, sourceUrl")}function Ft(i){return typeof i=="string"?i:"opName"in i?i.opName:i.name}function le(i,e){const t=Ft(e);return i.name===t||i.name.startsWith(`${t}~`)}function at(i,e){return Object.assign(e,{opName:i})}const Ot=(i,e)=>{const t=new URL(e);return t.hostname=`${i}.${t.hostname}`,t.toString().replace(/\/$/,"")},It="0123456789abcdefghijklmnopqrstuvwxyz",Lt=i=>{if(i<=0n)return"0";let e="";for(;i>0n;){const t=i%36n;e=It[Number(t)]+e,i=i/36n}return e},zt=(i,e)=>{try{const t=new URL(i),r=new URL(e);return t.hostname.endsWith(r.hostname)}catch{return!1}},Dt=async i=>{const e=new TextEncoder().encode(i),t=await window.crypto.subtle.digest("SHA-256",e),r=Array.from(new Uint8Array(t)).map(s=>s.toString(16).padStart(2,"0")).join("");return BigInt(`0x${r}`)},Nt=10,Bt=async i=>{const e=await Dt(i);return Lt(e).slice(0,Nt)},qt=async(i,e)=>{const t=await Bt(i);return Ot(t,e)};function Oe(i){return Object.prototype.toString.call(i)==="[object Object]"}const jt=/\W|_/g;function Gt(i){return i.split(jt).map((e,t)=>e.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+e.slice(1)).join("")}function Ie(i,{ignoreKeys:e}={ignoreKeys:[]}){return Array.isArray(i)?i.map(t=>be(t,{ignoreKeys:e})):i}function be(i,{ignoreKeys:e}={ignoreKeys:[]}){if(Array.isArray(i))return Ie(i,{ignoreKeys:e});if(!Oe(i))return i;const t={};for(const r of Object.keys(i)){let s=i[r];if(e.includes(r)){t[r]=s;continue}Oe(s)?s=be(s,{ignoreKeys:e}):Array.isArray(s)&&(s=Ie(s,{ignoreKeys:e})),t[Gt(r)]=s}return t}const Ht=i=>new Promise(e=>setTimeout(e,i));function Wt({libraryName:i,libraryVersion:e,userAgent:t,publicKey:r="",integration:s=""}){const o="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:r,libraryName:i,libraryVersion:e,languageName:o,integration:s});const a=[i,e,r].filter(Boolean).join("/"),l=[o,s].filter(Boolean).join("; ");return`${a} (${l})`}const Vt={factor:2,time:100};function Kt(i,e=Vt){let t=0;function r(s){const o=Math.round(e.time*e.factor**t);return s({attempt:t,retry:l=>Ht(l??o).then(()=>(t+=1,r(s)))})}return r(i)}class ye extends Error{}class te extends ye{constructor(t){super();v(this,"originalProgressEvent");this.name="NetworkError",this.message="Network error",Object.setPrototypeOf(this,te.prototype),this.originalProgressEvent=t}}const Yt=(i,e)=>{i&&(i.aborted?Promise.resolve().then(e):i.addEventListener("abort",()=>e(),{once:!0}))};class we extends ye{constructor(t="Request canceled"){super(t);v(this,"isCancel",!0);this.name="CancelError",Object.setPrototypeOf(this,we.prototype)}}const K={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3},Xt=({method:i,url:e,data:t,headers:r={},signal:s,onProgress:o})=>new Promise((a,l)=>{const c=new XMLHttpRequest,u=(i==null?void 0:i.toUpperCase())||"GET";let d=!1;c.open(u,e,!0),r&&Object.entries(r).forEach(p=>{const[f,g]=p;typeof g<"u"&&!Array.isArray(g)&&c.setRequestHeader(f,g)}),c.responseType="text",Yt(s,()=>{d=!0,c.abort(),l(new we)}),c.onload=()=>{if(c.status!=200)l(new Error(`Error ${c.status}: ${c.statusText}`));else{const p={method:u,url:e,data:t,headers:r||void 0,signal:s,onProgress:o},f=c.getAllResponseHeaders().trim().split(/[\r\n]+/),g={};f.forEach(function($){const R=$.split(": "),q=R.shift(),j=R.join(": ");q&&typeof q<"u"&&(g[q]=j)});const w=c.response,x=c.status;a({request:p,data:w,headers:g,status:x})}},c.onerror=p=>{d||l(new te(p))},o&&typeof o=="function"&&(c.upload.onprogress=p=>{p.lengthComputable?o({isComputable:!0,value:p.loaded/p.total}):o({isComputable:!1})}),t?c.send(t):c.send()});class xe extends ye{constructor(t,r,s,o,a){super();v(this,"code");v(this,"request");v(this,"response");v(this,"headers");this.name="UploadError",this.message=t,this.code=r,this.request=s,this.response=o,this.headers=a,Object.setPrototypeOf(this,xe.prototype)}}const Jt=i=>{const e=new URLSearchParams;for(const[t,r]of Object.entries(i))r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).filter(s=>s[1]??!1).forEach(s=>e.set(`${t}[${s[0]}]`,String(s[1]))):Array.isArray(r)?r.forEach(s=>{e.append(`${t}[]`,s)}):typeof r=="string"&&r?e.set(t,r):typeof r=="number"&&e.set(t,r.toString());return e.toString()},pe=(i,e,t)=>{const r=new URL(i);return r.pathname=(r.pathname+e).replace("//","/"),t&&(r.search=Jt(t)),r.toString()};var Zt="6.18.4";const Qt="UploadcareUploadClient",ei=Zt;function ti(i){return Wt({libraryName:Qt,libraryVersion:ei,...i})}const ii="RequestThrottledError",Le=15e3,ri=1e3;function si(i){const{headers:e}=i||{};if(!e||typeof e["retry-after"]!="string")return Le;const t=parseInt(e["retry-after"],10);return Number.isFinite(t)?t*1e3:Le}function oi(i,e){const{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:r}=e;return Kt(({attempt:s,retry:o})=>i().catch(a=>{if("response"in a&&(a==null?void 0:a.code)===ii&&s<t)return o(si(a));if(a instanceof te&&s<r)return o((s+1)*ri);throw a}))}var ze;(function(i){i.Token="token",i.FileInfo="file_info"})(ze||(ze={}));var De;(function(i){i.Unknown="unknown",i.Waiting="waiting",i.Progress="progress",i.Error="error",i.Success="success"})(De||(De={}));function ai(i,{publicKey:e,baseURL:t=K.baseURL,signal:r,source:s,integration:o,userAgent:a,retryThrottledRequestMaxTimes:l=K.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=K.retryNetworkErrorMaxTimes}){return oi(()=>Xt({method:"GET",headers:{"X-UC-User-Agent":ti({publicKey:e,integration:o,userAgent:a})},url:pe(t,"/info/",{jsonerrors:1,pub_key:e,file_id:i,source:s}),signal:r}).then(({data:u,headers:d,request:p})=>{const f=be(JSON.parse(u));if("error"in f)throw new xe(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:c})}function ni(i){return"defaultEffects"in i}class Ne{constructor(e,{baseCDN:t=K.baseCDN,fileName:r}={}){v(this,"uuid");v(this,"name");v(this,"size");v(this,"isStored");v(this,"isImage");v(this,"mimeType");v(this,"cdnUrl");v(this,"s3Url");v(this,"originalFilename");v(this,"imageInfo");v(this,"videoInfo");v(this,"contentInfo");v(this,"metadata");v(this,"s3Bucket");v(this,"defaultEffects",null);const{uuid:s,s3Bucket:o}=e,a=pe(t,`${s}/`),l=o?pe(`https://${o}.s3.amazonaws.com/`,`${s}/${e.filename}`):null;this.uuid=s,this.name=r||e.filename,this.size=e.size,this.isStored=e.isStored,this.isImage=e.isImage,this.mimeType=e.mimeType,this.cdnUrl=a,this.originalFilename=e.originalFilename,this.imageInfo=e.imageInfo,this.videoInfo=e.videoInfo,this.contentInfo=e.contentInfo,this.metadata=e.metadata||null,this.s3Bucket=o||null,this.s3Url=l,ni(e)&&(this.defaultEffects=e.defaultEffects)}}const li=/\W|_/g;function ci(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function hi(i){return i.split(li).map((e,t)=>e&&e.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+e.slice(1)).join("")}function fe(i){if(Array.isArray(i))return i.map(t=>fe(t));if(!ci(i))return i;const e={};for(const t of Object.keys(i))e[hi(t)]=fe(i[t]);return e}const ui=[1,1],Be="https://ucarecdn.com",di=1500,pi=1e6;function fi(i,e){return new Promise((t,r)=>{if(e!=null&&e.aborted){r(new DOMException("Aborted","AbortError"));return}const s=setTimeout(()=>{e==null||e.removeEventListener("abort",o),t()},i),o=()=>{clearTimeout(s),r(new DOMException("Aborted","AbortError"))};e==null||e.addEventListener("abort",o,{once:!0})})}function qe(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}class mi{constructor(e){if(this.id="uploadcare-derivative",!e.publicKey)throw new Error("UploadcareDerivativeApi: publicKey is required");this.api=new At({publicKey:e.publicKey,baseUrl:e.baseUrl,fetch:e.fetch}),this.publicKey=e.publicKey,this.baseUrl=e.baseUrl,this.filename=e.filename??"generated.png",this.store=e.store,this.cname=e.cdnBaseUrl??Be,this.cnamePrefixed=e.cdnCnamePrefixed??"https://ucarecd.net",this.pollIntervalMs=e.pollIntervalMs??di,this.pollTimeoutMs=e.pollTimeoutMs??pi}async generate(e){const t=await this.startJob(e);return this.pollUntilDone(t,e)}async resolveCdnUrl(e){return ot({origin:await this.getCdnBase(),uuid:e})}async getFileInfo(e,t){const r=await ai(e,{publicKey:this.publicKey,baseURL:this.baseUrl,signal:t});return new Ne(r,{baseCDN:await this.getCdnBase()})}async startJob(e){const t=e.aspectRatio&&Q(e.aspectRatio)?[e.aspectRatio[0],e.aspectRatio[1]]:void 0,r=e.filename??this.filename,s=e.mode==="edit"?await this.startEditJob(e,t,r,e.metadata):await this.api.generate({prompt:e.prompt,aspectRatio:t??ui,filename:r,store:this.store,signal:e.signal,metadata:e.metadata});if(!s.job_id)throw new Error("Uploadcare derivative: response did not include a job_id");return s.job_id}startEditJob(e,t,r,s){if(!e.source)throw new Error("Uploadcare edit: a source image uuid is required");return this.api.edit({prompt:e.prompt,source:e.source,aspectRatio:t,filename:r,store:this.store,signal:e.signal,metadata:s})}async pollUntilDone(e,t){const r=this.pollTimeoutMs+qe();for(;;){const s=await this.api.getJobStatus(e,t.signal);if(s.status==="success"){if(!s.uuid)throw new Error("Uploadcare derivative: response did not include a uuid");const o=fe(s),a=new Ne(o,{baseCDN:await this.getCdnBase()});return{url:a.cdnUrl,uuid:a.uuid,prompt:t.prompt,mode:t.mode,file:a}}if(s.status==="error"){const o=s.error_code??"unknown",a=s.error??o;throw new ee(o,a,s.error_source)}if(qe()>=r)throw new Error(`Uploadcare derivative: timed out waiting for job ${e}`);await fi(this.pollIntervalMs,t.signal)}}getCdnBase(){return this.cdnBasePromise||(this.cdnBasePromise=this.cname===Be||zt(this.cname,this.cnamePrefixed)?qt(this.publicKey,this.cnamePrefixed):Promise.resolve(this.cname)),this.cdnBasePromise}}function _i(i){return i instanceof H.AiEnhancerError?i:i instanceof ee?new H.AiEnhancerError(i.message,{code:i.errorCode,source:i.errorSource,cause:i}):i instanceof Error?new H.AiEnhancerError(i.message,{cause:i}):new H.AiEnhancerError(typeof i=="string"&&i?i:"Generation failed",{cause:i})}const me={generate:{id:"generate",placeholderKey:"ai-enhancer-generate-placeholder",presets:[{label:"Portrait",prompt:"A photorealistic close-up portrait of a woman with freckles and windswept hair, soft natural window light, shallow depth of field, shot on an 85mm lens, ultra-detailed skin texture"},{label:"Cinematic",prompt:"Cinematic film still of a lone traveler on a neon-lit Tokyo street at night, rain-slicked pavement, glowing reflections, moody atmosphere, anamorphic, shot on 35mm"},{label:"Product",prompt:"Product photography of a frosted glass perfume bottle on a polished marble surface, soft studio lighting, gentle reflections, minimalist composition, high detail"},{label:"Landscape",prompt:"A serene mountain landscape at golden hour, low mist drifting through the valley, dramatic clouds, mirror-still lake reflections, photorealistic, ultra-detailed"},{label:"Illustration",prompt:"A flat vector illustration of a cozy bookshop café, warm color palette, clean bold shapes, soft shadows, modern editorial style"},{label:"3D character",prompt:"A cute 3D-rendered robot character, Pixar style, big expressive eyes, soft studio lighting, pastel color palette, smooth glossy materials, octane render"}]},edit:{id:"edit",placeholderKey:"ai-enhancer-edit-placeholder",presets:[{label:"Enhance",prompt:"Enhance the photo: improve the lighting, sharpen details, and make the colors richer while keeping it natural"},{label:"Golden hour",prompt:"Relight the scene with warm golden-hour sunlight and long, soft shadows"},{label:"White studio",prompt:"Place the subject on a clean seamless white studio backdrop with soft, even lighting"},{label:"Remove people",prompt:"Remove all other people from the scene, keeping the main subject intact"},{label:"Watercolor",prompt:"Restyle the image as a soft watercolor painting with delicate, visible brush strokes"},{label:"Black & white",prompt:"Convert to dramatic high-contrast black and white film photography with subtle grain"}]}},je=20;class gi{constructor(e){this.busy=!1,this.resultUrl=null,this.result=null,this.error=null,this.errorCode=null,this.history=[],this._abortController=null,this._host=e,e.addController(this)}hostDisconnected(){this.abort()}abort(){var e;(e=this._abortController)==null||e.abort()}reset(){this.abort(),this.resultUrl=null,this.result=null,this.error=null,this.errorCode=null,this._host.requestUpdate()}clearHistory(){this.history=[],this._host.requestUpdate()}setHistory(e){this.history=e.slice(0,je),this._host.requestUpdate()}setResult(e){this.resultUrl=e.url,this.result=e,this.error=null,this.errorCode=null,this._host.requestUpdate()}async run(e){var r;if(this.busy)return null;(r=this._abortController)==null||r.abort();const t=new AbortController;this._abortController=t,this.busy=!0,this.error=null,this.errorCode=null,this._host.requestUpdate();try{const s=await e.provider.generate({prompt:e.prompt,mode:e.mode,aspectRatio:e.aspectRatio,source:e.source,filename:e.filename,metadata:e.metadata,signal:t.signal});return t.signal.aborted?null:(this.resultUrl=s.url,this.result=s,this.history=[{id:crypto.randomUUID(),prompt:s.prompt,mode:s.mode,url:s.url,file:s.file,ratio:e.ratioValue??null},...this.history].slice(0,je),s)}catch(s){if((s==null?void 0:s.name)==="AbortError")return null;throw this.error=s.message||"Generation failed",this.errorCode=s instanceof ee?s.errorCode:null,s}finally{this._abortController===t&&(this.busy=!1,this._abortController=null),this._host.requestUpdate()}}}const vi={"ai-enhancer-source-label":"Generate image","ai-enhancer-file-action-label":"AI Edit","ai-enhancer-generate-title":"Generate image","ai-enhancer-edit-title":"Edit image","ai-enhancer-generate-placeholder":"Create image...","ai-enhancer-edit-placeholder":"Edit image...","ai-enhancer-cancel":"Cancel","ai-enhancer-generate-btn":"Generate","ai-enhancer-done-btn":"Done","ai-enhancer-start-over":"Start over","ai-enhancer-history-title":"Recent prompts","ai-enhancer-busy":"Generating…","ai-enhancer-error":"Something went wrong. Try again.","ai-enhancer-fullscreen":"View fullscreen","ai-enhancer-exit-fullscreen":"Exit fullscreen","ai-enhancer-aspect-ratio-aria":"Pick aspect ratio","ai-enhancer-aspect-original":"Original","ai-enhancer-aspect-square":"Square","ai-enhancer-aspect-tall":"Tall","ai-enhancer-aspect-wide":"Wide","ai-enhancer-aspect-portrait":"Portrait","ai-enhancer-aspect-landscape":"Landscape","ai-enhancer-aspect-vertical":"Vertical","ai-enhancer-aspect-widescreen":"Widescreen"},bi={"ai-enhancer-error-invalid_request":"Something went wrong with the request. Please try again.","ai-enhancer-error-invalid_source":"The source image couldn't be read. Please try a different image.","ai-enhancer-error-source_not_found":"The source image couldn't be found.","ai-enhancer-error-source_not_image":"The source file must be an image.","ai-enhancer-error-source_url_unavailable":"The source image couldn't be downloaded. Please try again.","ai-enhancer-error-invalid_aspect_ratio":"That aspect ratio isn't supported.","ai-enhancer-error-canvas_too_large":"The image is too large (max 4 megapixels). Try a smaller size.","ai-enhancer-error-canvas_dimension_too_small":"The image is too small — each side must be at least 256px.","ai-enhancer-error-source_extends_beyond_canvas":"The source image doesn't fit the canvas. Try a larger canvas.","ai-enhancer-error-derivative_disabled":"AI image generation isn't enabled for this account.","ai-enhancer-error-job_id_required":"Something went wrong. Please try again.","ai-enhancer-error-job_not_found":"This generation has expired. Please try again.","ai-enhancer-error-content_moderated":"This request was blocked by content moderation. Try a different prompt.","ai-enhancer-error-provider_unavailable":"The image service is busy right now. Please try again in a moment.","ai-enhancer-error-generation_timeout":"Generation took too long and timed out. Please try again.","ai-enhancer-error-invalid_input":"Some settings are invalid. Please adjust them and try again.","ai-enhancer-error-RequestThrottledError":"Too many requests right now. Please wait a moment and try again.","ai-enhancer-error-DownloadFileHTTPClientError":"Couldn't retrieve the generated image. Please try again.","ai-enhancer-error-DownloadFileNotFoundError":"The generated image couldn't be found. Please try again.","ai-enhancer-error-DownloadFileTaskFailedError":"Couldn't save the generated image. Please try again."},T={...vi,...bi},Y={en:async()=>T,ar:()=>Promise.resolve().then(()=>require("./ar-DYF6cE7-.cjs")).then(i=>i.default),az:()=>Promise.resolve().then(()=>require("./az-UnBZVrss.cjs")).then(i=>i.default),ca:()=>Promise.resolve().then(()=>require("./ca-CuwmB1Gw.cjs")).then(i=>i.default),cs:()=>Promise.resolve().then(()=>require("./cs-AwdVESvI.cjs")).then(i=>i.default),da:()=>Promise.resolve().then(()=>require("./da-BC58D6q4.cjs")).then(i=>i.default),de:()=>Promise.resolve().then(()=>require("./de-DEF79Sit.cjs")).then(i=>i.default),el:()=>Promise.resolve().then(()=>require("./el-DFmdf7I1.cjs")).then(i=>i.default),es:()=>Promise.resolve().then(()=>require("./es-BkhHze52.cjs")).then(i=>i.default),et:()=>Promise.resolve().then(()=>require("./et-BhG8YNek.cjs")).then(i=>i.default),fi:()=>Promise.resolve().then(()=>require("./fi-Cyypxkac.cjs")).then(i=>i.default),fr:()=>Promise.resolve().then(()=>require("./fr-nhxYdowR.cjs")).then(i=>i.default),he:()=>Promise.resolve().then(()=>require("./he-0YWGAesl.cjs")).then(i=>i.default),hy:()=>Promise.resolve().then(()=>require("./hy-CY51XCFd.cjs")).then(i=>i.default),is:()=>Promise.resolve().then(()=>require("./is-Nssowr9F.cjs")).then(i=>i.default),it:()=>Promise.resolve().then(()=>require("./it-DK-Xszlz.cjs")).then(i=>i.default),ja:()=>Promise.resolve().then(()=>require("./ja-BZtfRu9w.cjs")).then(i=>i.default),ka:()=>Promise.resolve().then(()=>require("./ka-DSCPqvM4.cjs")).then(i=>i.default),kk:()=>Promise.resolve().then(()=>require("./kk-DGN5Pk5W.cjs")).then(i=>i.default),ko:()=>Promise.resolve().then(()=>require("./ko-BnVYElzl.cjs")).then(i=>i.default),lv:()=>Promise.resolve().then(()=>require("./lv-DxBkV0GW.cjs")).then(i=>i.default),nb:()=>Promise.resolve().then(()=>require("./nb-ByZ1aeGs.cjs")).then(i=>i.default),nl:()=>Promise.resolve().then(()=>require("./nl-DaahHFo1.cjs")).then(i=>i.default),pl:()=>Promise.resolve().then(()=>require("./pl-BRDowgAP.cjs")).then(i=>i.default),pt:()=>Promise.resolve().then(()=>require("./pt-DTs3scou.cjs")).then(i=>i.default),ro:()=>Promise.resolve().then(()=>require("./ro-CtdLT2xS.cjs")).then(i=>i.default),ru:()=>Promise.resolve().then(()=>require("./ru-COjncrMy.cjs")).then(i=>i.default),sk:()=>Promise.resolve().then(()=>require("./sk-DZF9evla.cjs")).then(i=>i.default),sr:()=>Promise.resolve().then(()=>require("./sr-TVYoxU-s.cjs")).then(i=>i.default),sv:()=>Promise.resolve().then(()=>require("./sv-UPU_fRLB.cjs")).then(i=>i.default),tr:()=>Promise.resolve().then(()=>require("./tr-B4vyEPOt.cjs")).then(i=>i.default),uk:()=>Promise.resolve().then(()=>require("./uk-EP2kCiy9.cjs")).then(i=>i.default),vi:()=>Promise.resolve().then(()=>require("./vi-DI3QVinB.cjs")).then(i=>i.default),zh:()=>Promise.resolve().then(()=>require("./zh-BxANO4fS.cjs")).then(i=>i.default),"zh-TW":()=>Promise.resolve().then(()=>require("./zh-TW-BxiS-SSf.cjs")).then(i=>i.default)};function yi(i,e){return(e==null?void 0:e[i])??T[i]}function wi(i){if("kind"in i)return i;const e=ve(i.origin);if("sourceUrl"in i)return{kind:"proxy",origin:e,operations:i.operations??[],sourceUrl:i.sourceUrl};const t=i.search??"",r=i.hash??"";return"group"in i?i.nth!=null?{kind:"group-element",origin:e,group:i.group,nth:i.nth,operations:i.operations??[],filename:i.filename??null,search:t,hash:r}:{kind:"group",origin:e,group:i.group,search:t,hash:r}:{kind:"file",origin:e,uuid:i.uuid,conversion:i.conversion??null,operations:i.operations??[],filename:i.filename??null,search:t,hash:r}}var y,D,X,U;let xi=(U=class{constructor(e){ae(this,D);ae(this,y);Ue(this,y,wi(e))}static parse(e){return new U(rt(e))}get operations(){return"operations"in E(this,y)?[...E(this,y).operations]:[]}get href(){return ot(E(this,y))}toString(){return this.href}toJSON(){return"operations"in E(this,y)?{...E(this,y),operations:[...E(this,y).operations]}:{...E(this,y)}}with(...e){return G(this,D,X).call(this,t=>[...t,...e])}without(e){return G(this,D,X).call(this,t=>t.filter(r=>!le(r,e)))}replace(e){return G(this,D,X).call(this,t=>{const r=t.findIndex(o=>o.name===e.name);if(r===-1)return[...t,e];const s=[...t];return s[r]=e,s})}has(e){return this.operations.some(t=>le(t,e))}get(e){return this.operations.find(t=>le(t,e))??null}setFilename(e){return E(this,y).kind==="group"||E(this,y).kind==="proxy"?this:new U({...E(this,y),filename:e})}setOrigin(e){return new U({...E(this,y),origin:ve(e)})}},y=new WeakMap,D=new WeakSet,X=function(e){return"operations"in E(this,y)?new U({...E(this,y),operations:e(E(this,y).operations)}):this},U);const _e=(i,...e)=>({name:i,params:e}),Ei=at("preview",function(i,e){return i==null&&e==null?_e("preview"):_e("preview",it(i,e,"preview"))}),ki=at("scale_crop",function(i,e,t={}){const r=[it(i,e,"scale_crop")];return t.type!=null&&r.push(t.type),t.align!=null&&r.push(Ut(t.align,"scale_crop alignment")),_e("scale_crop",...r)}),Ri=3e3;function nt(i){const e=typeof window<"u"?window.devicePixelRatio:1;return Math.min(Math.ceil(i*Math.max(e,1)),Ri)}function lt(i,e){if(e.length===0)return i;try{return xi.parse(i).with(...e).href}catch{return i}}function Si(i,e){const t=nt(e);return lt(i,[Ei(t,t)])}function Ai(i,e){const t=nt(e);return lt(i,[ki(t,t,{align:"center"})])}const Ci="uc-ai-enhancer/history",Ge=200,$i=10080*60*1e3;class Ui{constructor(e){this._key=null,e.addController(this)}hostDisconnected(){}setNamespace(e){this._key=e?`${Ci}/${e}`:null}record(e){const t=this._key;if(!t)return;const r=this._read(t);r[e.uuid]={...e,createdAt:Date.now()},this._write(t,this._evict(r))}recordSource(e){const t=this._key;if(!t)return;const r=this._read(t);if(r[e.uuid])return;const s=Object.values(r).reduce((o,a)=>Math.min(o,a.createdAt),Date.now());r[e.uuid]={...e,source:null,createdAt:s-1},this._write(t,this._evict(r))}lineage(e){const t=this._key;return!t||!e?[]:this._component(this._read(t),e).sort((r,s)=>s.createdAt-r.createdAt).map(Ti)}_component(e,t){const r=new Map;for(const l of Object.values(e)){if(!l.source)continue;const c=r.get(l.source);c?c.push(l):r.set(l.source,[l])}const s=[],o=new Set,a=[t];for(;a.length>0;){const l=a.shift();if(l===void 0||o.has(l))continue;o.add(l);const c=e[l];c&&(s.push(c),c.source&&a.push(c.source));for(const u of r.get(l)??[])a.push(u.uuid)}return s}_evict(e){const t=Date.now();let r=Object.values(e).filter(o=>t-o.createdAt<$i);r.length>Ge&&(r=r.sort((o,a)=>a.createdAt-o.createdAt).slice(0,Ge));const s={};for(const o of r)s[o.uuid]=o;return s}_read(e){var t;try{const r=(t=globalThis.localStorage)==null?void 0:t.getItem(e);if(!r)return{};const s=JSON.parse(r);return s&&typeof s=="object"?s:{}}catch{return{}}}_write(e,t){var r;try{(r=globalThis.localStorage)==null||r.setItem(e,JSON.stringify(t))}catch{}}}function Ti(i){return{id:i.uuid,prompt:i.prompt,mode:i.mode,url:i.url,file:i.file,ratio:i.ratio}}function Pi(i){try{const e=rt(i);if(e.kind==="file")return{uuid:e.uuid,cdnUrlModifiers:st(e.operations),fileName:e.filename??""}}catch{}return{uuid:"",cdnUrlModifiers:"",fileName:""}}function Mi(i,e){return e?e(i,Pi(i)):i}class ct{constructor(e){this._cache=new Map,this._pending=new Set,this._host=e,e.addController(this)}hostDisconnected(){this._cache.clear(),this._pending.clear()}setResolver(e){this._resolver=e,this._cache.clear(),this._pending.clear(),this._host.requestUpdate()}resolve(e){if(!e||!this._resolver)return e;const t=this._cache.get(e);if(t!==void 0)return t;if(this._pending.has(e))return null;const r=Mi(e,this._resolver);return typeof r=="string"?(this._cache.set(e,r),r):(this._pending.add(e),r.then(s=>this._cache.set(e,s)).catch(()=>this._cache.set(e,e)).finally(()=>{this._pending.delete(e),this._host.requestUpdate()}),null)}}const Fi=`<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
2
+ <path d="M9.5 3 11 6.5 14.5 8 11 9.5 9.5 13 8 9.5 4.5 8 8 6.5 9.5 3Z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/>
3
+ <path d="M17.5 12 18.4 14.1 20.5 15 18.4 15.9 17.5 18 16.6 15.9 14.5 15 16.6 14.1 17.5 12Z" stroke="currentColor" stroke-width="1.25" stroke-linejoin="round"/>
4
+ <path d="M5.5 16 6.1 17.4 7.5 18 6.1 18.6 5.5 20 4.9 18.6 3.5 18 4.9 17.4 5.5 16Z" stroke="currentColor" stroke-width="1.25" stroke-linejoin="round"/>
5
+ </svg>`,Oi=`<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
6
+ <path d="m14.5 4.5 5 5L9 20H4v-5L14.5 4.5Z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/>
7
+ <path d="m13 6 5 5" stroke="currentColor" stroke-width="1.5"/>
8
+ <path d="M18.5 14.5 19 16l1.5.5L19 17l-.5 1.5L18 17l-1.5-.5L18 16l.5-1.5Z" stroke="currentColor" stroke-width="1.1" stroke-linejoin="round"/>
9
+ </svg>`,Ii=`<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
10
+ <path d="M3 6.74251L8 2L13 6.74251M7.99961 14V2.10636" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
11
+ </svg>`,Li=`<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
12
+ <rect x="2" y="3" width="12" height="10" rx="1.6" stroke="currentColor" stroke-width="1.4"/>
13
+ <circle cx="5.75" cy="6.25" r="1.05" stroke="currentColor" stroke-width="1.2"/>
14
+ <path d="M3 11.5l3-2.6 2.3 1.8L11 8l2 2.4" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
15
+ </svg>`,zi=`<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
16
+ <path d="M9 4H4v5M15 4h5v5M9 20H4v-5M15 20h5v-5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
17
+ </svg>`,Di=`<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
18
+ <path d="M4 9h5V4M20 9h-5V4M4 15h5v5M20 15h-5v5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
19
+ </svg>`,Ni=":host{display:inline-flex;position:relative}.trigger{anchor-name:--ai-aspect-anchor;display:inline-flex;align-items:center;gap:8px;height:var(--uc-ai-button-size);padding:0 10px;background:var(--uc-ai-secondary);border:0;border-radius:var(--uc-ai-radius-button);color:var(--uc-ai-foreground);cursor:pointer;font:inherit;transition:background var(--uc-ai-transition),transform .14s var(--uc-ai-ease-out, ease)}.trigger:hover,.trigger[aria-expanded=true]{background:var(--uc-ai-secondary-hover)}.trigger:active{transform:scale(.97)}.trigger:disabled{opacity:.4;cursor:not-allowed}.trigger svg{width:14px;height:14px;color:var(--uc-ai-foreground)}.trigger-label{font-variant-numeric:tabular-nums;font-size:12px;font-weight:500;letter-spacing:.02em;line-height:20px}.popover{margin:0 0 6px;padding:0;border:0;background:transparent;color:inherit;overflow:visible;width:max-content;min-width:180px;max-width:320px;position-anchor:--ai-aspect-anchor;inset:auto;bottom:anchor(top);right:anchor(right);transform-origin:bottom right;transition:opacity .15s var(--uc-ai-ease-out, ease),transform .15s var(--uc-ai-ease-out, ease),display .15s allow-discrete,overlay .15s allow-discrete}.popover:not(:popover-open){display:none;opacity:0;transform:scale(.96) translateY(4px)}@starting-style{.popover:popover-open{opacity:0;transform:scale(.96) translateY(4px)}}.popover-inner{background:var(--uc-ai-background);border:1px solid var(--uc-ai-border);border-radius:var(--uc-ai-radius-input, 12px);box-shadow:var(--uc-ai-dialog-shadow);padding:5px;display:flex;flex-direction:column;gap:2px}.option{display:flex;align-items:center;gap:10px;width:100%;padding:6px 10px;background:transparent;border:0;border-radius:max(0px,calc(var(--uc-ai-radius-input) - 5px));cursor:pointer;color:var(--uc-ai-foreground);font:inherit;font-size:13px;text-align:left;transition:background .12s ease}.option:hover{background:var(--uc-ai-secondary)}.option[aria-selected=true]{background:var(--uc-ai-secondary-hover)}.option svg{width:16px;height:16px;flex:0 0 16px;color:var(--uc-ai-foreground)}.option-ratio{flex:0 0 36px;font-variant-numeric:tabular-nums;font-weight:500;white-space:nowrap;color:var(--uc-ai-foreground)}.option-label{flex:1;min-width:0;color:var(--uc-ai-muted-foreground);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}@media(prefers-reduced-motion:reduce){.trigger,.popover{transition-property:opacity,background,display,overlay}.trigger:active{transform:none}.popover:not(:popover-open){transform:none}}";var Bi=Object.defineProperty,qi=Object.getOwnPropertyDescriptor,F=(i,e,t,r)=>{for(var s=r>1?void 0:r?qi(e,t):e,o=i.length-1,a;o>=0;o--)(a=i[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Bi(e,t,s),s};let S=class extends h.LitElement{constructor(){super(...arguments),this.options=[],this.selected=null,this.busy=!1,this.labelText=null,this.labelFor=i=>P(i.value)?V(i.value):"",this.open=!1,this._onToggle=i=>{i.newState==="closed"&&this.open&&(this.open=!1)}}_setOpen(i){this.open=i;const e=this._popover;if(!e)return;const t=e.matches(":popover-open");i&&!t?e.showPopover():!i&&t&&e.hidePopover()}_toggle(){this._setOpen(!this.open)}_select(i){this.dispatchEvent(new CustomEvent("uc:select",{detail:{value:i},bubbles:!0,composed:!0})),this._setOpen(!1)}_iconFor(i){return P(i)?Rt(i):Li}_triggerLabel(){const i=this.selected;if(!i)return"";if(P(i))return V(i);const e=this.options.find(t=>t.value===i);return e?this.labelFor(e):""}render(){const i=this._triggerLabel();return h.html`
20
+ <button
21
+ type="button"
22
+ class="trigger"
23
+ aria-haspopup="listbox"
24
+ aria-expanded="${this.open?"true":"false"}"
25
+ aria-label="${this.labelText??"Aspect ratio"}"
26
+ ?disabled=${this.busy}
27
+ @click=${this._toggle}
28
+ >
29
+ ${this.selected?J.unsafeSVG(this._iconFor(this.selected)):null}
30
+ ${i?h.html`<span class="trigger-label">${i}</span>`:null}
31
+ </button>
32
+ <div class="popover" popover="auto" role="listbox" @toggle=${this._onToggle}>
33
+ <div class="popover-inner">
34
+ ${this.options.map(e=>{const t=this.selected?ue(e.value,this.selected):!1;return h.html`
35
+ <button
36
+ type="button"
37
+ class="option"
38
+ role="option"
39
+ aria-selected="${t?"true":"false"}"
40
+ @click=${()=>this._select(e.value)}
41
+ >
42
+ ${J.unsafeSVG(this._iconFor(e.value))}
43
+ <span class="option-ratio">${P(e.value)?V(e.value):""}</span>
44
+ <span class="option-label">${this.labelFor(e)}</span>
45
+ </button>
46
+ `})}
47
+ </div>
48
+ </div>
49
+ `}};S.styles=h.unsafeCSS(Ni);F([n.property({attribute:!1})],S.prototype,"options",2);F([n.property({attribute:!1})],S.prototype,"selected",2);F([n.property({type:Boolean})],S.prototype,"busy",2);F([n.property({attribute:"aria-label-text"})],S.prototype,"labelText",2);F([n.property({attribute:!1})],S.prototype,"labelFor",2);F([n.state()],S.prototype,"open",2);F([n.query(".popover")],S.prototype,"_popover",2);S=F([n.customElement("uc-ai-aspect-ratio")],S);const ji=new WeakMap;let He=0;const ce=new Map,We=new WeakSet,Ve=()=>new Promise(i=>requestAnimationFrame(i)),Ke=(i,e)=>{const t=i-e;return t===0?void 0:t},Ye=(i,e)=>{const t=i/e;return t===1?void 0:t},he={left:(i,e)=>{const t=Ke(i,e);return{value:t,transform:t==null||isNaN(t)?void 0:`translateX(${t}px)`}},top:(i,e)=>{const t=Ke(i,e);return{value:t,transform:t==null||isNaN(t)?void 0:`translateY(${t}px)`}},width:(i,e)=>{let t;e===0&&(e=1,t={width:"1px"});const r=Ye(i,e);return{value:r,overrideFrom:t,transform:r==null||isNaN(r)?void 0:`scaleX(${r})`}},height:(i,e)=>{let t;e===0&&(e=1,t={height:"1px"});const r=Ye(i,e);return{value:r,overrideFrom:t,transform:r==null||isNaN(r)?void 0:`scaleY(${r})`}}},Gi={duration:333,easing:"ease-in-out"},Hi=["left","top","width","height","opacity","color","background"],Xe=new WeakMap;class Wi extends Qe.AsyncDirective{constructor(e){if(super(e),this.t=!1,this.i=null,this.o=null,this.h=!0,this.shouldLog=!1,e.type===Z.PartType.CHILD)throw Error("The `animate` directive must be used in attribute position.");this.createFinished()}createFinished(){var e;(e=this.resolveFinished)==null||e.call(this),this.finished=new Promise(t=>{this.l=t})}async resolveFinished(){var e;(e=this.l)==null||e.call(this),this.l=void 0}render(e){return Ze.nothing}getController(){return ji.get(this.u)}isDisabled(){var e;return this.options.disabled||((e=this.getController())==null?void 0:e.disabled)}update(e,[t]){var s;const r=this.u===void 0;return r&&(this.u=(s=e.options)==null?void 0:s.host,this.u.addController(this),this.u.updateComplete.then(o=>this.t=!0),this.element=e.element,Xe.set(this.element,this)),this.optionsOrCallback=t,(r||typeof t!="function")&&this.m(t),this.render(t)}m(e){e=e??{};const t=this.getController();t!==void 0&&((e={...t.defaultOptions,...e}).keyframeOptions={...t.defaultOptions.keyframeOptions,...e.keyframeOptions}),e.properties??(e.properties=Hi),this.options=e}p(){const e={},t=this.element.getBoundingClientRect(),r=getComputedStyle(this.element);return this.options.properties.forEach(s=>{const o=t[s]??(he[s]?void 0:r[s]),a=Number(o);e[s]=isNaN(a)?o+"":a}),e}v(){let e,t=!0;return this.options.guard&&(e=this.options.guard(),t=((r,s)=>{if(Array.isArray(r)){if(Array.isArray(s)&&s.length===r.length&&r.every((o,a)=>o===s[a]))return!1}else if(s===r)return!1;return!0})(e,this._)),this.h=this.t&&!this.isDisabled()&&!this.isAnimating()&&t&&this.element.isConnected,this.h&&(this._=Array.isArray(e)?Array.from(e):e),this.h}hostUpdate(){typeof this.optionsOrCallback=="function"&&this.m(this.optionsOrCallback()),this.v()&&(this.A=this.p(),this.i=this.i??this.element.parentNode,this.o=this.element.nextSibling)}async hostUpdated(){if(!this.h||!this.element.isConnected||this.options.skipInitial&&!this.isHostRendered)return;let e;this.prepare(),await Ve;const t=this.P(),r=this.V(this.options.keyframeOptions,t),s=this.p();if(this.A!==void 0){const{from:o,to:a}=this.O(this.A,s,t);this.log("measured",[this.A,s,o,a]),e=this.calculateKeyframes(o,a)}else{const o=ce.get(this.options.inId);if(o){ce.delete(this.options.inId);const{from:a,to:l}=this.O(o,s,t);e=this.calculateKeyframes(a,l),e=this.options.in?[{...this.options.in[0],...e[0]},...this.options.in.slice(1),e[1]]:e,He++,e.forEach(c=>c.zIndex=He)}else this.options.in&&(e=[...this.options.in,{}])}this.animate(e,r)}resetStyles(){this.j!==void 0&&(this.element.setAttribute("style",this.j??""),this.j=void 0)}commitStyles(){var e,t;this.j=this.element.getAttribute("style"),(e=this.webAnimation)==null||e.commitStyles(),(t=this.webAnimation)==null||t.cancel()}reconnected(){}async disconnected(){var t;if(!this.h||(this.options.id!==void 0&&ce.set(this.options.id,this.A),this.options.out===void 0))return;if(this.prepare(),await Ve(),(t=this.i)==null?void 0:t.isConnected){const r=this.o&&this.o.parentNode===this.i?this.o:null;if(this.i.insertBefore(this.element,r),this.options.stabilizeOut){const s=this.p();this.log("stabilizing out");const o=this.A.left-s.left,a=this.A.top-s.top;getComputedStyle(this.element).position!=="static"||o===0&&a===0||(this.element.style.position="relative"),o!==0&&(this.element.style.left=o+"px"),a!==0&&(this.element.style.top=a+"px")}}const e=this.V(this.options.keyframeOptions);await this.animate(this.options.out,e),this.element.remove()}prepare(){this.createFinished()}start(){var e,t;(t=(e=this.options).onStart)==null||t.call(e,this)}didFinish(e){var t,r;e&&((r=(t=this.options).onComplete)==null||r.call(t,this)),this.A=void 0,this.animatingProperties=void 0,this.frames=void 0,this.resolveFinished()}P(){const e=[];for(let t=this.element.parentNode;t;t=t==null?void 0:t.parentNode){const r=Xe.get(t);r&&!r.isDisabled()&&r&&e.push(r)}return e}get isHostRendered(){const e=We.has(this.u);return e||this.u.updateComplete.then(()=>{We.add(this.u)}),e}V(e,t=this.P()){const r={...Gi};return t.forEach(s=>Object.assign(r,s.options.keyframeOptions)),Object.assign(r,e),r}O(e,t,r){e={...e},t={...t};const s=r.map(l=>l.animatingProperties).filter(l=>l!==void 0);let o=1,a=1;return s.length>0&&(s.forEach(l=>{l.width&&(o/=l.width),l.height&&(a/=l.height)}),e.left!==void 0&&t.left!==void 0&&(e.left=o*e.left,t.left=o*t.left),e.top!==void 0&&t.top!==void 0&&(e.top=a*e.top,t.top=a*t.top)),{from:e,to:t}}calculateKeyframes(e,t,r=!1){const s={},o={};let a=!1;const l={};for(const c in t){const u=e[c],d=t[c];if(c in he){const p=he[c];if(u===void 0||d===void 0)continue;const f=p(u,d);f.transform!==void 0&&(l[c]=f.value,a=!0,s.transform=`${s.transform??""} ${f.transform}`,f.overrideFrom!==void 0&&Object.assign(s,f.overrideFrom))}else u!==d&&u!==void 0&&d!==void 0&&(a=!0,s[c]=u,o[c]=d)}return s.transformOrigin=o.transformOrigin=r?"center center":"top left",this.animatingProperties=l,a?[s,o]:void 0}async animate(e,t=this.options.keyframeOptions){this.start(),this.frames=e;let r=!1;if(!this.isAnimating()&&!this.isDisabled()&&(this.options.onFrames&&(this.frames=e=this.options.onFrames(this),this.log("modified frames",e)),e!==void 0)){this.log("animate",[e,t]),r=!0,this.webAnimation=this.element.animate(e,t);const s=this.getController();s==null||s.add(this);try{await this.webAnimation.finished}catch{}s==null||s.remove(this)}return this.didFinish(r),r}isAnimating(){var e,t;return((e=this.webAnimation)==null?void 0:e.playState)==="running"||((t=this.webAnimation)==null?void 0:t.pending)}log(e,t){this.shouldLog&&!this.isDisabled()&&console.log(e,this.options.id,t)}}const Vi=Z.directive(Wi),Ki=["top","right","bottom","left"];class Yi extends Qe.AsyncDirective{constructor(e){if(super(e),e.type!==Z.PartType.ELEMENT)throw Error("The `position` directive must be used in attribute position.")}render(e,t){return Ze.nothing}update(e,[t,r]){var s;return this.u===void 0&&(this.u=(s=e.options)==null?void 0:s.host,this.u.addController(this)),this.C=e.element,this.N=t,this.S=r??["left","top","width","height"],this.render(t,r)}hostUpdated(){this.F()}F(){var o,a;const e=typeof this.N=="function"?this.N():(o=this.N)==null?void 0:o.value,t=e.offsetParent;if(e===void 0||!t)return;const r=e.getBoundingClientRect(),s=t.getBoundingClientRect();(a=this.S)==null||a.forEach(l=>{const c=Ki.includes(l)?r[l]-s[l]:r[l];this.C.style[l]=c+"px"})}}Z.directive(Yi);const Xi=':host{display:flex;justify-content:center}.strip{position:relative;display:inline-flex;align-items:center;min-height:44px}.chip{display:flex;align-items:center;padding:2px;margin-right:-11px;background:var(--uc-ai-floating, var(--uc-ai-background));border:1px solid transparent;border-radius:calc(var(--uc-ai-radius-button, 8px) + 2px);box-shadow:0 1px 8px #0000004d;cursor:pointer;transform:scale(1);transition:margin .3s var(--uc-ai-ease-out, ease),border-color 225ms ease,transform .27s var(--uc-ai-ease-out, ease),opacity .33s var(--uc-ai-ease-out, ease)}.chip:disabled{cursor:not-allowed}.chip:last-child{margin-right:0}@media(hover:hover)and (pointer:fine){.chip:hover:not(:disabled){transform:scale(1.1)}.strip:hover .chip:not(:disabled){margin-right:7px}.strip:hover .chip:not(:disabled):last-child{margin-right:0}}.chip--selected{border-color:var(--uc-ai-primary);transform:scale(1.2)}.thumb{position:relative;display:block;width:40px;height:40px;border-radius:var(--uc-ai-radius-button, 8px);background-color:var(--uc-ai-muted);overflow:hidden}.thumb:not(.thumb--loaded):after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;background:linear-gradient(100deg,transparent 30%,color-mix(in srgb,var(--uc-ai-foreground) 9%,transparent) 50%,transparent 70%);transform:translate(-100%);animation:thumb-shimmer 1.2s ease-in-out infinite}@keyframes thumb-shimmer{to{transform:translate(100%)}}.thumb__img{display:block;width:100%;height:100%;object-fit:cover;opacity:0;transition:opacity .24s var(--uc-ai-ease-out, ease)}.thumb--loaded .thumb__img{opacity:1}@media(prefers-reduced-motion:reduce){.thumb:not(.thumb--loaded):after{animation:none}.thumb__img{transition:none}}.startover{position:absolute;right:calc(100% + 10px);top:50%;display:flex;align-items:center;background:var(--uc-ai-floating, var(--uc-ai-background));border:1px solid var(--uc-ai-floating-border, transparent);border-radius:calc(var(--uc-ai-radius-button, 8px) + 2px);box-shadow:var(--uc-ai-dialog-shadow);white-space:nowrap;opacity:0;transform:translateY(-50%) translate(-6px) scale(.95);transform-origin:right center;pointer-events:none;transition:opacity .26s var(--uc-ai-ease-out, ease),transform .26s var(--uc-ai-ease-out, ease)}.strip:hover .startover,.strip:focus-within .startover{opacity:1;transform:translateY(-50%) translate(0) scale(1);pointer-events:auto}.strip--empty .startover{position:static;opacity:1;transform:none;pointer-events:auto}.startover__btn{height:var(--uc-ai-button-size, 32px);padding:0 12px;background:transparent;border:0;border-radius:inherit;color:var(--uc-ai-foreground);font:inherit;font-size:13px;cursor:pointer}.startover__btn:disabled{cursor:not-allowed}.startover__btn:hover{background:var(--uc-ai-secondary)}.strip:before{content:"";position:absolute;right:100%;top:-12px;bottom:-12px;width:200px}.strip--empty:before{content:none}@media(prefers-reduced-motion:reduce){.chip,.startover{transition-property:opacity,border-color,margin}.chip:hover,.chip--selected{transform:scale(1)}.strip:not(.strip--empty) .startover,.strip:not(.strip--empty):hover .startover,.strip:not(.strip--empty):focus-within .startover{transform:translateY(-50%)}}';var Ji=Object.defineProperty,Zi=Object.getOwnPropertyDescriptor,O=(i,e,t,r)=>{for(var s=r>1?void 0:r?Zi(e,t):e,o=i.length-1,a;o>=0;o--)(a=i[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&Ji(e,t,s),s};const Qi=80;let A=class extends h.LitElement{constructor(){super(...arguments),this.entries=[],this.selectedUuid=null,this.showStartOver=!1,this.startOverLabel="",this.listLabel="Generation history",this.busy=!1,this._secure=new ct(this),this._loaded=new Set}willUpdate(i){if(i.has("secureResolver")&&this._secure.setResolver(this.secureResolver),i.has("entries")){const e=new Set(this.entries.map(t=>t.id));for(const t of this._loaded)e.has(t)||this._loaded.delete(t)}}_onThumbSettled(i){this._loaded.has(i)||(this._loaded.add(i),this.requestUpdate())}_select(i){this.dispatchEvent(new CustomEvent("uc:select",{detail:{entry:i},bubbles:!0,composed:!0}))}_startOver(){this.dispatchEvent(new CustomEvent("uc:start-over",{bubbles:!0,composed:!0}))}render(){const i=this.entries.length>0;if(!i&&!this.showStartOver)return h.html`${h.nothing}`;const e={strip:!0,"strip--empty":!i},t=[...this.entries].reverse();return h.html`
50
+ <div class=${k.classMap(e)} role="toolbar" aria-label="${this.listLabel}">
51
+ ${this.showStartOver?h.html`
52
+ <div class="startover">
53
+ <button type="button" ?disabled="${this.busy}" class="startover__btn" @click=${this._startOver}>
54
+ ${this.startOverLabel}
55
+ </button>
56
+ </div>
57
+ `:h.nothing}
58
+ ${mt.repeat(t,r=>r.id,r=>{const s=this._secure.resolve(Ai(r.url,Qi)),o=this.selectedUuid!=null&&r.file.uuid===this.selectedUuid,a=this._loaded.has(r.id);return h.html`
59
+ <button
60
+ type="button"
61
+ ?disabled=${this.busy}
62
+ class=${k.classMap({chip:!0,"chip--selected":o})}
63
+ aria-pressed="${o?"true":"false"}"
64
+ aria-label=${r.prompt||"Result"}
65
+ title=${r.prompt}
66
+ @click=${()=>this._select(r)}
67
+ ${Vi({keyframeOptions:{duration:300,easing:"cubic-bezier(0.23, 1, 0.32, 1)"}})}
68
+ >
69
+ <span class=${k.classMap({thumb:!0,"thumb--loaded":a})}>
70
+ ${s?h.html`<img
71
+ class="thumb__img"
72
+ src="${s}"
73
+ alt=""
74
+ aria-hidden="true"
75
+ decoding="async"
76
+ @load=${()=>this._onThumbSettled(r.id)}
77
+ @error=${()=>this._onThumbSettled(r.id)}
78
+ />`:h.nothing}
79
+ </span>
80
+ </button>
81
+ `})}
82
+ </div>
83
+ `}};A.styles=h.unsafeCSS(Xi);O([n.property({attribute:!1})],A.prototype,"entries",2);O([n.property({attribute:"selected-uuid"})],A.prototype,"selectedUuid",2);O([n.property({type:Boolean,attribute:"show-start-over"})],A.prototype,"showStartOver",2);O([n.property({attribute:"start-over-label"})],A.prototype,"startOverLabel",2);O([n.property({attribute:"list-label"})],A.prototype,"listLabel",2);O([n.property({type:Boolean})],A.prototype,"busy",2);O([n.property({attribute:!1})],A.prototype,"secureResolver",2);A=O([n.customElement("uc-ai-history")],A);const er=':host{display:block}.card{width:100%;box-sizing:border-box;background:color-mix(in srgb,var(--uc-ai-floating, var(--uc-ai-background)) 80%,transparent);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border:1px solid var(--uc-ai-floating-border, transparent);border-radius:var(--uc-ai-composer-radius-top) var(--uc-ai-composer-radius-top) var(--uc-ai-composer-radius-bottom) var(--uc-ai-composer-radius-bottom);transition:border-radius .4s var(--uc-ai-ease-out),box-shadow .4s var(--uc-ai-ease-out);box-shadow:var(--uc-ai-composer-shadow);overflow:visible;--uc-ai-radius-button: max(0px, calc(var(--uc-ai-composer-radius) - var(--uc-ai-padding)))}.body{display:flex;flex-direction:column;gap:var(--uc-ai-padding);padding:var(--uc-ai-padding)}.input{box-sizing:border-box;width:100%;min-height:40px;max-height:var(--uc-ai-prompt-max-height, calc(var(--uc-ai-prompt-max-lines, 6) * 1.5em + 10px));resize:none;border:0;outline:none;padding:0 3px;background:transparent;font-family:inherit;font-size:var(--uc-ai-font-size);line-height:20px;color:var(--uc-ai-foreground);overflow-y:auto;scrollbar-width:thin;scrollbar-color:var(--uc-ai-border) transparent;transition:height .16s var(--uc-ai-ease-out, ease)}@supports (field-sizing: content){.input{field-sizing:content;transition:none}}.input::placeholder{color:var(--uc-ai-muted-foreground)}.input:disabled{color:var(--uc-ai-muted-foreground);-webkit-text-fill-color:var(--uc-ai-muted-foreground);cursor:not-allowed}.row{display:flex;align-items:center;gap:10px}.actions{flex:1;min-width:0;display:flex;align-items:center}.actions::slotted(*){min-width:0}.controls{display:flex;align-items:center;gap:0;flex:none}.send{margin-left:5px;width:var(--uc-ai-button-size, 32px);height:var(--uc-ai-button-size, 32px);flex:none;min-width:0;display:inline-flex;align-items:center;justify-content:center;position:relative;background:var(--uc-ai-primary);color:var(--uc-ai-primary-foreground);border:none;border-radius:var(--uc-ai-radius-button);cursor:pointer;overflow:hidden;transition:width .22s var(--uc-ai-ease-out, ease),margin-left .22s var(--uc-ai-ease-out, ease),opacity .15s var(--uc-ai-ease-out, ease),transform .15s var(--uc-ai-ease-out, ease),background var(--uc-ai-transition)}.send:hover:not(:disabled){background:var(--uc-ai-primary-hover)}.send:active:not(:disabled){transform:scale(.95)}.send:disabled{cursor:default}.send[hidden]{display:inline-flex;width:0;min-width:0;padding:0;margin-left:0;opacity:0;transform:scale(.8);pointer-events:none}.send__icon,.send__spinner{position:absolute;top:50%;left:50%;width:16px;height:16px;transition:opacity .2s var(--uc-ai-ease-out, ease),transform .2s var(--uc-ai-ease-out, ease),filter .2s var(--uc-ai-ease-out, ease)}.send__icon{opacity:1;transform:translate(-50%,-50%) scale(1);filter:blur(0)}.send__icon svg{width:16px;height:16px;display:block}.send__spinner{opacity:0;transform:translate(-50%,-50%) scale(.95);filter:blur(3px)}.send__spinner:before,.send__spinner:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;border-radius:50%;border:1.5px solid currentColor}.send__spinner:before{opacity:.3}.send__spinner:after{border-top-color:transparent;animation:send-spin .7s linear infinite;will-change:transform}@keyframes send-spin{to{transform:rotate(360deg)}}.send--busy .send__icon{opacity:0;transform:translate(-50%,-50%) scale(.95);filter:blur(3px)}.send--busy .send__spinner{opacity:1;transform:translate(-50%,-50%) scale(1);filter:blur(0)}.send--busy:disabled{opacity:1}@media(prefers-reduced-motion:reduce){.input,.send{transition-property:opacity,background,width,margin-left}.send__icon,.send__spinner{transition-property:opacity}.send__spinner:after{animation:none}.send:active:not(:disabled){transform:none}}';var tr=Object.defineProperty,ir=Object.getOwnPropertyDescriptor,I=(i,e,t,r)=>{for(var s=r>1?void 0:r?ir(e,t):e,o=i.length-1,a;o>=0;o--)(a=i[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&tr(e,t,s),s};let C=class extends h.LitElement{constructor(){super(...arguments),this.mode="generate",this.value="",this.placeholder="",this.busy=!1,this.allowCustom=!0,this.sendAriaLabel=""}focusInput(){var i;(i=this._inputEl)==null||i.focus()}updated(i){i.has("value")&&this._resize()}_resize(){const i=this._inputEl;!i||CSS.supports("field-sizing","content")||(i.style.height="auto",i.style.height=`${i.scrollHeight}px`)}_onInput(i){const e=i.target.value;this.value=e,this.dispatchEvent(new CustomEvent("uc:input",{detail:{value:e},bubbles:!0,composed:!0})),this._resize()}_onKeydown(i){i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&this.value.trim()&&!this.busy&&(i.preventDefault(),this._emitSend())}_emitSend(){this.dispatchEvent(new CustomEvent("uc:send",{bubbles:!0,composed:!0}))}render(){const i=this.value.trim().length===0;return h.html`
84
+ <div class="card">
85
+ <div class="body">
86
+ ${this.allowCustom?h.html`<textarea
87
+ class="input"
88
+ rows="1"
89
+ .value=${this.value}
90
+ placeholder="${this.placeholder}"
91
+ aria-label="${this.placeholder}"
92
+ autocomplete="off"
93
+ autocorrect="off"
94
+ autocapitalize="off"
95
+ spellcheck="false"
96
+ name="uc-ai-prompt"
97
+ data-1p-ignore
98
+ data-lpignore="true"
99
+ data-form-type="other"
100
+ @input=${this._onInput}
101
+ @keydown=${this._onKeydown}
102
+ ?disabled=${this.busy}
103
+ ></textarea>`:h.nothing}
104
+
105
+ <div class="row">
106
+ <div class="actions">
107
+ <slot name="chips"></slot>
108
+ </div>
109
+ <div class="controls">
110
+ <slot name="aspect-ratio"></slot>
111
+ <button
112
+ type="button"
113
+ class=${k.classMap({send:!0,"send--busy":this.busy})}
114
+ aria-label="${this.sendAriaLabel}"
115
+ ?hidden=${i}
116
+ ?disabled=${this.busy||i}
117
+ @click=${this._emitSend}
118
+ >
119
+ <span class="send__icon">${J.unsafeSVG(Ii)}</span>
120
+ <span class="send__spinner" aria-hidden="true"></span>
121
+ </button>
122
+ </div>
123
+ </div>
124
+ </div>
125
+ </div>
126
+ `}};C.styles=h.unsafeCSS(er);I([n.property()],C.prototype,"mode",2);I([n.property()],C.prototype,"value",2);I([n.property()],C.prototype,"placeholder",2);I([n.property({type:Boolean})],C.prototype,"busy",2);I([n.property({type:Boolean})],C.prototype,"allowCustom",2);I([n.property({attribute:"send-aria-label"})],C.prototype,"sendAriaLabel",2);I([n.query(".input")],C.prototype,"_inputEl",2);C=I([n.customElement("uc-ai-prompt-row")],C);const rr=":host{display:block;min-width:0}.row{display:flex;flex-wrap:nowrap;align-items:center;gap:5px;overflow-x:auto;scrollbar-width:none}.row::-webkit-scrollbar{display:none}.row.fade-left.fade-right{-webkit-mask-image:linear-gradient(to right,transparent 0,#000 10px,#000 calc(100% - 10px),transparent 100%);mask-image:linear-gradient(to right,transparent 0,#000 10px,#000 calc(100% - 10px),transparent 100%)}.row.fade-left:not(.fade-right){-webkit-mask-image:linear-gradient(to right,transparent 0,#000 10px);mask-image:linear-gradient(to right,transparent 0,#000 10px)}.row.fade-right:not(.fade-left){-webkit-mask-image:linear-gradient(to right,#000 calc(100% - 10px),transparent 100%);mask-image:linear-gradient(to right,#000 calc(100% - 10px),transparent 100%)}.chip{flex:none;height:var(--uc-ai-button-size, 32px);display:inline-flex;align-items:center;justify-content:center;padding:0 10px;background:var(--uc-ai-secondary);border:0;border-radius:var(--uc-ai-radius-button);font-family:inherit;font-size:13px;line-height:20px;color:var(--uc-ai-secondary-foreground);cursor:pointer;white-space:nowrap;transition:background .15s ease,transform .14s var(--uc-ai-ease-out, ease)}@media(hover:hover)and (pointer:fine){.chip:hover{background:var(--uc-ai-secondary-hover)}}.chip:active{background:var(--uc-ai-secondary-hover);transform:scale(.97)}.chip:disabled{opacity:.5;cursor:not-allowed}@media(prefers-reduced-motion:reduce){.chip{transition-property:background}.chip:active{transform:none}}";var sr=Object.defineProperty,or=Object.getOwnPropertyDescriptor,B=(i,e,t,r)=>{for(var s=r>1?void 0:r?or(e,t):e,o=i.length-1,a;o>=0;o--)(a=i[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&sr(e,t,s),s};let M=class extends h.LitElement{constructor(){super(...arguments),this.mode="generate",this.presets=null,this.busy=!1,this.labelText="Quick prompts"}firstUpdated(){typeof ResizeObserver=="function"&&this._rowEl&&(this._resizeObserver=new ResizeObserver(()=>this._updateFades()),this._resizeObserver.observe(this._rowEl)),this._updateFades()}updated(){this._updateFades()}disconnectedCallback(){var i;super.disconnectedCallback(),(i=this._resizeObserver)==null||i.disconnect()}_updateFades(){const i=this._rowEl;if(!i)return;const e=i.scrollWidth-i.clientWidth,t=i.scrollLeft;i.classList.toggle("fade-left",t>1),i.classList.toggle("fade-right",t<e-1)}_onWheel(i){const e=this._rowEl;!e||e.scrollWidth<=e.clientWidth||Math.abs(i.deltaY)<=Math.abs(i.deltaX)||(e.scrollLeft+=i.deltaY,i.preventDefault())}_select(i){this.dispatchEvent(new CustomEvent("uc:select",{detail:{preset:i},bubbles:!0,composed:!0}))}render(){const i=this.presets??me[this.mode].presets;return h.html`
127
+ <div
128
+ class="row"
129
+ role="toolbar"
130
+ aria-label="${this.labelText}"
131
+ @scroll=${this._updateFades}
132
+ @wheel=${this._onWheel}
133
+ >
134
+ ${i.map(e=>h.html`
135
+ <button type="button" class="chip" @click=${()=>this._select(e)} ?disabled=${this.busy}>
136
+ ${e.label}
137
+ </button>
138
+ `)}
139
+ </div>
140
+ `}};M.styles=h.unsafeCSS(rr);B([n.property()],M.prototype,"mode",2);B([n.property({attribute:!1})],M.prototype,"presets",2);B([n.property({type:Boolean})],M.prototype,"busy",2);B([n.property({attribute:"aria-label-text"})],M.prototype,"labelText",2);B([n.query(".row")],M.prototype,"_rowEl",2);M=B([n.customElement("uc-ai-chips")],M);function L(i,e){if(i===null)throw new Error(`DotGrid GL: failed to create ${e} (context lost?)`);return i}const ge=8,ar=`#version 300 es
141
+ precision highp float;
142
+ precision highp int;
143
+ in vec2 aCorner; // unit quad corner, -0.5..0.5
144
+ in float aClip; // per-instance frame clip, 0..1
145
+ uniform vec2 uResolution;
146
+ uniform float uCols;
147
+ uniform vec2 uOffset;
148
+ uniform float uCell;
149
+ uniform float uBaseRadius;
150
+ uniform float uFullHalf;
151
+ uniform float uEnv;
152
+ uniform float uShimMix;
153
+ uniform int uMask;
154
+ uniform int uGenerating;
155
+ uniform float uMinScale;
156
+ uniform float uPeakScale;
157
+ uniform float uIdleScale;
158
+ uniform int uEpiCount;
159
+ uniform vec2 uEpis[${ge}];
160
+ uniform float uEpiRadius;
161
+ uniform float uEpiFalloff;
162
+ uniform float uColorA;
163
+ uniform float uFalloffWarp; // bends the distance field (de-ring)
164
+ uniform float uDither; // per-dot size dither
165
+ out float vAlpha;
166
+ out vec2 vLocalPx; // fragment offset from the dot centre, CSS px
167
+ out float vHalf; // dot half-size, CSS px
168
+
169
+ float hash(float a, float b) { return fract(sin(a * 12.9898 + b * 78.233) * 43758.5453); }
170
+
171
+ float epiIntensity(vec2 p) {
172
+ float best = 0.0;
173
+ // Low-frequency warp of the distance field — dissolves ring banding.
174
+ float k = uFalloffWarp > 0.0 ? (6.2831853 / (uEpiRadius * 0.7)) : 0.0;
175
+ float warp = k > 0.0 ? uFalloffWarp * uEpiRadius * sin(p.x * k + 1.3) * cos(p.y * k * 0.9) : 0.0;
176
+ for (int i = 0; i < ${ge}; i++) {
177
+ if (i >= uEpiCount) break;
178
+ float d = max(0.0, distance(p, uEpis[i]) + warp);
179
+ if (d >= uEpiRadius) continue;
180
+ float t = 1.0 - d / uEpiRadius;
181
+ float f = t * t * (3.0 - 2.0 * t); // smoothstep
182
+ if (uEpiFalloff != 1.0) f = pow(f, uEpiFalloff);
183
+ best = max(best, f);
184
+ }
185
+ return best;
186
+ }
187
+
188
+ void main() {
189
+ float col = mod(float(gl_InstanceID), uCols);
190
+ float row = floor(float(gl_InstanceID) / uCols);
191
+ vec2 center = uOffset + vec2(col, row) * uCell;
192
+ float intensity = epiIntensity(center);
193
+ // When masking, ignore the per-dot frame clip and let the scissor define the
194
+ // frame edge instead: dots straddling the edge then poke in and cover it, so
195
+ // the revealed image fills the frame exactly (no uncovered strip that pops in
196
+ // when the grid hands off to the real <img>). The idle/shimmer grid keeps the
197
+ // soft per-dot clip so stray dots never show outside the frame.
198
+ float clipv = (uMask == 1) ? 1.0 : aClip;
199
+
200
+ // Per-dot size dither (scaled by intensity), breaking the size-wave's banding.
201
+ float sizeDither = (hash(col, row) - 0.5) * uDither * intensity;
202
+
203
+ float halfSize;
204
+ if (uMask == 1) {
205
+ float wave = uMinScale + (uPeakScale - uMinScale) * intensity + sizeDither;
206
+ float animated = (uGenerating == 1) ? wave : uMinScale;
207
+ float smallHalf = uBaseRadius * animated;
208
+ halfSize = (uFullHalf + uEnv * (smallHalf - uFullHalf)) * clipv;
209
+ } else {
210
+ float scale = uIdleScale;
211
+ if (uShimMix > 0.0) {
212
+ float wave = uMinScale + (uPeakScale - uMinScale) * intensity + sizeDither;
213
+ scale += (wave - scale) * uShimMix;
214
+ }
215
+ halfSize = uBaseRadius * scale * clipv;
216
+ }
217
+
218
+ if (halfSize <= 0.0) {
219
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0); // offscreen → culled
220
+ vAlpha = 0.0;
221
+ vLocalPx = vec2(0.0);
222
+ vHalf = 0.0;
223
+ return;
224
+ }
225
+
226
+ // Expand the quad ~1px beyond the dot so the fragment can anti-alias the edge
227
+ // sub-pixel — without this, hard quad edges snap to whole pixels and the
228
+ // grow/shrink reveal looks stepped.
229
+ float ext = halfSize + 1.0;
230
+ vLocalPx = aCorner * (2.0 * ext);
231
+ vHalf = halfSize;
232
+ vec2 pos = center + aCorner * (2.0 * ext);
233
+ vec2 ndc = (pos / uResolution) * 2.0 - 1.0;
234
+ gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
235
+
236
+ vAlpha = (uMask == 1) ? 1.0 : uColorA;
237
+ }`,nr=`#version 300 es
238
+ precision highp float;
239
+ precision highp int;
240
+ in float vAlpha;
241
+ in vec2 vLocalPx; // CSS px from the dot centre
242
+ in float vHalf; // dot half-size, CSS px
243
+ uniform vec3 uColorRGB;
244
+ uniform int uMask;
245
+ out vec4 frag;
246
+ void main() {
247
+ // Box signed distance, evaluated in CSS px, anti-aliased over ~1px of screen
248
+ // space via fwidth — so size changes are sub-pixel-smooth (no stepping) while
249
+ // a square at idle still reads crisp.
250
+ vec2 d = abs(vLocalPx) - vec2(vHalf);
251
+ float sd = min(max(d.x, d.y), 0.0) + length(max(d, vec2(0.0)));
252
+ float aaw = max(fwidth(sd), 1e-4);
253
+ float cov = clamp(0.5 - sd / aaw, 0.0, 1.0);
254
+ vec3 rgb = (uMask == 1) ? vec3(1.0) : uColorRGB;
255
+ frag = vec4(rgb * vAlpha * cov, vAlpha * cov); // premultiplied
256
+ }`,lr=`#version 300 es
257
+ precision highp float;
258
+ in vec2 aQuad; // 0..1
259
+ uniform vec2 uResolution;
260
+ uniform vec4 uFrame; // left, top, right, bottom (CSS px)
261
+ out vec2 vFramePx;
262
+ void main() {
263
+ vec2 px = mix(uFrame.xy, uFrame.zw, aQuad);
264
+ vFramePx = px - uFrame.xy;
265
+ vec2 ndc = (px / uResolution) * 2.0 - 1.0;
266
+ gl_Position = vec4(ndc.x, -ndc.y, 0.0, 1.0);
267
+ }`,cr=`#version 300 es
268
+ precision highp float;
269
+ in vec2 vFramePx;
270
+ uniform sampler2D uImage;
271
+ uniform vec2 uFrameSize;
272
+ uniform vec2 uImageSize;
273
+ out vec4 frag;
274
+ void main() {
275
+ // object-fit: cover.
276
+ float s = max(uFrameSize.x / uImageSize.x, uFrameSize.y / uImageSize.y);
277
+ vec2 dsz = uImageSize * s;
278
+ vec2 off = (uFrameSize - dsz) * 0.5;
279
+ vec2 uv = (vFramePx - off) / dsz;
280
+ frag = vec4(texture(uImage, uv).rgb, 1.0);
281
+ }`;class Ee{constructor(e){this._dotUniforms={},this._imgUniforms={},this._appliedW=0,this._appliedH=0,this._appliedScale=0,this._texImage=null,this._texOk=!1,this._gl=e,this._dotProgram=this._link(ar,nr),this._imgProgram=this._link(lr,cr),this._cornerBuf=this._staticBuffer([-.5,-.5,.5,-.5,-.5,.5,.5,.5]),this._quadBuf=this._staticBuffer([0,0,1,0,0,1,1,1]),this._clipBuf=L(e.createBuffer(),"buffer"),this._dotVao=L(e.createVertexArray(),"vertex array"),e.bindVertexArray(this._dotVao);const t=e.getAttribLocation(this._dotProgram,"aCorner");e.bindBuffer(e.ARRAY_BUFFER,this._cornerBuf),e.enableVertexAttribArray(t),e.vertexAttribPointer(t,2,e.FLOAT,!1,0,0);const r=e.getAttribLocation(this._dotProgram,"aClip");e.bindBuffer(e.ARRAY_BUFFER,this._clipBuf),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,1,e.FLOAT,!1,0,0),e.vertexAttribDivisor(r,1),e.bindVertexArray(null),this._imgVao=L(e.createVertexArray(),"vertex array"),e.bindVertexArray(this._imgVao);const s=e.getAttribLocation(this._imgProgram,"aQuad");e.bindBuffer(e.ARRAY_BUFFER,this._quadBuf),e.enableVertexAttribArray(s),e.vertexAttribPointer(s,2,e.FLOAT,!1,0,0),e.bindVertexArray(null);for(const o of["uResolution","uCols","uOffset","uCell","uBaseRadius","uFullHalf","uEnv","uShimMix","uMask","uGenerating","uMinScale","uPeakScale","uIdleScale","uEpiCount","uEpis","uEpiRadius","uEpiFalloff","uColorA","uColorRGB","uFalloffWarp","uDither"])this._dotUniforms[o]=e.getUniformLocation(this._dotProgram,o);for(const o of["uResolution","uFrame","uImage","uFrameSize","uImageSize"])this._imgUniforms[o]=e.getUniformLocation(this._imgProgram,o);this._texture=L(e.createTexture(),"texture"),e.bindTexture(e.TEXTURE_2D,this._texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1)}static create(e){let t=null;try{t=e.getContext("webgl2",{premultipliedAlpha:!0,antialias:!1,alpha:!0,preserveDrawingBuffer:!0})}catch{return null}if(!t)return null;try{return new Ee(t)}catch(r){return typeof console<"u"&&console.warn("[dot-grid] WebGL init failed, using 2D:",r),null}}setImage(e){const t=this._gl;if(this._texImage=e,this._texOk=!1,!(!e||!e.complete||e.naturalWidth===0)){t.bindTexture(t.TEXTURE_2D,this._texture);try{t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),this._texOk=!0}catch{this._texOk=!1}}}get hasImage(){return this._texOk}render(e){const t=this._gl;this._resize(e.cssW,e.cssH,e.scale),t.disable(t.SCISSOR_TEST),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT);const r=e.cols*e.rows;if(r<=0)return;if(e.mask){const o=e.scale,a=Math.round(e.frameLeft*o),l=Math.round((e.cssH-e.frameBottom)*o),c=Math.round((e.frameRight-e.frameLeft)*o),u=Math.round((e.frameBottom-e.frameTop)*o);t.enable(t.SCISSOR_TEST),t.scissor(a,l,Math.max(0,c),Math.max(0,u))}t.bindBuffer(t.ARRAY_BUFFER,this._clipBuf),t.bufferData(t.ARRAY_BUFFER,e.clip,t.DYNAMIC_DRAW),t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.useProgram(this._dotProgram),t.bindVertexArray(this._dotVao);const s=this._dotUniforms;if(t.uniform2f(s.uResolution,e.cssW,e.cssH),t.uniform1f(s.uCols,e.cols),t.uniform2f(s.uOffset,e.offsetX,e.offsetY),t.uniform1f(s.uCell,e.cell),t.uniform1f(s.uBaseRadius,e.baseRadius),t.uniform1f(s.uFullHalf,e.fullHalf),t.uniform1f(s.uEnv,e.env),t.uniform1f(s.uShimMix,e.shimMix),t.uniform1i(s.uMask,e.mask?1:0),t.uniform1i(s.uGenerating,e.generating?1:0),t.uniform1f(s.uMinScale,e.minScale),t.uniform1f(s.uPeakScale,e.peakScale),t.uniform1f(s.uIdleScale,e.idleScale),t.uniform1i(s.uEpiCount,Math.min(e.epiCount,ge)),t.uniform2fv(s.uEpis,e.epis),t.uniform1f(s.uEpiRadius,e.epiRadius),t.uniform1f(s.uEpiFalloff,e.epiFalloff),t.uniform1f(s.uColorA,e.color[3]),t.uniform3f(s.uColorRGB,e.color[0],e.color[1],e.color[2]),t.uniform1f(s.uFalloffWarp,e.falloffWarp),t.uniform1f(s.uDither,e.dither),t.drawArraysInstanced(t.TRIANGLE_STRIP,0,4,r),e.mask&&this._texOk&&this._texImage){t.blendFunc(t.DST_ALPHA,t.ZERO),t.useProgram(this._imgProgram),t.bindVertexArray(this._imgVao);const o=this._imgUniforms;t.uniform2f(o.uResolution,e.cssW,e.cssH),t.uniform4f(o.uFrame,e.frameLeft,e.frameTop,e.frameRight,e.frameBottom),t.uniform2f(o.uFrameSize,e.frameRight-e.frameLeft,e.frameBottom-e.frameTop),t.uniform2f(o.uImageSize,this._texImage.naturalWidth,this._texImage.naturalHeight),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this._texture),t.uniform1i(o.uImage,0),t.drawArrays(t.TRIANGLE_STRIP,0,4)}t.disable(t.SCISSOR_TEST),t.bindVertexArray(null)}dispose(){var t;const e=this._gl;e.deleteProgram(this._dotProgram),e.deleteProgram(this._imgProgram),e.deleteBuffer(this._cornerBuf),e.deleteBuffer(this._quadBuf),e.deleteBuffer(this._clipBuf),e.deleteVertexArray(this._dotVao),e.deleteVertexArray(this._imgVao),e.deleteTexture(this._texture),(t=e.getExtension("WEBGL_lose_context"))==null||t.loseContext()}_resize(e,t,r){if(e===this._appliedW&&t===this._appliedH&&r===this._appliedScale)return;const s=this._gl;s.canvas.width=Math.round(e*r),s.canvas.height=Math.round(t*r),s.canvas.style.width=`${e}px`,s.canvas.style.height=`${t}px`,s.viewport(0,0,s.canvas.width,s.canvas.height),this._appliedW=e,this._appliedH=t,this._appliedScale=r}_staticBuffer(e){const t=this._gl,r=L(t.createBuffer(),"buffer");return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}_link(e,t){const r=this._gl,s=this._compile(r.VERTEX_SHADER,e),o=this._compile(r.FRAGMENT_SHADER,t),a=L(r.createProgram(),"program");if(r.attachShader(a,s),r.attachShader(a,o),r.linkProgram(a),r.deleteShader(s),r.deleteShader(o),!r.getProgramParameter(a,r.LINK_STATUS)){const l=r.getProgramInfoLog(a);throw r.deleteProgram(a),new Error(`DotGrid GL link failed: ${l}`)}return a}_compile(e,t){const r=this._gl,s=L(r.createShader(e),"shader");if(r.shaderSource(s,t),r.compileShader(s),!r.getShaderParameter(s,r.COMPILE_STATUS)){const o=r.getShaderInfoLog(s);throw r.deleteShader(s),new Error(`DotGrid GL compile failed: ${o}`)}return s}}const hr=1200,ur=800,dr=1.5,Je=i=>1-(1-i)**3,pr={cellSize:6,dotRatio:.46,sizeScale:1,minScale:.68,peakScale:1.6,dither:.1,epiCount:2,epiRadiusRatio:.4,epiSpeed:.54,epiWander:.115,epiFalloff:1.5,falloffWarp:.12,idleScale:.9,maxDpr:3,edgeTau:80,enterMs:380,exitMs:420,shimEnterMs:450,shimExitMs:450};class fr{constructor(e,t){this._refs=null,this._ctx=null,this._gl=null,this._glImageEl=null,this._glImageReady=!1,this._cfg={...pr},this._sizeMul=1,this._dotColor="rgba(0, 0, 0, 0.16)",this._dotColorRGBA=[0,0,0,.16],this._w=0,this._h=0,this._cols=0,this._rows=0,this._offsetX=0,this._offsetY=0,this._epiRadius=1,this._appliedScale=0,this._clip=new Float32Array(0),this._env=0,this._envFrom=0,this._envTo=0,this._envStart=0,this._envDur=0,this._envAnimating=!1,this._shimMix=0,this._shimFrom=0,this._shimTo=0,this._shimStart=0,this._shimDur=0,this._shimAnimating=!1,this._exitPending=!1,this._prevShim=!1,this._opacityManual=!1,this._hiddenImage=null,this._rafId=null,this._lastTime=0,this._state={shimmering:!1,empty:!0,generating:!1},this._epis=[],this._onThemeChange=()=>{this.refreshColor()},this._rectCache=null,this._glEpis=new Float32Array(16),this._tick=r=>{const s=this._lastTime?Math.min(64,r-this._lastTime):16;if(this._lastTime=r,this._rectCache=this._frameRect(),this._envAnimating){const a=Math.min(1,(r-this._envStart)/this._envDur);this._env=this._envFrom+(this._envTo-this._envFrom)*Je(a),a>=1&&(this._env=this._envTo,this._envAnimating=!1)}if(this._shimAnimating){const a=Math.min(1,(r-this._shimStart)/this._shimDur);this._shimMix=this._shimFrom+(this._shimTo-this._shimFrom)*Je(a),a>=1&&(this._shimMix=this._shimTo,this._shimAnimating=!1)}this._state.generating&&!this._reduceMotion&&this._moveEpicenters(s);const o=this._followFrame(s);this._draw(),this._rectCache=null,this._state.shimmering||this._envAnimating||this._shimAnimating||o?this._rafId=requestAnimationFrame(this._tick):(this._rafId=null,this._lastTime=0)},e.addController(this),t&&(this._cfg={...this._cfg,...t}),this._reduceMotion=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1}get _canDraw(){return!!this._ctx||!!this._gl}get _baseRadius(){return this._cfg.cellSize*this._cfg.dotRatio/2}_computeSizeMul(){return this._w<=0||this._h<=0?1:Math.sqrt(this._w*this._h/(hr*ur))**this._cfg.sizeScale}attach(e){if(this._refs=e,this._cfg.useWebgl!==!1&&(this._gl=Ee.create(e.surface)),this._gl||(this._ctx=e.surface.getContext("2d")),!!this._canDraw){if(this._readDotColor(),typeof ResizeObserver=="function"&&(this._resizeObserver=new ResizeObserver(()=>{this._resize(),this.sync(this._state)}),this._resizeObserver.observe(e.viewport),this._frameObserver=new ResizeObserver(()=>this._ensureLoop()),this._frameObserver.observe(e.frame)),typeof window<"u"&&typeof window.matchMedia=="function"&&(this._schemeMql=window.matchMedia("(prefers-color-scheme: dark)"),this._schemeMql.addEventListener("change",this._onThemeChange)),typeof MutationObserver=="function"&&typeof document<"u"){this._themeObserver=new MutationObserver(this._onThemeChange);for(const t of[document.documentElement,document.body])t&&this._themeObserver.observe(t,{attributes:!0,attributeFilter:["class","style","data-theme"]})}this._resize(),this.sync(this._state)}}hostDisconnected(){var e,t,r,s,o;(e=this._resizeObserver)==null||e.disconnect(),(t=this._frameObserver)==null||t.disconnect(),(r=this._themeObserver)==null||r.disconnect(),(s=this._schemeMql)==null||s.removeEventListener("change",this._onThemeChange),this._rafId!==null&&cancelAnimationFrame(this._rafId),this._rafId=null,(o=this._gl)==null||o.dispose(),this._gl=null}onImageLoad(){this._glImageReady=!1,this._tryStartExit(),this._ensureLoop()}refreshColor(){this._readDotColor(),this._rafId===null&&this._draw()}settle(){this._canDraw&&(this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null,this._lastTime=0),this._exitPending=!1,this._envAnimating=!1,this._shimAnimating=!1,this._env=0,this._shimMix=0,this._prevShim=!1,this._showHiddenImage(),this._draw())}sync(e){if(this._state=e,!this._canDraw)return;const t=e.shimmering;t&&!this._prevShim?(this._exitPending=!1,this._initEpicenters(),this._hasImage()?this._startEnv(1,this._cfg.enterMs):(this._env=1,this._envAnimating=!1,this._startShimMix(1,this._cfg.shimEnterMs))):!t&&this._prevShim&&(this._hasImage()?(this._env=1,this._startEnv(0,this._cfg.exitMs),this._shimMix=0):e.empty?(this._env=0,this._envAnimating=!1,this._startShimMix(0,this._cfg.shimExitMs)):this._exitPending=!0),this._prevShim=t,t||this._envAnimating||this._shimAnimating?this._ensureLoop():this._rafId===null&&this._draw()}setConfig(e){e&&(this._cfg={...this._cfg,...e},this._canDraw&&this.recalibrate())}recalibrate(){this._canDraw&&(this._resize(),this._epis.length!==this._cfg.epiCount&&this._initEpicenters(),this._rafId===null&&this._draw())}reset(){this._env=0,this._envAnimating=!1,this._shimMix=0,this._shimAnimating=!1,this._exitPending=!1,this._prevShim=!1,this._epis.length=0,this._state={shimmering:!1,empty:!0,generating:!1},this._restoreOpacity(),this._canDraw&&(this._snapClip(),this._draw())}_now(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}_readDotColor(){if(!this._refs)return;const e=getComputedStyle(this._refs.surface).color;e&&(this._dotColor=e,this._dotColorRGBA=this._parseColor(e))}_parseColor(e){if(this._scratch2d===void 0){const s=document.createElement("canvas");s.width=s.height=1,this._scratch2d=s.getContext("2d",{willReadFrequently:!0})}const t=this._scratch2d;if(!t)return this._dotColorRGBA;t.clearRect(0,0,1,1),t.fillStyle="#000",t.fillStyle=e,t.fillRect(0,0,1,1);const r=t.getImageData(0,0,1,1).data;return[(r[0]??0)/255,(r[1]??0)/255,(r[2]??0)/255,(r[3]??0)/255]}_hasImage(){var t;const e=((t=this._refs)==null?void 0:t.getImage())??null;return!!e&&!!e.getAttribute("src")&&e.complete&&e.naturalWidth>0}_maskingImage(){return this._hasImage()&&!this._state.empty&&(this._state.shimmering||this._env>.001)}_startEnv(e,t){if(t<=0||this._reduceMotion){this._env=e,this._envTo=e,this._envAnimating=!1;return}this._envFrom=this._env,this._envTo=e,this._envStart=this._now(),this._envDur=t,this._envAnimating=!0,this._ensureLoop()}_startShimMix(e,t){if(t<=0||this._reduceMotion){this._shimMix=e,this._shimAnimating=!1;return}this._shimFrom=this._shimMix,this._shimTo=e,this._shimStart=this._now(),this._shimDur=t,this._shimAnimating=!0,this._ensureLoop()}_frameRect(){const e=this._refs,t=e.frame.getBoundingClientRect(),r=e.viewport.getBoundingClientRect(),s=t.left-r.left,o=t.top-r.top;return{left:s,top:o,right:s+t.width,bottom:o+t.height}}_liveRect(){return this._rectCache??this._frameRect()}_epiRadiusFor(e){const t=Math.max(0,e.right-e.left),r=Math.max(0,e.bottom-e.top);return Math.sqrt(t*r)*this._cfg.epiRadiusRatio||1}_inFrame(e,t,r){return e-this._baseRadius>=r.left&&e+this._baseRadius<=r.right&&t-this._baseRadius>=r.top&&t+this._baseRadius<=r.bottom}_snapClip(){const e=this._frameRect(),t=this._cfg.cellSize;let r=0;for(let s=0;s<this._rows;s++){const o=this._offsetY+s*t;for(let a=0;a<this._cols;a++,r++)this._clip[r]=this._inFrame(this._offsetX+a*t,o,e)?1:0}}_followFrame(e){const t=this._liveRect(),r=this._cfg.cellSize,s=this._reduceMotion?1:1-Math.exp(-e/this._cfg.edgeTau);let o=!1,a=0;for(let l=0;l<this._rows;l++){const c=this._offsetY+l*r;for(let u=0;u<this._cols;u++,a++){const d=this._inFrame(this._offsetX+u*r,c,t)?1:0;let p=this._clip[a]+(d-this._clip[a])*s;Math.abs(d-p)<.002?p=d:o=!0,this._clip[a]=p}}return o}_allocate(){const e=this._cfg.cellSize;this._cols=Math.max(1,Math.round(this._w/e)),this._rows=Math.max(1,Math.round(this._h/e)),this._offsetX=(this._w-(this._cols-1)*e)/2,this._offsetY=(this._h-(this._rows-1)*e)/2,this._clip=new Float32Array(this._cols*this._rows),this._snapClip()}_scale(e=!1){const t=Math.min(window.devicePixelRatio||1,this._cfg.maxDpr);return e?Math.min(t,dr):t}_applyBacking(e){const t=this._refs,r=this._ctx;!t||!r||(t.surface.width=Math.round(this._w*e),t.surface.height=Math.round(this._h*e),t.surface.style.width=`${this._w}px`,t.surface.style.height=`${this._h}px`,r.setTransform(e,0,0,e,0,0),this._appliedScale=e)}_ensureScale(e){const t=this._scale(e);t!==this._appliedScale&&this._applyBacking(t)}_resize(){const e=this._refs;!e||!this._canDraw||(this._w=e.viewport.clientWidth,this._h=e.viewport.clientHeight,!(this._w<=0||this._h<=0)&&(this._sizeMul=this._computeSizeMul(),this._allocate(),this._ctx?this._applyBacking(this._scale()):this._appliedScale=this._scale()))}_initEpicenters(){const e=this._frameRect();this._epis.length=0;const t=this._cfg.epiSpeed*this._sizeMul;for(let r=0;r<this._cfg.epiCount;r++){const s=Math.random()*Math.PI*2;this._epis.push({x:e.left+Math.random()*(e.right-e.left),y:e.top+Math.random()*(e.bottom-e.top),vx:Math.cos(s)*t,vy:Math.sin(s)*t})}}_moveEpicenters(e){this._epis.length===0&&this._initEpicenters();const t=this._liveRect(),r=this._cfg.epiSpeed*this._sizeMul;for(const s of this._epis){const o=Math.atan2(s.vy,s.vx)+(Math.random()-.5)*this._cfg.epiWander;s.vx=Math.cos(o)*r,s.vy=Math.sin(o)*r,s.x+=s.vx*e,s.y+=s.vy*e,s.x<t.left?(s.x=t.left,s.vx=Math.abs(s.vx)):s.x>t.right&&(s.x=t.right,s.vx=-Math.abs(s.vx)),s.y<t.top?(s.y=t.top,s.vy=Math.abs(s.vy)):s.y>t.bottom&&(s.y=t.bottom,s.vy=-Math.abs(s.vy))}}_epiIntensity(e,t){let r=0;const s=this._cfg.falloffWarp,o=s>0?Math.PI*2/(this._epiRadius*.7||1):0,a=o>0?s*this._epiRadius*Math.sin(e*o+1.3)*Math.cos(t*o*.9):0,l=this._cfg.epiFalloff;for(const c of this._epis){const u=Math.max(0,Math.hypot(e-c.x,t-c.y)+a);if(u>=this._epiRadius)continue;const d=1-u/this._epiRadius;let p=d*d*(3-2*d);l!==1&&(p=p**l),p>r&&(r=p)}return r}_staticScale(){return this._cfg.idleScale}_hash(e,t){const r=Math.sin(e*12.9898+t*78.233)*43758.5453;return r-Math.floor(r)}_shimmerScale(e,t,r,s){const o=this._epiIntensity(r,s),{minScale:a,peakScale:l}=this._cfg,c=(this._hash(e,t)-.5)*this._cfg.dither*o;return a+(l-a)*o+c}_drawCover(e){var p;const t=this._ctx,r=(p=this._refs)==null?void 0:p.getImage();if(!r)return;const s=r.naturalWidth,o=r.naturalHeight;if(!s||!o)return;const a=e.right-e.left,l=e.bottom-e.top,c=Math.max(a/s,l/o),u=s*c,d=o*c;t.drawImage(r,e.left+(a-u)/2,e.top+(l-d)/2,u,d)}_setOpacity(e){const t=this._refs;if(!t)return;const r=t.getImage();e?(this._opacityManual||(t.surface.style.transition="none",t.surface.style.opacity="1",this._opacityManual=!0),r&&r!==this._hiddenImage&&(this._showHiddenImage(),r.style.transition="none",r.style.opacity="0",this._hiddenImage=r)):(this._opacityManual&&(t.surface.style.transition="",t.surface.style.opacity="",this._opacityManual=!1),this._showHiddenImage())}_showHiddenImage(){const e=this._hiddenImage;e&&(e.isConnected&&(e.style.transition="",e.style.opacity="1"),this._hiddenImage=null)}_restoreOpacity(){const e=this._refs;this._opacityManual&&e&&(e.surface.style.transition="",e.surface.style.opacity="",this._opacityManual=!1),this._showHiddenImage()}_draw(){if(this._gl){this._drawGL();return}const e=this._ctx;if(!e||this._w<=0||this._h<=0)return;const t=this._maskingImage();if(this._setOpacity(t),!(this._state.shimmering||this._state.empty||t))return;const r=t||this._state.shimmering||this._envAnimating||this._shimAnimating;this._ensureScale(r),e.clearRect(0,0,this._w,this._h);const s=this._liveRect();this._epiRadius=this._epiRadiusFor(s);const o=this._cfg.cellSize,a=o/2;e.fillStyle=t?"#000":this._dotColor;const l=typeof Path2D=="function"?new Path2D:null;let c=0;for(let u=0;u<this._rows;u++){const d=this._offsetY+u*o;for(let p=0;p<this._cols;p++,c++){const f=this._clip[c];if(f<=0)continue;const g=this._offsetX+p*o;let w;if(t){const $=this._reduceMotion?1:this._state.generating?this._shimmerScale(p,u,g,d):this._cfg.minScale,R=this._baseRadius*$;w=(a+this._env*(R-a))*f}else{let $=this._staticScale();if(!this._reduceMotion&&this._shimMix>0){const R=this._shimmerScale(p,u,g,d);$+=(R-$)*this._shimMix}w=this._baseRadius*$*f}if(w<=0)continue;const x=w*2;l?l.rect(g-w,d-w,x,x):e.fillRect(g-w,d-w,x,x)}}l&&e.fill(l),t&&(e.globalCompositeOperation="source-in",this._drawCover(s),e.globalCompositeOperation="source-over")}_drawGL(){const e=this._gl,t=this._refs;if(!e||!t||this._w<=0||this._h<=0)return;const r=this._maskingImage();if(this._setOpacity(r),!(this._state.shimmering||this._state.empty||r))return;const s=this._liveRect();if(this._epiRadius=this._epiRadiusFor(s),r){const c=t.getImage();(c!==this._glImageEl||c!==null&&c.complete&&!this._glImageReady)&&(e.setImage(c&&c.complete&&c.naturalWidth>0?c:null),this._glImageEl=c,this._glImageReady=e.hasImage)}const o=Math.min(this._epis.length,8);for(let c=0;c<o;c++)this._glEpis[c*2]=this._epis[c].x,this._glEpis[c*2+1]=this._epis[c].y;const a=this._cfg.cellSize,l={cssW:this._w,cssH:this._h,scale:this._appliedScale||this._scale(),cols:this._cols,rows:this._rows,offsetX:this._offsetX,offsetY:this._offsetY,cell:a,baseRadius:this._baseRadius,fullHalf:a/2,env:this._env,shimMix:this._shimMix,mask:r,generating:this._state.generating&&!this._reduceMotion,minScale:this._cfg.minScale,peakScale:this._cfg.peakScale,idleScale:this._cfg.idleScale,epis:this._glEpis,epiCount:o,epiRadius:this._epiRadius,epiFalloff:this._cfg.epiFalloff,falloffWarp:this._cfg.falloffWarp,dither:this._cfg.dither,color:this._dotColorRGBA,clip:this._clip,frameLeft:s.left,frameTop:s.top,frameRight:s.right,frameBottom:s.bottom};e.render(l)}_ensureLoop(){this._canDraw&&this._rafId===null&&(this._lastTime=0,this._rafId=requestAnimationFrame(this._tick))}_tryStartExit(){this._exitPending&&this._hasImage()&&(this._exitPending=!1,this._env=1,this._startEnv(0,this._cfg.exitMs))}}const mr=":host{display:block;width:100%;height:100%;container-type:inline-size}.canvas{position:relative;width:100%;height:100%;min-height:240px;overflow:hidden}.canvas__bg{position:absolute;top:0;right:0;bottom:0;left:0;background:var(--uc-ai-background)}.canvas__viewport{position:absolute;top:20px;right:20px;bottom:20px;left:20px;display:grid;place-items:center;pointer-events:none}.canvas__frame{position:relative;overflow:hidden}.canvas.is-ready .canvas__frame{transition:width .46s var(--uc-ai-ease-in-out, ease),height .46s var(--uc-ai-ease-in-out, ease)}.canvas__image{position:relative;z-index:1;width:100%;height:100%;display:block;object-fit:cover;transition:opacity .3s var(--uc-ai-ease-out, ease)}.canvas__under{position:absolute;top:0;right:0;bottom:0;left:0;z-index:0;width:100%;height:100%;display:block;object-fit:cover}.dot-grid{position:absolute;top:0;right:0;bottom:0;left:0;pointer-events:none;opacity:0;color:var(--uc-ai-dot-grid-color, color-mix(in srgb, currentColor 15%, transparent));transition:opacity .2s ease}.canvas.is-empty .dot-grid,.canvas.is-loading .dot-grid{opacity:1}.preload{position:absolute;width:1px;height:1px;opacity:0;pointer-events:none}.layer.full{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:100%;object-fit:contain;z-index:4}.fullscreen-btn{position:absolute;top:12px;right:12px;z-index:5;display:grid;place-items:center;width:var(--uc-ai-button-size, 32px);height:var(--uc-ai-button-size, 32px);padding:0;border:0;border-radius:var(--uc-ai-radius-button, 8px);background:color-mix(in oklch,var(--uc-ai-background) 75%,transparent);backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);color:var(--uc-ai-foreground);cursor:pointer;opacity:0;transition:opacity var(--uc-ai-transition, .2s ease),background var(--uc-ai-transition, .2s ease)}.fullscreen-btn svg{width:18px;height:18px}.canvas:hover .fullscreen-btn,.fullscreen-btn:focus-visible{opacity:1}.fullscreen-btn:hover{background:var(--uc-ai-background)}@media(hover:none){.fullscreen-btn{opacity:1}}.canvas:fullscreen{background:#000}.canvas:fullscreen .canvas__bg{background:#000}.error-state{position:absolute;top:0;right:0;bottom:0;left:0;display:grid;place-items:center;padding:16px;text-align:center;color:var(--uc-ai-muted-foreground);font-size:.875em;z-index:3}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(prefers-reduced-motion:reduce){.canvas__viewport,.canvas__frame,.canvas__image,.fullscreen-btn{transition:none}}";var _r=Object.defineProperty,gr=Object.getOwnPropertyDescriptor,b=(i,e,t,r)=>{for(var s=r>1?void 0:r?gr(e,t):e,o=i.length-1,a;o>=0;o--)(a=i[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&_r(e,t,s),s};const vr=3/2,br=70;let _=class extends h.LitElement{constructor(){super(...arguments),this.url=null,this.ratio=null,this.naturalRatio=null,this.busy=!1,this.alt="",this.busyLabel="",this.errorLabel="",this.fullscreenLabel="",this.exitFullscreenLabel="",this.fullsizeUrl=null,this._displayedUrl=null,this._fadingUrl=null,this._failed=!1,this._frameReady=!1,this._fullscreen=!1,this._dotGrid=new fr(this),this._switchCovering=!1,this._seenUrls=new Set,this._instantSwap=!1,this._onVisibilityChange=()=>{document.visibilityState!=="visible"||this.busy||!this._displayedUrl||(this._clearCoverTimer(),this._switchCovering=!1,this._dotGrid.settle())},this._preloadedFullsizeUrl=null,this._onFullscreenKeydown=i=>{i.key==="Escape"&&document.fullscreenElement&&(i.preventDefault(),i.stopPropagation(),document.exitFullscreen())}}connectedCallback(){super.connectedCallback(),document.addEventListener("visibilitychange",this._onVisibilityChange)}disconnectedCallback(){var i;super.disconnectedCallback(),(i=this._resizeObserver)==null||i.disconnect(),this._clearCoverTimer(),document.removeEventListener("keydown",this._onFullscreenKeydown,!0),document.removeEventListener("visibilitychange",this._onVisibilityChange)}firstUpdated(){const i=this._dotGridEl,e=this._viewportEl,t=this._frameEl;i&&e&&t&&this._dotGrid.attach({surface:i,viewport:e,frame:t,getImage:()=>this._imageEl??null}),typeof ResizeObserver=="function"&&e&&(this._resizeObserver=new ResizeObserver(()=>this._updateFrame()),this._resizeObserver.observe(e)),this._updateFrame(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this._frameReady=!0})})}willUpdate(i){i.has("shimmerConfig")&&this._dotGrid.setConfig(this.shimmerConfig),i.has("url")&&(this.url?this.url!==this._displayedUrl&&(this._failed=!1):(this._displayedUrl=null,this._failed=!1))}updated(i){const e=i.has("_displayedUrl");(i.has("ratio")||i.has("naturalRatio")||e)&&this._updateFrame(),(i.has("busy")||i.has("url")||e)&&(this._updateSwitchCover(i.has("busy")),this._syncGrid())}_syncGrid(){this._dotGrid.sync({shimmering:this.busy||this._switchCovering,empty:this._displayedUrl==null,generating:this.busy})}_updateSwitchCover(i){if(!(this.url!=null&&this.url!==this._displayedUrl&&!this._failed)){this._clearCoverTimer(),this._switchCovering=!1;return}if(this.busy){this._clearCoverTimer(),this._instantSwap=!1;return}if(i){this._clearCoverTimer(),this._instantSwap=!1,this._switchCovering=!0;return}if(this.url!=null&&this._seenUrls.has(this.url)){this._clearCoverTimer(),this._switchCovering=!1,this._instantSwap=!0;return}this._instantSwap=!1,!(this._switchCovering||this._coverTimer!=null)&&(this._coverTimer=window.setTimeout(()=>{this._coverTimer=void 0,this.url!=null&&this.url!==this._displayedUrl&&!this._failed&&!this.busy&&!this._switchCovering&&(this._switchCovering=!0,this._syncGrid())},br))}_clearCoverTimer(){this._coverTimer!=null&&(clearTimeout(this._coverTimer),this._coverTimer=void 0)}resetGrid(){this._dotGrid.reset()}_frameRatioValue(){if(this.ratio&&this.ratio>0)return this.ratio;if(this.naturalRatio&&this.naturalRatio>0)return this.naturalRatio;const i=this._imageEl;return i&&i.naturalWidth>0&&i.naturalHeight>0?i.naturalWidth/i.naturalHeight:vr}_updateFrame(){const i=this._viewportEl,e=this._frameEl;if(!i||!e)return;const t=i.clientWidth,r=i.clientHeight;if(!t||!r)return;const s=this._frameRatioValue();let o,a;t/r>s?(a=r,o=a*s):(o=t,a=o/s),e.style.width=`${Math.round(o)}px`,e.style.height=`${Math.round(a)}px`}_onLoaded(i){const e=i.currentTarget.getAttribute("src");if(!e||e!==this.url)return;const t=this._displayedUrl;this._instantSwap&&t&&t!==e&&(this._fadingUrl=t),this._displayedUrl=e,this._failed=!1,this._seenUrls.add(e)}_onDisplayedLoad(){this._fadingUrl=null,this._updateFrame(),this._dotGrid.onImageLoad()}_onError(){this._failed=!0,this.dispatchEvent(new CustomEvent("uc:image-error",{detail:{url:this.url},bubbles:!0,composed:!0}))}get _fullscreenSupported(){var i;return document.fullscreenEnabled&&typeof((i=this._canvasEl)==null?void 0:i.requestFullscreen)=="function"}_preloadFullsize(){!this.fullsizeUrl||this.fullsizeUrl===this._preloadedFullsizeUrl||(this._preloadedFullsizeUrl=this.fullsizeUrl,new Image().src=this.fullsizeUrl)}_toggleFullscreen(){var i;document.fullscreenElement?document.exitFullscreen():(i=this._canvasEl)==null||i.requestFullscreen()}_onFullscreenChange(){this._fullscreen=document.fullscreenElement!=null,this._fullscreen?document.addEventListener("keydown",this._onFullscreenKeydown,!0):document.removeEventListener("keydown",this._onFullscreenKeydown,!0)}render(){const i=this.url!=null&&this.url!==this._displayedUrl&&!this._failed,e=this._displayedUrl==null,t=!e&&!this._failed&&!this.busy&&this._fullscreenSupported,r={canvas:!0,"is-empty":e,"is-loading":this.busy,"is-ready":this._frameReady};return h.html`
282
+ <div class=${k.classMap(r)} @fullscreenchange=${this._onFullscreenChange}>
283
+ <div class="canvas__bg"></div>
284
+
285
+ <div class="canvas__viewport">
286
+ <div class="canvas__frame">
287
+ ${this._fadingUrl?h.html`<img class="canvas__under" src="${this._fadingUrl}" alt="" aria-hidden="true" crossorigin="anonymous" />`:h.nothing}
288
+ ${this._displayedUrl?h.html`<img
289
+ class="canvas__image"
290
+ src="${this._displayedUrl}"
291
+ alt="${this.alt||"AI image"}"
292
+ decoding="async"
293
+ crossorigin="anonymous"
294
+ @load=${this._onDisplayedLoad}
295
+ />`:h.nothing}
296
+ </div>
297
+ <canvas class="dot-grid" aria-hidden="true"></canvas>
298
+ </div>
299
+
300
+ ${this._fullscreen&&this.fullsizeUrl?h.html`<img class="layer full" src="${this.fullsizeUrl}" alt="${this.alt||"AI image"}" decoding="async" />`:h.nothing}
301
+ ${i?h.html`<img
302
+ class="preload"
303
+ src="${_t.ifDefined(this.url??void 0)}"
304
+ alt=""
305
+ aria-hidden="true"
306
+ decoding="async"
307
+ crossorigin="anonymous"
308
+ @load=${this._onLoaded}
309
+ @error=${this._onError}
310
+ />`:h.nothing}
311
+ ${this._failed?h.html`<div class="error-state" role="alert">${this.errorLabel||"Failed to load image"}</div>`:h.nothing}
312
+ ${t?h.html`
313
+ <button
314
+ type="button"
315
+ class="fullscreen-btn"
316
+ data-testid="fullscreen-btn"
317
+ aria-label="${this._fullscreen?this.exitFullscreenLabel:this.fullscreenLabel}"
318
+ @mouseenter=${this._preloadFullsize}
319
+ @focus=${this._preloadFullsize}
320
+ @click=${this._toggleFullscreen}
321
+ >
322
+ ${J.unsafeSVG(this._fullscreen?Di:zi)}
323
+ </button>
324
+ `:h.nothing}
325
+ <span class="sr-only" role="status" aria-live="polite">${this.busy?this.busyLabel:""}</span>
326
+ </div>
327
+ `}};_.styles=h.unsafeCSS(mr);b([n.property()],_.prototype,"url",2);b([n.property({type:Number})],_.prototype,"ratio",2);b([n.property({type:Number,attribute:"natural-ratio"})],_.prototype,"naturalRatio",2);b([n.property({type:Boolean})],_.prototype,"busy",2);b([n.property()],_.prototype,"alt",2);b([n.property({attribute:"busy-label"})],_.prototype,"busyLabel",2);b([n.property({attribute:"error-label"})],_.prototype,"errorLabel",2);b([n.property({attribute:"fullscreen-label"})],_.prototype,"fullscreenLabel",2);b([n.property({attribute:"exit-fullscreen-label"})],_.prototype,"exitFullscreenLabel",2);b([n.property({attribute:"fullsize-url"})],_.prototype,"fullsizeUrl",2);b([n.property({attribute:!1})],_.prototype,"shimmerConfig",2);b([n.state()],_.prototype,"_displayedUrl",2);b([n.state()],_.prototype,"_fadingUrl",2);b([n.state()],_.prototype,"_failed",2);b([n.state()],_.prototype,"_frameReady",2);b([n.state()],_.prototype,"_fullscreen",2);b([n.query(".canvas")],_.prototype,"_canvasEl",2);b([n.query(".canvas__viewport")],_.prototype,"_viewportEl",2);b([n.query(".canvas__frame")],_.prototype,"_frameEl",2);b([n.query(".canvas__image")],_.prototype,"_imageEl",2);b([n.query(".dot-grid")],_.prototype,"_dotGridEl",2);_=b([n.customElement("uc-ai-canvas")],_);const yr=":host{display:block;container-type:inline-size}.footer{display:flex;justify-content:space-between;align-items:center;gap:8px;padding:var(--uc-ai-padding);background:transparent}.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:var(--uc-ai-button-size);padding:0 14px;border:0;border-radius:var(--uc-ai-radius-button);font-family:inherit;font-size:14px;font-weight:500;cursor:pointer;transition:background .15s ease,filter .15s ease,transform .14s var(--uc-ai-ease-out, ease)}.btn:active{transform:scale(.97)}.btn--ghost{background:var(--uc-ai-secondary);color:var(--uc-ai-secondary-foreground)}.btn--primary{background:var(--uc-ai-primary);color:var(--uc-ai-primary-foreground)}@media(hover:hover)and (pointer:fine){.btn--ghost:hover{background:var(--uc-ai-secondary-hover)}.btn--primary:hover{background:var(--uc-ai-primary-hover)}}.btn--primary:disabled{opacity:.5;cursor:not-allowed;background:var(--uc-ai-primary)}.btn svg{width:14px;height:14px}@media(prefers-reduced-motion:reduce){.btn{transition-property:background,filter}.btn:active{transform:none}}";var wr=Object.defineProperty,xr=Object.getOwnPropertyDescriptor,ie=(i,e,t,r)=>{for(var s=r>1?void 0:r?xr(e,t):e,o=i.length-1,a;o>=0;o--)(a=i[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&wr(e,t,s),s};let N=class extends h.LitElement{constructor(){super(...arguments),this.cancelLabel="",this.primaryLabel="",this.primaryDisabled=!1}_emitCancel(){this.dispatchEvent(new CustomEvent("uc:cancel",{bubbles:!0,composed:!0}))}_emitPrimary(){this.dispatchEvent(new CustomEvent("uc:primary",{bubbles:!0,composed:!0}))}render(){return h.html`
328
+ <div class="footer">
329
+ <button type="button" class="btn btn--ghost" @click=${this._emitCancel}>
330
+ <span>${this.cancelLabel}</span>
331
+ </button>
332
+ <button
333
+ type="button"
334
+ class="btn btn--primary"
335
+ @click=${this._emitPrimary}
336
+ ?disabled=${this.primaryDisabled}
337
+ >
338
+ <span>${this.primaryLabel}</span>
339
+ </button>
340
+ </div>
341
+ `}};N.styles=h.unsafeCSS(yr);ie([n.property({attribute:"cancel-label"})],N.prototype,"cancelLabel",2);ie([n.property({attribute:"primary-label"})],N.prototype,"primaryLabel",2);ie([n.property({type:Boolean,attribute:"primary-disabled"})],N.prototype,"primaryDisabled",2);N=ie([n.customElement("uc-ai-footer")],N);const Er=":host{--uc-ai-foreground: light-dark(#181818, #e1e1e1);--uc-ai-background: light-dark(#ffffff, #1b1b1b);--uc-ai-floating: var(--uc-floating, light-dark(#ffffff, #242424));--uc-ai-floating-border: var(--uc-floating-border, light-dark(transparent, rgba(255, 255, 255, .05)));--uc-ai-muted: light-dark(#f5f5f5, #242424);--uc-ai-muted-foreground: light-dark(#717171, #989898);--uc-ai-primary: light-dark(#174bd7, #579aff);--uc-ai-primary-hover: light-dark(#1141c0, #4a8aef);--uc-ai-primary-foreground: light-dark(#ffffff, #000000);--uc-ai-primary-transparent: light-dark(rgba(23, 75, 215, .07), rgba(87, 154, 255, .07));--uc-ai-secondary: light-dark(rgba(24, 24, 24, .05), rgba(225, 225, 225, .07));--uc-ai-secondary-hover: light-dark(rgba(24, 24, 24, .08), rgba(225, 225, 225, .1));--uc-ai-secondary-foreground: light-dark(#181818, #e1e1e1);--uc-ai-border: light-dark(#e4e4e8, #3d3d3d);--uc-ai-shadow-color: light-dark(rgba(24, 24, 24, .18), rgba(0, 0, 0, .5));--uc-ai-dialog-shadow: 0 6px 20px light-dark(rgba(0, 0, 0, .1), rgba(0, 0, 0, .25));--uc-ai-composer-shadow: 0 4px 14px light-dark(rgba(0, 0, 0, .18), rgba(0, 0, 0, .34)), 0 0 26px light-dark(rgba(0, 0, 0, .2), rgba(0, 0, 0, .42));--uc-ai-composer-shadow-peek: 0 2px 10px light-dark(rgba(0, 0, 0, .16), rgba(0, 0, 0, .34));--uc-ai-composer-radius: var(--uc-ai-radius-frame);--uc-ai-composer-radius-top: var(--uc-ai-composer-radius);--uc-ai-composer-radius-bottom: var(--uc-ai-composer-radius);--uc-ai-destructive: #d8473e;--uc-ai-destructive-foreground: light-dark(#b3261e, #ff9d96);--uc-ai-radius: 8px;--uc-ai-radius-button: var(--uc-ai-radius);--uc-ai-radius-input: calc(var(--uc-ai-radius) * 1.5);--uc-ai-radius-card: calc(var(--uc-ai-radius) * 2);--uc-ai-radius-frame: calc(var(--uc-ai-radius) * 2.25);--uc-ai-padding: 10px;--uc-ai-button-size: 32px;--uc-ai-font-family: system-ui, -apple-system, sans-serif;--uc-ai-font-size: 14px;--uc-ai-transition: .2s ease;--uc-ai-ease-out: cubic-bezier(.23, 1, .32, 1);--uc-ai-ease-in-out: cubic-bezier(.77, 0, .175, 1);--uc-ai-dot-grid-color: light-dark(rgba(0, 0, 0, .21), rgba(255, 255, 255, .1));--uc-ai-prompt-max-lines: 6;--uc-ai-prompt-max-height: calc(var(--uc-ai-prompt-max-lines) * 1.5em + 10px);display:block;width:100%;height:100%;font-family:var(--uc-ai-font-family);font-size:var(--uc-ai-font-size);color:var(--uc-ai-foreground);color-scheme:light dark;container-type:inline-size}:host([hidden]){display:none}:host(.uc-light),:host-context(.uc-light){color-scheme:light}:host(.uc-dark),:host-context(.uc-dark){color-scheme:dark}.shell{display:flex;flex-direction:column;background:var(--uc-ai-background);border-radius:var(--uc-ai-radius-card);overflow:hidden;box-shadow:var(--uc-ai-dialog-shadow);height:100%}.stage{position:relative;flex:1;min-height:360px;overflow:hidden;background:var(--uc-ai-background)}uc-ai-canvas{position:absolute;top:0;right:0;bottom:0;left:0}.composer{width:700px;max-width:calc(100% - 40px)}.composer__content{display:flex;flex-direction:column;gap:14px;align-items:center}.composer--overlay{position:absolute;left:50%;transform:translate(-50%);z-index:5;transition:transform .48s var(--uc-ai-ease-out)}.composer--overlay-bottom{bottom:32px}.composer--overlay-top{top:32px}.composer--docked{margin-inline:auto;padding:14px 20px;position:relative;z-index:1}.composer--docked-bottom{padding-top:8px}.composer--docked-top{padding-bottom:8px}.history-pinned{position:absolute;left:50%;transform:translate(-50%);width:700px;max-width:calc(100% - 40px);z-index:5}.history-pinned--canvas-top{top:20px}.history-pinned--canvas-bottom{bottom:20px}.history-pinned--docked.history-pinned--canvas-top{top:6px}.history-pinned--docked.history-pinned--canvas-bottom{bottom:6px}.dock-hotzone{position:absolute;left:0;right:0;height:100px;z-index:4;pointer-events:none}.dock-hotzone--bottom{bottom:0}.dock-hotzone--top{top:0}:host([composer-auto-hide]) .stage:not(.is-empty) .dock-hotzone{pointer-events:auto}.composer-fade{position:absolute;left:0;right:0;height:26px;z-index:6;pointer-events:none;opacity:0;transition:opacity .3s var(--uc-ai-ease-out)}.composer-fade--bottom{bottom:0;background:linear-gradient(to top,var(--uc-ai-background) 0,var(--uc-ai-background) 8px,transparent)}.composer-fade--top{top:0;background:linear-gradient(to bottom,var(--uc-ai-background) 0,var(--uc-ai-background) 8px,transparent)}:host([composer-auto-hide]) .stage:not(.is-empty) .composer-fade{opacity:1}:host([composer-auto-hide]) .stage:not(.is-empty):has(.dock-hotzone:hover) .composer-fade,:host([composer-auto-hide]) .stage:not(.is-empty):has(.composer--overlay:hover) .composer-fade,:host([composer-auto-hide]) .stage:not(.is-empty):has(.composer--overlay:focus-within) .composer-fade{opacity:0}:host([composer-auto-hide]) .stage:not(.is-empty) .composer--overlay-bottom{transform:translate(-50%,calc(100% + 4px))}:host([composer-auto-hide]) .stage:not(.is-empty) .composer--overlay-top{transform:translate(-50%,calc(-100% - 4px))}:host([composer-auto-hide]) .stage:not(.is-empty):not(:has(.composer--overlay:hover)):not(:has(.composer--overlay:focus-within)):not(:has(.dock-hotzone:hover)) .composer--overlay{--uc-ai-composer-shadow: var(--uc-ai-composer-shadow-peek)}:host([composer-auto-hide]) .stage:not(.is-empty):not(:has(.composer--overlay:hover)):not(:has(.composer--overlay:focus-within)):not(:has(.dock-hotzone:hover)) .composer--overlay-bottom{--uc-ai-composer-radius-bottom: 0px}:host([composer-auto-hide]) .stage:not(.is-empty):not(:has(.composer--overlay:hover)):not(:has(.composer--overlay:focus-within)):not(:has(.dock-hotzone:hover)) .composer--overlay-top{--uc-ai-composer-radius-top: 0px}:host([composer-auto-hide]) .stage:not(.is-empty):has(.dock-hotzone--bottom:hover) .composer--overlay-bottom,:host([composer-auto-hide]) .stage:not(.is-empty):has(.composer--overlay-bottom:hover) .composer--overlay-bottom,:host([composer-auto-hide]) .stage:not(.is-empty):has(.composer--overlay-bottom:focus-within) .composer--overlay-bottom,:host([composer-auto-hide]) .stage:not(.is-empty):has(.dock-hotzone--top:hover) .composer--overlay-top,:host([composer-auto-hide]) .stage:not(.is-empty):has(.composer--overlay-top:hover) .composer--overlay-top,:host([composer-auto-hide]) .stage:not(.is-empty):has(.composer--overlay-top:focus-within) .composer--overlay-top{transform:translate(-50%)}:host([composer-auto-hide]) .stage:not(.is-empty):has(.dock-hotzone:hover) .dock-hotzone,:host([composer-auto-hide]) .stage:not(.is-empty):has(.composer--overlay:hover) .dock-hotzone,:host([composer-auto-hide]) .stage:not(.is-empty):has(.composer--overlay:focus-within) .dock-hotzone{height:320px}:host([composer-auto-hide]) .shell--has-image .composer--docked{margin-block:8px 14px;position:relative}:host([composer-auto-hide]) .shell--has-image .composer--docked .composer__content{position:relative;transition:transform .5s var(--uc-ai-ease-out)}:host([composer-auto-hide]) .shell--has-image .composer--docked .composer__content uc-ai-history{position:absolute;left:0;right:0}:host([composer-auto-hide]) .shell--has-image .composer--docked-bottom .composer__content uc-ai-history{bottom:calc(100% + 14px)}:host([composer-auto-hide]) .shell--has-image .composer--docked-top .composer__content uc-ai-history{top:calc(100% + 14px)}:host([composer-auto-hide]) .shell--has-image .composer--docked-bottom{clip-path:inset(-200px -200px 0 -200px)}:host([composer-auto-hide]) .shell--has-image .composer--docked-top{clip-path:inset(0 -200px -200px -200px)}:host([composer-auto-hide]) .shell--has-image:not(:has(.composer--docked:hover)):not(:has(.composer--docked:focus-within)) .composer--docked{--uc-ai-composer-shadow: var(--uc-ai-composer-shadow-peek)}:host([composer-auto-hide]) .shell--has-image:not(:has(.composer--docked:hover)):not(:has(.composer--docked:focus-within)) .composer--docked-bottom .composer__content{transform:translateY(calc(100% - 22px))}:host([composer-auto-hide]) .shell--has-image:not(:has(.composer--docked:hover)):not(:has(.composer--docked:focus-within)) .composer--docked-top .composer__content{transform:translateY(calc(-100% + 22px))}uc-ai-history,uc-ai-prompt-row{width:100%}.error-box{position:absolute;top:0;right:0;bottom:0;left:0;z-index:6;display:grid;place-items:center;padding:20px;pointer-events:none}.error-box__card{pointer-events:auto;max-width:75%;padding:10px 15px;background:var(--uc-ai-floating, var(--uc-ai-background));border:1px solid var(--uc-ai-floating-border, transparent);border-radius:var(--uc-ai-radius-card);box-shadow:var(--uc-ai-dialog-shadow);color:var(--uc-ai-destructive-foreground);font-size:14px;line-height:1.4;text-align:center}";var kr=Object.defineProperty,Rr=Object.getOwnPropertyDescriptor,m=(i,e,t,r)=>{for(var s=r>1?void 0:r?Rr(e,t):e,o=i.length-1,a;o>=0;o--)(a=i[o])&&(s=(r?a(e,t,s):a(s))||s);return r&&s&&kr(e,t,s),s};const Sr=["top","bottom"],Ar=["full","available"],Cr=["composer-above","composer-below","canvas-top","canvas-bottom"];exports.UcAiEnhancer=class extends h.LitElement{constructor(){super(...arguments),this.sourceUuid=null,this.pubkey="",this.aspectRatios=null,this.localeName="en",this.localeDefinitionOverride={},this.presetsOnly=!1,this.presets={},this.composerPlacement="bottom",this.canvasFit="available",this.historyPlacement="composer-above",this.composerAutoHide=!1,this.toolbarPlacement="bottom",this._prompt="",this._selectedRatio=null,this._inputUrl=null,this._gen=new gi(this),this._history=new Ui(this),this._secure=new ct(this),this._localeStrings=T,this._localeToken=0,this._lastPreviewUrl=null,this._ratioOptionsCache=new Map,this._labelForOption=e=>e.labelKey?this._l(e.labelKey):""}willUpdate(e){const t=e.has("provider")||e.has("pubkey")||e.has("baseUrl")||e.has("cdnCname")||e.has("cdnCnamePrefixed");t&&(this._provider=this.provider??(this.pubkey?new mi({publicKey:this.pubkey,baseUrl:this.baseUrl,cdnBaseUrl:this.cdnCname,cdnCnamePrefixed:this.cdnCnamePrefixed}):void 0)),e.has("secureDeliveryProxyUrlResolver")&&this._secure.setResolver(this.secureDeliveryProxyUrlResolver);const r=e.has("sourceUuid")||e.has("sourceFileInfo");if(e.has("pubkey")&&this._history.setNamespace(this.pubkey),r&&this._gen.reset(),r||e.has("pubkey")){const o=this._history.lineage(this._sourceUuid);this._gen.setHistory(o);const a=o[0];a&&a.file.uuid!==this._sourceUuid&&this._gen.setResult({url:a.url,uuid:a.file.uuid,prompt:a.prompt,mode:a.mode,file:a.file})}(t||r)&&this._resolveInputUrl(),(t||r)&&this._resolveSourceFileInfo();const s=this._mode;if(s!==this._lastMode)this._lastMode=s,this._selectedRatio=s==="edit"?z:this._defaultGenerateRatio();else if(e.has("aspectRatios")){const o=this._selectedRatio;P(o)&&!this._standardRatios().some(a=>ue(a,o))&&(this._selectedRatio=this._defaultGenerateRatio())}e.has("aspectRatios")&&this._ratioOptionsCache.clear(),(e.has("localeName")||e.has("localeDefinitionOverride"))&&this._resolveLocale()}async _resolveLocale(){var o,a;const e=this.localeName||"en",t=++this._localeToken;let r=T;if(e!=="en")try{r=await((o=Y[e])==null?void 0:o.call(Y))??T}catch{r=T}if(t!==this._localeToken)return;const s=(a=this.localeDefinitionOverride)==null?void 0:a[e];this._localeStrings=s?{...r,...s}:r}_l(e){return yi(e,this._localeStrings)}_errorMessage(){const e=this._gen.errorCode;if(e){const t=`ai-enhancer-error-${e}`,r=this._localeStrings[t]??T[t];if(r)return r}return this._l("ai-enhancer-error")}get _sourceUuid(){var e;return this.sourceUuid??((e=this.sourceFileInfo)==null?void 0:e.uuid)??null}get _currentSourceUuid(){var e;return((e=this._gen.result)==null?void 0:e.uuid)??this._sourceUuid}get _mode(){return this._currentSourceUuid?"edit":"generate"}_resolveInputUrl(){const e=this._sourceUuid,t=this._provider;if(!e||!(t!=null&&t.resolveCdnUrl)){this._inputUrl=null;return}t.resolveCdnUrl(e).then(r=>{this._sourceUuid===e&&this._provider===t&&(this._inputUrl=r,this._persistSourceEntry())})}_persistSourceEntry(){const e=this._sourceEntry;e&&this._history.recordSource({uuid:e.file.uuid,url:e.url,prompt:e.prompt,mode:e.mode,ratio:e.ratio,file:e.file})}get _effectiveSourceFileInfo(){return this.sourceFileInfo??this._fetchedFileInfo}_resolveSourceFileInfo(){if(this._fetchedFileInfo=void 0,this.sourceFileInfo)return;const e=this.sourceUuid,t=this._provider;!e||!(t!=null&&t.getFileInfo)||t.getFileInfo(e).then(r=>{this.sourceUuid===e&&this._provider===t&&!this.sourceFileInfo&&(this._fetchedFileInfo=r,this._persistSourceEntry())},()=>{})}get _displayUrl(){return this._gen.resultUrl??this._inputUrl}get _sourceEntry(){const e=this._sourceUuid,t=this._effectiveSourceFileInfo,r=this._inputUrl;return!e||!r||!t?null:{id:e,prompt:"",mode:"edit",url:r,file:t,ratio:z}}get _historyEntries(){const e=this._sourceEntry;return!e||this._gen.history.some(t=>t.file.uuid===e.file.uuid)?this._gen.history:[...this._gen.history,e]}_displayedNaturalRatio(){var t,r;const e=((t=this._gen.result)==null?void 0:t.file.imageInfo)??((r=this._effectiveSourceFileInfo)==null?void 0:r.imageInfo);return e&&e.width>0&&e.height>0?e.width/e.height:null}get _previewUrl(){const e=this._displayUrl;if(!e)return this._lastPreviewUrl=null,null;const t=this._secure.resolve(Si(e,this.clientWidth||1024));return t!=null&&(this._lastPreviewUrl=t),this._lastPreviewUrl}get _fullsizeUrl(){return this._secure.resolve(this._displayUrl)}_standardRatios(){const e=(this.aspectRatios??[]).filter(Q);return e.length>0?e:[...et]}_defaultGenerateRatio(){const e=this._standardRatios();return e.find(t=>ue(t,gt))??e[0]??null}_ratioOptions(e){const t=this._ratioOptionsCache.get(e);if(t)return t;const r=this._standardRatios().map(xt),s=e==="edit"?[{value:z,labelKey:"ai-enhancer-aspect-original"},...r]:r;return this._ratioOptionsCache.set(e,s),s}_resolveOutputFilename(){var r;const e=((r=this._effectiveSourceFileInfo)==null?void 0:r.originalFilename)||void 0,t=this.outputFilename;return typeof t=="function"?t(e,this._gen.history.length+1)||void 0:typeof t=="string"?t||void 0:e}async _resolveMetadata(){const e=this.metadata;if(typeof e!="function")return e??void 0;const t=this._effectiveSourceFileInfo;if(t)try{return await e(t)}catch{return}}async _generate(){const e=this._prompt.trim(),t=this._provider;if(!e||!t)return;const r=this._mode,s=r==="edit"?this._currentSourceUuid:null,o=await this._resolveMetadata();try{const a=await this._gen.run({provider:t,prompt:e,mode:r,aspectRatio:P(this._selectedRatio)?this._selectedRatio:void 0,ratioValue:this._selectedRatio,source:r==="edit"?this._currentSourceUuid??void 0:void 0,filename:this._resolveOutputFilename(),metadata:o});a&&(this._prompt="",this._history.record({uuid:a.uuid,source:s,url:a.url,prompt:a.prompt,mode:a.mode,ratio:this._selectedRatio,file:a.file}))}catch(a){const l={error:_i(a)};this.dispatchEvent(new CustomEvent("uc:error",{detail:l,bubbles:!0,composed:!0}))}}_onStartOver(){var e;this.sourceUuid=null,this.sourceFileInfo=void 0,this._inputUrl=null,this._fetchedFileInfo=void 0,this._prompt="",this._gen.reset(),this._gen.clearHistory(),(e=this._canvasEl)==null||e.resetGrid()}_onPromptInput(e){this._prompt=e.detail.value}_onSend(){this._generate()}_onSelectHistoryEntry(e){const{entry:t}=e.detail;this._prompt=t.prompt,this._selectedRatio=t.ratio,this._gen.setResult({url:t.url,uuid:t.file.uuid,prompt:t.prompt,mode:t.mode,file:t.file})}_onSelectAspectRatio(e){this._selectedRatio=e.detail.value}_onSelectPreset(e){if(this._prompt=e.detail.preset.prompt,this.presetsOnly){this._generate();return}queueMicrotask(()=>{var t;return(t=this._promptRow)==null?void 0:t.focusInput()})}_onPrimary(){const e=this._gen.result;if(!e)return;const t={url:e.url,uuid:e.uuid,prompt:e.prompt,mode:e.mode,aspectRatio:P(this._selectedRatio)?this._selectedRatio:void 0,file:e.file};this.dispatchEvent(new CustomEvent("uc:done",{detail:t,bubbles:!0,composed:!0}))}_onCancel(e){e.stopPropagation(),this.dispatchEvent(new CustomEvent("uc:cancel",{bubbles:!0,composed:!0}))}render(){var Ae,Ce;const e=this._mode,t=e==="edit"&&!this.sourceUuid&&!this.sourceFileInfo,r=me[e].placeholderKey,s=((Ae=this.presets)==null?void 0:Ae[e])??me[e].presets,o=this._gen.busy||!this._gen.result,a=this._ratioOptions(e),l=this._displayUrl!=null,c=P(this._selectedRatio)?this._selectedRatio[0]/this._selectedRatio[1]:null,u={stage:!0,"is-empty":!l},d=Sr.includes(this.composerPlacement)?this.composerPlacement:"bottom",f=(Ar.includes(this.canvasFit)?this.canvasFit:"available")==="full",g=!f,w=`${f?"overlay":"docked"}-${d}`,x=Cr.includes(this.historyPlacement)?this.historyPlacement:"composer-above",$=x==="composer-above"||x==="composer-below",R=(f||g&&this.composerAutoHide)&&$,q=x==="canvas-top"?"top":x==="canvas-bottom"?"bottom":d,j=this._historyEntries,ke=j.length>0||t,re=ke?h.html`
342
+ <uc-ai-history
343
+ .busy=${this._gen.busy}
344
+ .entries=${j}
345
+ .selectedUuid=${((Ce=this._gen.result)==null?void 0:Ce.uuid)??this._sourceUuid}
346
+ ?show-start-over=${t}
347
+ start-over-label="${this._l("ai-enhancer-start-over")}"
348
+ list-label="${this._l("ai-enhancer-history-title")}"
349
+ .secureResolver=${this.secureDeliveryProxyUrlResolver}
350
+ @uc:select=${this._onSelectHistoryEntry}
351
+ @uc:start-over=${this._onStartOver}
352
+ ></uc-ai-history>
353
+ `:h.nothing,ht=h.html`
354
+ <uc-ai-prompt-row
355
+ .mode=${e}
356
+ .value=${this._prompt}
357
+ .placeholder=${this._l(r)}
358
+ .busy=${this._gen.busy}
359
+ .allowCustom=${!this.presetsOnly}
360
+ send-aria-label="${this._l("ai-enhancer-generate-btn")}"
361
+ @uc:input=${this._onPromptInput}
362
+ @uc:send=${this._onSend}
363
+ >
364
+ ${s.length>0?h.html`
365
+ <uc-ai-chips
366
+ slot="chips"
367
+ .mode=${e}
368
+ .presets=${s}
369
+ .busy=${this._gen.busy}
370
+ @uc:select=${this._onSelectPreset}
371
+ ></uc-ai-chips>
372
+ `:h.nothing}
373
+ ${a.length>0?h.html`
374
+ <uc-ai-aspect-ratio
375
+ slot="aspect-ratio"
376
+ .options=${a}
377
+ .selected=${this._selectedRatio}
378
+ .busy=${this._gen.busy}
379
+ .labelFor=${this._labelForOption}
380
+ aria-label-text="${this._l("ai-enhancer-aspect-ratio-aria")}"
381
+ @uc:select=${this._onSelectAspectRatio}
382
+ ></uc-ai-aspect-ratio>
383
+ `:h.nothing}
384
+ </uc-ai-prompt-row>
385
+ `,se=h.html`
386
+ <div
387
+ class=${k.classMap({composer:!0,"composer--overlay":f,"composer--docked":g,[`composer--${w}`]:!0})}
388
+ >
389
+ <div class="composer__content">
390
+ ${R&&x==="composer-above"?re:h.nothing}
391
+ ${ht}
392
+ ${R&&x==="composer-below"?re:h.nothing}
393
+ </div>
394
+ </div>
395
+ `,ut=ke&&!R?h.html`<div
396
+ class=${k.classMap({"history-pinned":!0,"history-pinned--docked":g,[`history-pinned--canvas-${q}`]:!0})}
397
+ >
398
+ ${re}
399
+ </div>`:h.nothing,dt=this.composerAutoHide&&f?h.html`
400
+ <div class=${k.classMap({"dock-hotzone":!0,[`dock-hotzone--${d}`]:!0})}></div>
401
+ <div class=${k.classMap({"composer-fade":!0,[`composer-fade--${d}`]:!0})}></div>
402
+ `:h.nothing,Re=this.toolbarPlacement==="top",Se=h.html`
403
+ <uc-ai-footer
404
+ cancel-label="${this._l("ai-enhancer-cancel")}"
405
+ primary-label="${this._l("ai-enhancer-done-btn")}"
406
+ ?primary-disabled=${o}
407
+ @uc:cancel=${this._onCancel}
408
+ @uc:primary=${this._onPrimary}
409
+ ></uc-ai-footer>
410
+ `;return h.html`
411
+ <div
412
+ class=${k.classMap({shell:!0,"shell--has-image":l})}
413
+ role="region"
414
+ aria-label="${this._l(e==="edit"?"ai-enhancer-edit-title":"ai-enhancer-generate-title")}"
415
+ >
416
+ ${Re?Se:h.nothing}
417
+ ${g&&d==="top"?se:h.nothing}
418
+ <div class=${k.classMap(u)}>
419
+ <uc-ai-canvas
420
+ .url=${this._previewUrl}
421
+ .ratio=${c}
422
+ .naturalRatio=${this._displayedNaturalRatio()}
423
+ .fullsizeUrl=${this._fullsizeUrl}
424
+ .shimmerConfig=${this.shimmerConfig}
425
+ .busy=${this._gen.busy}
426
+ .alt=${this._prompt}
427
+ busy-label="${this._l("ai-enhancer-busy")}"
428
+ error-label="${this._l("ai-enhancer-error")}"
429
+ fullscreen-label="${this._l("ai-enhancer-fullscreen")}"
430
+ exit-fullscreen-label="${this._l("ai-enhancer-exit-fullscreen")}"
431
+ ></uc-ai-canvas>
432
+
433
+ ${dt}
434
+ ${ut}
435
+ ${f?se:h.nothing}
436
+
437
+ ${this._gen.error?h.html`<div class="error-box" role="alert">
438
+ <div class="error-box__card">${this._errorMessage()}</div>
439
+ </div>`:h.nothing}
440
+ </div>
441
+ ${g&&d==="bottom"?se:h.nothing}
442
+ ${Re?h.nothing:Se}
443
+ </div>
444
+ `}};exports.UcAiEnhancer.styles=h.unsafeCSS(Er);m([n.property({attribute:"source-uuid"})],exports.UcAiEnhancer.prototype,"sourceUuid",2);m([n.property({attribute:!1})],exports.UcAiEnhancer.prototype,"sourceFileInfo",2);m([n.property({attribute:!1})],exports.UcAiEnhancer.prototype,"outputFilename",2);m([n.property({attribute:!1})],exports.UcAiEnhancer.prototype,"metadata",2);m([n.property()],exports.UcAiEnhancer.prototype,"pubkey",2);m([n.property({attribute:!1})],exports.UcAiEnhancer.prototype,"provider",2);m([n.property({attribute:"base-url"})],exports.UcAiEnhancer.prototype,"baseUrl",2);m([n.property({attribute:"cdn-cname"})],exports.UcAiEnhancer.prototype,"cdnCname",2);m([n.property({attribute:"cdn-cname-prefixed"})],exports.UcAiEnhancer.prototype,"cdnCnamePrefixed",2);m([n.property({attribute:!1})],exports.UcAiEnhancer.prototype,"secureDeliveryProxyUrlResolver",2);m([n.property({type:Array,attribute:"aspect-ratios",converter:i=>i?Et(i):null})],exports.UcAiEnhancer.prototype,"aspectRatios",2);m([n.property({attribute:"locale-name"})],exports.UcAiEnhancer.prototype,"localeName",2);m([n.property({attribute:!1})],exports.UcAiEnhancer.prototype,"localeDefinitionOverride",2);m([n.property({type:Boolean,attribute:"presets-only"})],exports.UcAiEnhancer.prototype,"presetsOnly",2);m([n.property({attribute:!1})],exports.UcAiEnhancer.prototype,"presets",2);m([n.property({attribute:"composer-placement"})],exports.UcAiEnhancer.prototype,"composerPlacement",2);m([n.property({attribute:"canvas-fit"})],exports.UcAiEnhancer.prototype,"canvasFit",2);m([n.property({attribute:"history-placement"})],exports.UcAiEnhancer.prototype,"historyPlacement",2);m([n.property({type:Boolean,attribute:"composer-auto-hide",reflect:!0})],exports.UcAiEnhancer.prototype,"composerAutoHide",2);m([n.property({attribute:"toolbar-placement"})],exports.UcAiEnhancer.prototype,"toolbarPlacement",2);m([n.property({attribute:!1})],exports.UcAiEnhancer.prototype,"shimmerConfig",2);m([n.state()],exports.UcAiEnhancer.prototype,"_prompt",2);m([n.state()],exports.UcAiEnhancer.prototype,"_selectedRatio",2);m([n.state()],exports.UcAiEnhancer.prototype,"_inputUrl",2);m([n.state()],exports.UcAiEnhancer.prototype,"_fetchedFileInfo",2);m([n.query("uc-ai-prompt-row")],exports.UcAiEnhancer.prototype,"_promptRow",2);m([n.query("uc-ai-canvas")],exports.UcAiEnhancer.prototype,"_canvasEl",2);m([n.state()],exports.UcAiEnhancer.prototype,"_localeStrings",2);exports.UcAiEnhancer=m([n.customElement("uc-ai-enhancer")],exports.UcAiEnhancer);exports.ICON_EDIT_AI=Oi;exports.ICON_GENERATE=Fi;exports.LOCALE_LOADERS=Y;exports.POPULAR_ASPECT_RATIOS=et;exports.enLocale=T;exports.isValidAspectRatio=Q;