handler-playable-sdk 1.0.64 → 1.0.65
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.
- package/dist/{chunk-KTX6AN5P.js → chunk-VEUM4HYT.js} +4 -4
- package/dist/cli/brand-dna.mjs +1 -1
- package/dist/cli/canva-import.mjs +1 -1
- package/dist/cli/cleanup-assets.mjs +1 -1
- package/dist/cli/fix-scales.mjs +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/cli/screen-helper.mjs +1 -1
- package/dist/cli/setup-library.mjs +1 -1
- package/dist/cli/student-helper/add-logic.mjs +1 -1
- package/dist/cli/student-helper/add-object.mjs +1 -1
- package/dist/cli/student-helper/arg-parsing.mjs +1 -1
- package/dist/cli/student-helper/asset-registry.mjs +1 -1
- package/dist/cli/student-helper/bullet-system.mjs +1 -1
- package/dist/cli/student-helper/collectable-system.mjs +1 -1
- package/dist/cli/student-helper/constants.mjs +1 -1
- package/dist/cli/student-helper/drag-snap-couples.mjs +1 -1
- package/dist/cli/student-helper/endgame-screen.mjs +1 -1
- package/dist/cli/student-helper/fs-io.mjs +1 -1
- package/dist/cli/student-helper/logic-defaults.mjs +1 -1
- package/dist/cli/student-helper/print-help.mjs +1 -1
- package/dist/cli/student-helper/prompts.mjs +1 -1
- package/dist/cli/student-helper/scratch-card.mjs +1 -1
- package/dist/cli/student-helper/screen-utils.mjs +1 -1
- package/dist/cli/student-helper/snippets.mjs +1 -1
- package/dist/cli/student-helper/start-screen.mjs +1 -1
- package/dist/cli/student-helper/swerve-collect.mjs +1 -1
- package/dist/cli/student-helper/tap-destroy.mjs +1 -1
- package/dist/cli/student-helper/template-packs.mjs +1 -1
- package/dist/cli/student-helper.mjs +1 -1
- package/dist/cli/sync-screens.mjs +1 -1
- package/dist/cli/validate-assets.mjs +1 -1
- package/dist/cli/validate.mjs +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.js +1 -1
- package/dist/pixi/index.cjs +1 -1
- package/dist/pixi/index.js +1 -1
- package/dist/three/index.cjs +12 -12
- package/dist/three/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as Yt,c as en,d as Ae,e as tn}from"./chunk-I5OOVR5U.js";import{i as Xt}from"./chunk-PW2FGMCO.js";import{c as Ne,d as Wt,e as Ze,g as Fa,h as nn,j as Ba,k as Ua,n as an,o as Kt,p as st,q as Ga,r as sn,s as qa}from"./chunk-HVKF2KYL.js";import{a as Hr}from"./chunk-JXBG6UFL.js";import{Application as al}from"pixi.js";var Fe={};function Jt(r,e,t=!1){Fe[r]||(Fe[r]=[]),Fe[r].push({fn:e,once:t})}function rn(r,e){if(Fe[r]){if(!e){delete Fe[r];return}Fe[r]=Fe[r].filter(t=>t.fn!==e)}}function Zt(r,...e){let t=Fe[r];if(t)for(let i of[...t])i.fn(...e),i.once&&rn(r,i.fn)}function he(r,e){Jt(r,e,!0)}var te=null,be=[],rt=null;function Wa(r){te=r,be=[],rt!==null&&(clearTimeout(rt),rt=null)}function Ka(){var r,e,t;return{endpoint:(te==null?void 0:te.endpoint)||"",transport:(te==null?void 0:te.transport)||"beacon",batchSize:(r=te==null?void 0:te.batchSize)!=null?r:10,flushIntervalMs:(e=te==null?void 0:te.flushIntervalMs)!=null?e:300,maxQueue:(t=te==null?void 0:te.maxQueue)!=null?t:200,debug:!!(te!=null&&te.debug)}}async function Va(r,e,t,i){let n=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(r,new Blob([n],{type:"application/json"}));i&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){i&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0}),i&&console.log("[handler.telemetry] fetch",e)}catch(a){i&&console.warn("[handler.telemetry] fetch failed",a)}}function on(r,e){let t=Ka();if(e&&t.endpoint){if(be.push(r),be.length>t.maxQueue&&(be=be.slice(be.length-t.maxQueue)),be.length>=t.batchSize){Ya();return}rt===null&&(rt=window.setTimeout(()=>{rt=null,Ya()},t.flushIntervalMs))}}async function Ya(){let r=Ka();if(!r.endpoint||be.length===0)return;let e=be.splice(0,r.batchSize);await Va(r.endpoint,{events:e},r.transport,r.debug),be.length>0&&await Va(r.endpoint,{events:be.splice(0,r.batchSize)},r.transport,r.debug)}function Xa(r){return Math.max(0,Math.min(1,r))}function Nr(r){let e=String(r!=null?r:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),i=t?Number(t[1]):1.8;return n=>1+(i+1)*Math.pow(n-1,3)+i*Math.pow(n-1,2)}return t=>1-(1-t)*(1-t)}function Tt(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function Fr(r,e){let t=r==null?void 0:r[e];return typeof t=="number"?t:0}function Ja(r,e,t){try{r[e]=t}catch{}}function Br(r){let e=r==null?void 0:r.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,i=typeof e.y=="number"?e.y:1;return{x:t,y:i}}function Za(r,e){let t=r==null?void 0:r.scale;if(t)try{typeof t.set=="function"?t.set(e.x,e.y):(typeof t.x=="number"&&(t.x=e.x),typeof t.y=="number"&&(t.y=e.y))}catch{}}function Qa(r,e){let t=Br(r);if(!t)return{from:null,to:null};let i=null,n=null;return typeof e.scale=="number"?(i=e.scale,n=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(i=e.scale.x),typeof e.scale.y=="number"&&(n=e.scale.y)),typeof e.scaleX=="number"&&(i=e.scaleX),typeof e.scaleY=="number"&&(n=e.scaleY),i===null&&n===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:i!=null?i:t.x,y:n!=null?n:t.y}}}function es(){let r=new Set,e=new WeakMap,t=null,i=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),r.size>0&&i()})},n=d=>{var p;r.add(d);let u=(p=e.get(d.target))!=null?p:new Set;u.add(d),e.set(d.target,u),i()},a=d=>{r.delete(d);let u=e.get(d.target);u&&(u.delete(d),u.size===0&&e.delete(d.target))},s=d=>{d.killed||(d.killed=!0,a(d))},o=()=>{var u,p;let d=Tt();for(let g of Array.from(r)){if(g.killed||g.paused)continue;let h=d-g.startMs-g.delayMs;if(h<0)continue;let m=g.durationMs>0?h/g.durationMs:1,f=Xa(m),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(m),b-1):0;if(g.repeat>0&&m>=1){let L=m-y;f=Xa(L)}let v=g.ease(f);g.yoyo&&y%2===1&&(v=1-v);for(let L of g.props)Ja(g.target,L.key,L.from+(L.to-L.from)*v);g.scaleFrom&&g.scaleTo&&Za(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*v,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*v});try{(u=g.onUpdate)==null||u.call(g)}catch{}if(m>=b){s(g);try{(p=g.onComplete)==null||p.call(g)}catch{}}}},l=(d,u,p)=>{var L;let g=Math.max(0,(typeof u.duration=="number"?u.duration:.5)*1e3),h=Math.max(0,(typeof u.delay=="number"?u.delay:0)*1e3+((L=p==null?void 0:p.delayMsOverride)!=null?L:0)),m=Nr(u.ease),f=typeof u.repeat=="number"?Math.max(0,u.repeat|0):0,b=u.yoyo===!0,y=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let j of Object.keys(u)){if(y.has(j))continue;let _=u[j];typeof _=="number"&&v.push({key:j,from:Fr(d,j),to:_})}let S=Qa(d,u);return{target:d,startMs:Tt(),delayMs:h,durationMs:g,ease:m,props:v,scaleFrom:S.from,scaleTo:S.to,repeat:f,yoyo:b,onUpdate:typeof u.onUpdate=="function"?u.onUpdate:void 0,onComplete:typeof u.onComplete=="function"?u.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(d,u){let p=l(d,u);return n(p),{kill:()=>s(p),pause:()=>{p.paused||(p.paused=!0,p.pauseAtMs=Tt())},resume:()=>{var m;if(!p.paused)return;let g=(m=p.pauseAtMs)!=null?m:Tt(),h=Tt()-g;p.startMs+=h,p.paused=!1,p.pauseAtMs=null},isActive:()=>!p.killed&&!p.paused}},fromTo(d,u,p){return c.set(d,u),c.to(d,p)},set(d,u){if(!d||!u)return;for(let g of Object.keys(u)){let h=u[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof h=="number"&&Ja(d,g,h)}let p=Qa(d,u);p.to&&Za(d,p.to)},killTweensOf(d){let u=e.get(d);if(u)for(let p of Array.from(u))s(p)},timeline(d={}){let u=[],p=0,g=!1,h=[],m=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?p+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):p},f=y=>{u.push(y);let v=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);p=Math.max(p,y.atMs+v)},b={to(y,v,S){return f({kind:"to",target:y,vars:v,atMs:m(S)}),b},fromTo(y,v,S,L){return f({kind:"fromTo",target:y,vars:S,from:v,atMs:m(L)}),b},play(){var y,v;if(g)return b;g=!0,h=[];for(let S of u)S.kind==="fromTo"&&c.set(S.target,(y=S.from)!=null?y:{}),h.push(c.to(S.target,{...S.vars,delay:S.atMs/1e3+((v=S.vars.delay)!=null?v:0)}));return b},pause(){for(let y of h)y.pause();return b},kill(){for(let y of h)y.kill();h=[],g=!1}};return d.paused||b.play(),b}};return c}function ts(){if(typeof window=="undefined")return;let r=window;if(!r.gsap)try{r.gsap=es()}catch{}}var is={name:"handler-playable-sdk",version:"1.0.64",type:"module",description:"Handler Playable SDK v0.1 with contract-aligned surface (root sandbox, canonical event envelope).",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./pixi":{types:"./dist/pixi/index.d.ts",import:"./dist/pixi/index.js",require:"./dist/pixi/index.cjs"},"./pixi/index.css":{import:"./dist/pixi/index.css",require:"./dist/pixi/index.css"},"./three":{types:"./dist/three/index.d.ts",import:"./dist/three/index.js",require:"./dist/three/index.cjs"},"./cli":{types:"./dist/cli/index.d.ts",import:"./dist/cli/index.js",require:"./dist/cli/index.cjs"}},bin:{"handler-student-helper":"./bin/student-helper.mjs","handler-validate":"./bin/validate.mjs","handler-sync-screens":"./bin/sync-screens.mjs","handler-brand-dna":"./bin/brand-dna.mjs","handler-setup-library":"./bin/setup-library.mjs","handler-screen-helper":"./bin/screen-helper.mjs"},scripts:{prebuild:"python3 src/preview/build-css.py",build:"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --minify --external lottie-web --external jszip && npm run create-mjs-symlinks && npm run postbuild-cli && npm run obfuscate && npm run postbuild",postbuild:"python3 src/preview/copy-css-to-dist.py","postbuild-cli":"cp src/cli/*.mjs dist/cli/ && mkdir -p dist/cli/student-helper && cp src/cli/student-helper/*.mjs dist/cli/student-helper/ && chmod +x dist/cli/*.mjs dist/cli/student-helper/*.mjs && chmod +x bin/*.mjs","create-mjs-symlinks":"cd dist && ln -sf index.js index.mjs && cd pixi && ln -sf index.js index.mjs && cd ../three && ln -sf index.js index.mjs","build:dev":"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --external lottie-web --external jszip && npm run create-mjs-symlinks && npm run postbuild-cli",obfuscate:"javascript-obfuscator dist/pixi/index.js --output dist/pixi/index.js --config obfuscator.config.json && javascript-obfuscator dist/three/index.js --output dist/three/index.js --config obfuscator.config.json && javascript-obfuscator dist/cli/index.js --output dist/cli/index.js --config obfuscator.config.json && npm run obfuscate-cli","obfuscate-cli":'for file in dist/cli/*.mjs dist/cli/student-helper/*.mjs; do javascript-obfuscator "$file" --output "$file" --config obfuscator.config.json; done',lint:"eslint 'src/**/*.{ts,tsx}'",typecheck:"tsc --noEmit",prepublishOnly:"npm run build","publish:update":"node scripts/publish-and-update.cjs patch","publish:update:minor":"node scripts/publish-and-update.cjs minor","publish:update:major":"node scripts/publish-and-update.cjs major"},author:"Handler",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/HandlerAIGames/handler-playable-sdk.git"},files:["dist","bin","LICENSE","README.md"],peerDependencies:{"lottie-web":"^5.0.0","pixi.js":"^8.0.0",three:"^0.182.0"},peerDependenciesMeta:{"pixi.js":{optional:!0},three:{optional:!0},"lottie-web":{optional:!0}},devDependencies:{"@types/three":"^0.182.0",eslint:"^9.39.2","javascript-obfuscator":"^5.1.0","pixi.js":"8.8.1",three:"^0.182.0","ts-node":"^10.9.2",tsup:"^8.4.0",typescript:"^5.7.2","typescript-eslint":"^8.53.0"},dependencies:{"@google/genai":"^1.35.0","@google/generative-ai":"^0.24.1",jszip:"^3.10.1",sharp:"^0.34.5"}};var me=0,Gr=me++,ns=me++,as=me++,ss=me++,rs=me++,os=me++,ls=me++,cs=me++,ds=me++,ps=me++,us=me++,gs=me++,W=Gr;function hs(){return W===ns}function ms(){return W===as}function fs(){return W===ss}function bs(){return W===rs}function ot(){return W===os}function lt(){return W===ls}function ys(){return W===cs}function vs(){return W===ds}function ws(){return W===ps}function ln(){return W===us}function cn(){return W===gs}function xs(){let r=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(r==="mraid")try{mraid.getState(),W=ns;return}catch{}else if(r==="dapi")try{dapi.isReady(),W=as;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(W=ss)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(W=rs)}catch{}else if(e==="mintegral")window.gameReady&&(W=os);else if(e==="tapjoy")window.TJ_API&&(W=ls);else if(e==="tiktok")window.openAppStore&&(W=cs);else if(e==="smadex")try{window.smxTracking&&(W=ds)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(W=ps)}catch{}else e==="vungle"?W=us:(r==="nucleo"||e==="nucleo")&&(W=gs)}import dn from"lottie-web";var Ss=dn;typeof window!="undefined"&&(window.lottie=dn,window.__baseLottie=dn);function ie(r,e){let t=(n,a)=>a===0?n:t(a,n%a),i=t(r,e);return`${r/i}:${e/i}`}var jl=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:ie(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:ie(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:ie(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:ie(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:ie(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:ie(360,780)}],_l=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:ie(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:ie(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:ie(412,915)}],Ol=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:ie(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:ie(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:ie(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:ie(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:ie(800,1280)}],pn=[{id:"playable-portrait",label:"Playable Portrait",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"mraid-320x480",label:"MRAID 320\xD7480",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"playable",ratio:ie(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:ie(768,1024),mraidScale:.7}];var Es=[...pn],Cs=[{category:"playable",label:"Playable Ad",devices:pn}],un=pn[0];function ct(r){return Es.find(e=>e.id===r)||un}function Rl(r){return Es.filter(e=>e.category===r)}var Be=class{async updateProperty(e,t,i,n={}){var l,c,d;console.log("[PropertyUpdateManager] Updating:",e,t,i);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let s=a(e);if(!s){console.error("[PropertyUpdateManager] Config not found for:",e);return}if(Ne({objectId:e,path:t,value:i},{persist:!0}),t==="transform"||t.startsWith("transform."))console.log("[DEBUG FALLBACK] PropertyUpdateManager SKIP applyEditableObjectConfig (transform path)",t,e);else{let u=window.applyEditableObjectConfig;if(typeof u=="function"){let p=window.__editableConfig,g=(d=(c=(l=p==null?void 0:p.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:s;await u(e,g),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available")}this.triggerRefresh(e),n.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let i=t.split("."),n=e;for(let a of i)if(n&&typeof n=="object"&&a in n)n=n[a];else return;return n}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function gn(r){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let i=(a=t.target.files)==null?void 0:a[0];if(!i)return;let n=new FileReader;n.onload=async()=>{let s=n.result,o=r.category||"misc",c=`${(r.objectId||"new_asset").replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")||"new_asset"}_uploaded`;try{let u=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:o,filename:`${c}.png`,data:s,overwrite:!0})})).json();if(!(u!=null&&u.success)){alert(`Upload failed: ${(u==null?void 0:u.error)||"Unknown error"}`);return}let p=window.addAssetToRegistry;typeof p=="function"&&p(o,`${c}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch{}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),await r.onApply(u.path)}catch(d){console.error("[QuickActionsBar] Upload error:",d),alert("Upload failed. Check console.")}},n.readAsDataURL(i)},e.click()}var Qt=class{constructor(){this.updateManager=new Be}async handleAction(e,t,i){console.log("[QuickActionsBar] Action:",e,t,i);let n=window.getEditableObjectConfig;if(typeof n!="function")return;let a=n(t);if(!a)return;let s=this.updateManager.getNestedProperty(a,i);if(e==="ai-convert"||e==="upload"||e==="library"){let o=i==="ui.text"||i==="render.asset.path",l=i==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&i!=="render.asset.path"&&(i="render.asset.path"))}switch(e){case"library":this.openLibrary(t,i,s);break;case"ai-edit":this.openAIEditor(t,i,s);break;case"upload":this.openUpload(t,i);break;case"reset":await this.resetToDefault(t,i);break;case"ai-convert":this.handleAiConvert(t,i,s);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var i,n;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let s=((n=(i=t.transform)==null?void 0:i.scale)!=null?n:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",s),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",s)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let i=window.getEditableAssets;if(typeof i!="function")return;let n=i();if(!n||!n.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!n.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),n.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),n.categories&&!n.categories.includes(d)&&n.categories.push(d),n.libraryAssets&&!n.libraryAssets[d]&&(n.libraryAssets[d]=[]);let u=window.reRenderAssetLibrary;typeof u=="function"&&u()}}openLibrary(e,t,i){var a;let n=window.__debugContext;if(n){if(n.activeTab!=="library"){n.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(n.libraryPanel){let s=window.getEditableObjectConfig,o=s==null?void 0:s(e),l=(a=o==null?void 0:o.identity)==null?void 0:a.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),n.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let a=t.split(".").pop()||t;n(a,`Edit ${a} for ${e}`,i,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var s;let i=window.getEditableObjectConfig,n=i==null?void 0:i(e),a=((s=n==null?void 0:n.identity)==null?void 0:s.category)||(t.split(".")[0]==="render"?"environment":"ui");gn({objectId:e,category:a,onApply:async o=>{var g,h;let l=window.applyAssetToSlot,c=this.getFilenameFromPath(o),d=/render\.asset\.path/i.test(t)||/\.(png|jpg|jpeg|gif|webp)$/i.test(o);typeof l=="function"&&c&&d&&await l(e,c,a),await this.updateManager.updateProperty(e,t,o);let u=window.__debugContext;(h=(g=u==null?void 0:u.options)==null?void 0:g.onPropertyChange)==null||h.call(g,e,t,o);let p=window.__highlightLibrarySlot;typeof p=="function"&&setTimeout(()=>{p(e,a)},500),window.dispatchEvent(new CustomEvent("inspector:refresh"))}})}getFilenameFromPath(e){if(!e)return"";let t=e.split("?")[0].replace(/\\/g,"/");return t.split("/").pop()||t}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let i=await this.getDefaultValue(e,t);i!==void 0?(await this.updateManager.updateProperty(e,t,i),console.log("[QuickActionsBar] Reset to default value:",i)):alert("No default value found for this property.")}catch(i){console.error("[QuickActionsBar] Failed to reset to default:",i),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let i=t.split(".");if(i.length<2)return;let n=i[0],a=i.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(n):typeof s.schemas=="object"&&(o=s.schemas[n]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of a)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let s=`A single, high-quality, high-detail game UI icon/asset representing "${String(i||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",o),n(e,s,"",{objectId:e,path:o});let l=window.__debugContext;if(l){l.activeTab="ai";let c=window.__updateWorkbenchTabs;typeof c=="function"&&c()}}else console.warn("[QuickActionsBar] AI Editor not available")}};var qr=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],Vr=["environment","ui","character","system","backgrounds"],Yr=["bg","world","ui"],As={SwerveMove:{speed:5,sensitivity:1,directionMode:"dominantAxis",axis:"both",bounds:{left:-400,right:400,top:-300,bottom:300}},DragToWin:{targetId:"",successDistance:80},DragSnap:{snapTargetId:"",snapDistance:40},JoystickMove:{speed:6,bounds:{left:-400,right:400,top:-300,bottom:300}}},ei=class{constructor(){this.modal=null;this.state=null}open(e){this.state=this.createInitialState(e),this.createModal(),document.body.appendChild(this.modal),this.attachEventListeners(),this.updateStepUI()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),window.__wizardAssetPicker=null,this.modal=null,this.state=null}createInitialState(e){return{step:1,objectType:"sprite",instanceId:"",displayName:"",category:"environment",screenId:e.screenId,layer:"world",positionMode:"static",anchorPreset:"center",anchorX:.5,anchorY:.5,positionX:0,positionY:0,offsetX:0,offsetY:0,scale:.2,rotation:0,zIndex:0,assetPath:"",tint:"",alpha:1,text:"",font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",graphicsWidth:200,graphicsHeight:200,graphicsFill:"#FFFFFF",graphicsAlpha:1,interactionEnabled:!1,dragEnabled:!1,hoverEnabled:!1,clickEnabled:!1,logicId:"",logicPropsRaw:""}}createModal(){let e=document.createElement("div");e.className="wizard-modal",e.innerHTML=`
|
|
1
|
+
import{a as Yt,c as en,d as Ae,e as tn}from"./chunk-I5OOVR5U.js";import{i as Xt}from"./chunk-PW2FGMCO.js";import{c as Ne,d as Wt,e as Ze,g as Fa,h as nn,j as Ba,k as Ua,n as an,o as Kt,p as st,q as Ga,r as sn,s as qa}from"./chunk-HVKF2KYL.js";import{a as Hr}from"./chunk-JXBG6UFL.js";import{Application as al}from"pixi.js";var Fe={};function Jt(r,e,t=!1){Fe[r]||(Fe[r]=[]),Fe[r].push({fn:e,once:t})}function rn(r,e){if(Fe[r]){if(!e){delete Fe[r];return}Fe[r]=Fe[r].filter(t=>t.fn!==e)}}function Zt(r,...e){let t=Fe[r];if(t)for(let i of[...t])i.fn(...e),i.once&&rn(r,i.fn)}function he(r,e){Jt(r,e,!0)}var te=null,be=[],rt=null;function Wa(r){te=r,be=[],rt!==null&&(clearTimeout(rt),rt=null)}function Ka(){var r,e,t;return{endpoint:(te==null?void 0:te.endpoint)||"",transport:(te==null?void 0:te.transport)||"beacon",batchSize:(r=te==null?void 0:te.batchSize)!=null?r:10,flushIntervalMs:(e=te==null?void 0:te.flushIntervalMs)!=null?e:300,maxQueue:(t=te==null?void 0:te.maxQueue)!=null?t:200,debug:!!(te!=null&&te.debug)}}async function Va(r,e,t,i){let n=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(r,new Blob([n],{type:"application/json"}));i&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){i&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0}),i&&console.log("[handler.telemetry] fetch",e)}catch(a){i&&console.warn("[handler.telemetry] fetch failed",a)}}function on(r,e){let t=Ka();if(e&&t.endpoint){if(be.push(r),be.length>t.maxQueue&&(be=be.slice(be.length-t.maxQueue)),be.length>=t.batchSize){Ya();return}rt===null&&(rt=window.setTimeout(()=>{rt=null,Ya()},t.flushIntervalMs))}}async function Ya(){let r=Ka();if(!r.endpoint||be.length===0)return;let e=be.splice(0,r.batchSize);await Va(r.endpoint,{events:e},r.transport,r.debug),be.length>0&&await Va(r.endpoint,{events:be.splice(0,r.batchSize)},r.transport,r.debug)}function Xa(r){return Math.max(0,Math.min(1,r))}function Nr(r){let e=String(r!=null?r:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),i=t?Number(t[1]):1.8;return n=>1+(i+1)*Math.pow(n-1,3)+i*Math.pow(n-1,2)}return t=>1-(1-t)*(1-t)}function Tt(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function Fr(r,e){let t=r==null?void 0:r[e];return typeof t=="number"?t:0}function Ja(r,e,t){try{r[e]=t}catch{}}function Br(r){let e=r==null?void 0:r.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,i=typeof e.y=="number"?e.y:1;return{x:t,y:i}}function Za(r,e){let t=r==null?void 0:r.scale;if(t)try{typeof t.set=="function"?t.set(e.x,e.y):(typeof t.x=="number"&&(t.x=e.x),typeof t.y=="number"&&(t.y=e.y))}catch{}}function Qa(r,e){let t=Br(r);if(!t)return{from:null,to:null};let i=null,n=null;return typeof e.scale=="number"?(i=e.scale,n=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(i=e.scale.x),typeof e.scale.y=="number"&&(n=e.scale.y)),typeof e.scaleX=="number"&&(i=e.scaleX),typeof e.scaleY=="number"&&(n=e.scaleY),i===null&&n===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:i!=null?i:t.x,y:n!=null?n:t.y}}}function es(){let r=new Set,e=new WeakMap,t=null,i=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),r.size>0&&i()})},n=d=>{var p;r.add(d);let u=(p=e.get(d.target))!=null?p:new Set;u.add(d),e.set(d.target,u),i()},a=d=>{r.delete(d);let u=e.get(d.target);u&&(u.delete(d),u.size===0&&e.delete(d.target))},s=d=>{d.killed||(d.killed=!0,a(d))},o=()=>{var u,p;let d=Tt();for(let g of Array.from(r)){if(g.killed||g.paused)continue;let h=d-g.startMs-g.delayMs;if(h<0)continue;let m=g.durationMs>0?h/g.durationMs:1,f=Xa(m),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(m),b-1):0;if(g.repeat>0&&m>=1){let L=m-y;f=Xa(L)}let v=g.ease(f);g.yoyo&&y%2===1&&(v=1-v);for(let L of g.props)Ja(g.target,L.key,L.from+(L.to-L.from)*v);g.scaleFrom&&g.scaleTo&&Za(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*v,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*v});try{(u=g.onUpdate)==null||u.call(g)}catch{}if(m>=b){s(g);try{(p=g.onComplete)==null||p.call(g)}catch{}}}},l=(d,u,p)=>{var L;let g=Math.max(0,(typeof u.duration=="number"?u.duration:.5)*1e3),h=Math.max(0,(typeof u.delay=="number"?u.delay:0)*1e3+((L=p==null?void 0:p.delayMsOverride)!=null?L:0)),m=Nr(u.ease),f=typeof u.repeat=="number"?Math.max(0,u.repeat|0):0,b=u.yoyo===!0,y=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let j of Object.keys(u)){if(y.has(j))continue;let _=u[j];typeof _=="number"&&v.push({key:j,from:Fr(d,j),to:_})}let S=Qa(d,u);return{target:d,startMs:Tt(),delayMs:h,durationMs:g,ease:m,props:v,scaleFrom:S.from,scaleTo:S.to,repeat:f,yoyo:b,onUpdate:typeof u.onUpdate=="function"?u.onUpdate:void 0,onComplete:typeof u.onComplete=="function"?u.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(d,u){let p=l(d,u);return n(p),{kill:()=>s(p),pause:()=>{p.paused||(p.paused=!0,p.pauseAtMs=Tt())},resume:()=>{var m;if(!p.paused)return;let g=(m=p.pauseAtMs)!=null?m:Tt(),h=Tt()-g;p.startMs+=h,p.paused=!1,p.pauseAtMs=null},isActive:()=>!p.killed&&!p.paused}},fromTo(d,u,p){return c.set(d,u),c.to(d,p)},set(d,u){if(!d||!u)return;for(let g of Object.keys(u)){let h=u[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof h=="number"&&Ja(d,g,h)}let p=Qa(d,u);p.to&&Za(d,p.to)},killTweensOf(d){let u=e.get(d);if(u)for(let p of Array.from(u))s(p)},timeline(d={}){let u=[],p=0,g=!1,h=[],m=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?p+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):p},f=y=>{u.push(y);let v=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);p=Math.max(p,y.atMs+v)},b={to(y,v,S){return f({kind:"to",target:y,vars:v,atMs:m(S)}),b},fromTo(y,v,S,L){return f({kind:"fromTo",target:y,vars:S,from:v,atMs:m(L)}),b},play(){var y,v;if(g)return b;g=!0,h=[];for(let S of u)S.kind==="fromTo"&&c.set(S.target,(y=S.from)!=null?y:{}),h.push(c.to(S.target,{...S.vars,delay:S.atMs/1e3+((v=S.vars.delay)!=null?v:0)}));return b},pause(){for(let y of h)y.pause();return b},kill(){for(let y of h)y.kill();h=[],g=!1}};return d.paused||b.play(),b}};return c}function ts(){if(typeof window=="undefined")return;let r=window;if(!r.gsap)try{r.gsap=es()}catch{}}var is={name:"handler-playable-sdk",version:"1.0.65",type:"module",description:"Handler Playable SDK v0.1 with contract-aligned surface (root sandbox, canonical event envelope).",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./pixi":{types:"./dist/pixi/index.d.ts",import:"./dist/pixi/index.js",require:"./dist/pixi/index.cjs"},"./pixi/index.css":{import:"./dist/pixi/index.css",require:"./dist/pixi/index.css"},"./three":{types:"./dist/three/index.d.ts",import:"./dist/three/index.js",require:"./dist/three/index.cjs"},"./cli":{types:"./dist/cli/index.d.ts",import:"./dist/cli/index.js",require:"./dist/cli/index.cjs"}},bin:{"handler-student-helper":"./bin/student-helper.mjs","handler-validate":"./bin/validate.mjs","handler-sync-screens":"./bin/sync-screens.mjs","handler-brand-dna":"./bin/brand-dna.mjs","handler-setup-library":"./bin/setup-library.mjs","handler-screen-helper":"./bin/screen-helper.mjs"},scripts:{prebuild:"python3 src/preview/build-css.py",build:"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --minify --external lottie-web --external jszip && npm run create-mjs-symlinks && npm run postbuild-cli && npm run obfuscate && npm run postbuild",postbuild:"python3 src/preview/copy-css-to-dist.py","postbuild-cli":"cp src/cli/*.mjs dist/cli/ && mkdir -p dist/cli/student-helper && cp src/cli/student-helper/*.mjs dist/cli/student-helper/ && chmod +x dist/cli/*.mjs dist/cli/student-helper/*.mjs && chmod +x bin/*.mjs","create-mjs-symlinks":"cd dist && ln -sf index.js index.mjs && cd pixi && ln -sf index.js index.mjs && cd ../three && ln -sf index.js index.mjs","build:dev":"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --external lottie-web --external jszip && npm run create-mjs-symlinks && npm run postbuild-cli",obfuscate:"javascript-obfuscator dist/pixi/index.js --output dist/pixi/index.js --config obfuscator.config.json && javascript-obfuscator dist/three/index.js --output dist/three/index.js --config obfuscator.config.json && javascript-obfuscator dist/cli/index.js --output dist/cli/index.js --config obfuscator.config.json && npm run obfuscate-cli","obfuscate-cli":'for file in dist/cli/*.mjs dist/cli/student-helper/*.mjs; do javascript-obfuscator "$file" --output "$file" --config obfuscator.config.json; done',lint:"eslint 'src/**/*.{ts,tsx}'",typecheck:"tsc --noEmit",prepublishOnly:"npm run build","publish:update":"node scripts/publish-and-update.cjs patch","publish:update:minor":"node scripts/publish-and-update.cjs minor","publish:update:major":"node scripts/publish-and-update.cjs major"},author:"Handler",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/HandlerAIGames/handler-playable-sdk.git"},files:["dist","bin","LICENSE","README.md"],peerDependencies:{"lottie-web":"^5.0.0","pixi.js":"^8.0.0",three:"^0.182.0"},peerDependenciesMeta:{"pixi.js":{optional:!0},three:{optional:!0},"lottie-web":{optional:!0}},devDependencies:{"@types/three":"^0.182.0",eslint:"^9.39.2","javascript-obfuscator":"^5.1.0","pixi.js":"8.8.1",three:"^0.182.0","ts-node":"^10.9.2",tsup:"^8.4.0",typescript:"^5.7.2","typescript-eslint":"^8.53.0"},dependencies:{"@google/genai":"^1.35.0","@google/generative-ai":"^0.24.1",jszip:"^3.10.1",sharp:"^0.34.5"}};var me=0,Gr=me++,ns=me++,as=me++,ss=me++,rs=me++,os=me++,ls=me++,cs=me++,ds=me++,ps=me++,us=me++,gs=me++,W=Gr;function hs(){return W===ns}function ms(){return W===as}function fs(){return W===ss}function bs(){return W===rs}function ot(){return W===os}function lt(){return W===ls}function ys(){return W===cs}function vs(){return W===ds}function ws(){return W===ps}function ln(){return W===us}function cn(){return W===gs}function xs(){let r=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(r==="mraid")try{mraid.getState(),W=ns;return}catch{}else if(r==="dapi")try{dapi.isReady(),W=as;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(W=ss)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(W=rs)}catch{}else if(e==="mintegral")window.gameReady&&(W=os);else if(e==="tapjoy")window.TJ_API&&(W=ls);else if(e==="tiktok")window.openAppStore&&(W=cs);else if(e==="smadex")try{window.smxTracking&&(W=ds)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(W=ps)}catch{}else e==="vungle"?W=us:(r==="nucleo"||e==="nucleo")&&(W=gs)}import dn from"lottie-web";var Ss=dn;typeof window!="undefined"&&(window.lottie=dn,window.__baseLottie=dn);function ie(r,e){let t=(n,a)=>a===0?n:t(a,n%a),i=t(r,e);return`${r/i}:${e/i}`}var jl=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:ie(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:ie(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:ie(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:ie(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:ie(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:ie(360,780)}],_l=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:ie(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:ie(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:ie(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:ie(412,915)}],Ol=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:ie(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:ie(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:ie(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:ie(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:ie(800,1280)}],pn=[{id:"playable-portrait",label:"Playable Portrait",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"mraid-320x480",label:"MRAID 320\xD7480",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"playable",ratio:ie(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:ie(768,1024),mraidScale:.7}];var Es=[...pn],Cs=[{category:"playable",label:"Playable Ad",devices:pn}],un=pn[0];function ct(r){return Es.find(e=>e.id===r)||un}function Rl(r){return Es.filter(e=>e.category===r)}var Be=class{async updateProperty(e,t,i,n={}){var l,c,d;console.log("[PropertyUpdateManager] Updating:",e,t,i);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let s=a(e);if(!s){console.error("[PropertyUpdateManager] Config not found for:",e);return}if(Ne({objectId:e,path:t,value:i},{persist:!0}),t==="transform"||t.startsWith("transform."))console.log("[DEBUG FALLBACK] PropertyUpdateManager SKIP applyEditableObjectConfig (transform path)",t,e);else{let u=window.applyEditableObjectConfig;if(typeof u=="function"){let p=window.__editableConfig,g=(d=(c=(l=p==null?void 0:p.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:s;await u(e,g),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available")}this.triggerRefresh(e),n.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let i=t.split("."),n=e;for(let a of i)if(n&&typeof n=="object"&&a in n)n=n[a];else return;return n}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function gn(r){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let i=(a=t.target.files)==null?void 0:a[0];if(!i)return;let n=new FileReader;n.onload=async()=>{let s=n.result,o=r.category||"misc",c=`${(r.objectId||"new_asset").replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")||"new_asset"}_uploaded`;try{let u=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:o,filename:`${c}.png`,data:s,overwrite:!0})})).json();if(!(u!=null&&u.success)){alert(`Upload failed: ${(u==null?void 0:u.error)||"Unknown error"}`);return}let p=window.addAssetToRegistry;typeof p=="function"&&p(o,`${c}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch{}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),await r.onApply(u.path)}catch(d){console.error("[QuickActionsBar] Upload error:",d),alert("Upload failed. Check console.")}},n.readAsDataURL(i)},e.click()}var Qt=class{constructor(){this.updateManager=new Be}async handleAction(e,t,i){console.log("[QuickActionsBar] Action:",e,t,i);let n=window.getEditableObjectConfig;if(typeof n!="function")return;let a=n(t);if(!a)return;let s=this.updateManager.getNestedProperty(a,i);if(e==="ai-convert"||e==="upload"||e==="library"){let o=i==="ui.text"||i==="render.asset.path",l=i==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&i!=="render.asset.path"&&(i="render.asset.path"))}switch(e){case"library":this.openLibrary(t,i,s);break;case"ai-edit":this.openAIEditor(t,i,s);break;case"upload":this.openUpload(t,i);break;case"reset":await this.resetToDefault(t,i);break;case"ai-convert":this.handleAiConvert(t,i,s);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var i,n;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let s=((n=(i=t.transform)==null?void 0:i.scale)!=null?n:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",s),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",s)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let i=window.getEditableAssets;if(typeof i!="function")return;let n=i();if(!n||!n.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!n.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),n.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),n.categories&&!n.categories.includes(d)&&n.categories.push(d),n.libraryAssets&&!n.libraryAssets[d]&&(n.libraryAssets[d]=[]);let u=window.reRenderAssetLibrary;typeof u=="function"&&u()}}openLibrary(e,t,i){var a;let n=window.__debugContext;if(n){if(n.activeTab!=="library"){n.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(n.libraryPanel){let s=window.getEditableObjectConfig,o=s==null?void 0:s(e),l=(a=o==null?void 0:o.identity)==null?void 0:a.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),n.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let a=t.split(".").pop()||t;n(a,`Edit ${a} for ${e}`,i,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var s;let i=window.getEditableObjectConfig,n=i==null?void 0:i(e),a=((s=n==null?void 0:n.identity)==null?void 0:s.category)||(t.split(".")[0]==="render"?"environment":"ui");gn({objectId:e,category:a,onApply:async o=>{var g,h;let l=window.applyAssetToSlot,c=this.getFilenameFromPath(o),d=/render\.asset\.path/i.test(t)||/\.(png|jpg|jpeg|gif|webp)$/i.test(o);typeof l=="function"&&c&&d&&await l(e,c,a),await this.updateManager.updateProperty(e,t,o);let u=window.__debugContext;(h=(g=u==null?void 0:u.options)==null?void 0:g.onPropertyChange)==null||h.call(g,e,t,o);let p=window.__highlightLibrarySlot;typeof p=="function"&&setTimeout(()=>{p(e,a)},500),window.dispatchEvent(new CustomEvent("inspector:refresh"))}})}getFilenameFromPath(e){if(!e)return"";let t=e.split("?")[0].replace(/\\/g,"/");return t.split("/").pop()||t}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let i=await this.getDefaultValue(e,t);i!==void 0?(await this.updateManager.updateProperty(e,t,i),console.log("[QuickActionsBar] Reset to default value:",i)):alert("No default value found for this property.")}catch(i){console.error("[QuickActionsBar] Failed to reset to default:",i),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let i=t.split(".");if(i.length<2)return;let n=i[0],a=i.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(n):typeof s.schemas=="object"&&(o=s.schemas[n]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of a)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let s=`A single, high-quality, high-detail game UI icon/asset representing "${String(i||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",o),n(e,s,"",{objectId:e,path:o});let l=window.__debugContext;if(l){l.activeTab="ai";let c=window.__updateWorkbenchTabs;typeof c=="function"&&c()}}else console.warn("[QuickActionsBar] AI Editor not available")}};var qr=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],Vr=["environment","ui","character","system","backgrounds"],Yr=["bg","world","ui"],As={SwerveMove:{speed:5,sensitivity:1,directionMode:"dominantAxis",axis:"both",bounds:{left:-400,right:400,top:-300,bottom:300}},DragToWin:{targetId:"",successDistance:80},DragSnap:{snapTargetId:"",snapDistance:40},JoystickMove:{speed:6,bounds:{left:-400,right:400,top:-300,bottom:300}}},ei=class{constructor(){this.modal=null;this.state=null}open(e){this.state=this.createInitialState(e),this.createModal(),document.body.appendChild(this.modal),this.attachEventListeners(),this.updateStepUI()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),window.__wizardAssetPicker=null,this.modal=null,this.state=null}createInitialState(e){return{step:1,objectType:"sprite",instanceId:"",displayName:"",category:"environment",screenId:e.screenId,layer:"world",positionMode:"static",anchorPreset:"center",anchorX:.5,anchorY:.5,positionX:0,positionY:0,offsetX:0,offsetY:0,scale:.2,rotation:0,zIndex:0,assetPath:"",tint:"",alpha:1,text:"",font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",graphicsWidth:200,graphicsHeight:200,graphicsFill:"#FFFFFF",graphicsAlpha:1,interactionEnabled:!1,dragEnabled:!1,hoverEnabled:!1,clickEnabled:!1,logicId:"",logicPropsRaw:""}}createModal(){let e=document.createElement("div");e.className="wizard-modal",e.innerHTML=`
|
|
2
2
|
<div class="wizard-card">
|
|
3
3
|
<div class="wizard-header">
|
|
4
4
|
<div class="wizard-title">
|
|
@@ -661,7 +661,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
|
|
|
661
661
|
</div>
|
|
662
662
|
</div>
|
|
663
663
|
</div>
|
|
664
|
-
`}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let i=localStorage.getItem("scene-tools-collapsed");i!==null&&(this.isCollapsed=i==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let n=this.root.querySelector("[data-tools-collapse]");n==null||n.addEventListener("click",()=>{var E;this.isCollapsed=!this.isCollapsed,(E=this.root)==null||E.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let a=(E,M)=>{var k;let I=(k=this.root)==null?void 0:k.querySelector(`[data-status="${E}"]`);I&&I.classList.toggle("active",M)},s=this.root.querySelector("#debug-highlight-object");s==null||s.addEventListener("change",()=>{var E;(E=this.options)==null||E.onHighlightObject(!!s.checked),a("bounds",s.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var E;(E=this.options)==null||E.onHighlightAnchor(!!o.checked),a("anchor",o.checked),window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}));try{localStorage.setItem(this.getSceneStorageKey("highlight_anchor"),o.checked?"true":"false")}catch{}});let l=this.root.querySelector("#debug-nudge-enabled");l==null||l.addEventListener("change",()=>{a("nudge",l.checked)});let c=this.root.querySelector("#scene-grid-enabled"),d=this.root.querySelector("#scene-grid-gap"),u=this.root.querySelector("#scene-grid-alpha"),p=this.root.querySelector("#scene-grid-alpha-value"),g=this.root.querySelector("#scene-play-mode"),h=this.root.querySelector("[data-grid-toggle-btn]"),m=this.root.querySelector("[data-play-toggle-btn]"),f=()=>{if(!u)return .25;let E=Number(u.value),M=Number.isFinite(E)?Math.min(1,Math.max(0,E)):.25;return u.value=String(M),p&&(p.textContent=`${Math.round(M*100)}%`),M},b=(E,M,I)=>{var T,A;let k=I!==void 0?I:f();(A=(T=this.options)==null?void 0:T.onGridToggle)==null||A.call(T,E,M,k),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:E,gap:M,alpha:k}}))},y=E=>{var I,k;let M=f();(k=(I=this.options)==null?void 0:I.onGridGapChange)==null||k.call(I,E),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:E,alpha:M}}))},v=E=>{var M,I;(I=(M=this.options)==null?void 0:M.onGridAlphaChange)==null||I.call(M,E),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:L(),alpha:E}}))},S=E=>{var M,I;(I=(M=this.options)==null?void 0:M.onPlayModeChange)==null||I.call(M,E),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:E}}))},L=()=>{if(!d)return 50;let E=Number(d.value),M=Number.isFinite(E)?Math.min(200,Math.max(4,E)):50;return d.value=String(M),M},j=E=>{c&&(c.checked=E),d&&(d.disabled=!E),u&&(u.disabled=!E),h==null||h.classList.toggle("active",E)},_=E=>{g&&(g.checked=E),m==null||m.classList.toggle("active",E)};try{let E=localStorage.getItem(this.getSceneStorageKey("grid_enabled")),M=localStorage.getItem(this.getSceneStorageKey("grid_gap")),I=localStorage.getItem(this.getSceneStorageKey("grid_alpha")),k=localStorage.getItem(this.getSceneStorageKey("highlight_anchor")),T=E?E==="true":!1;j(T),d&&(d.value=M||"50",d.disabled=!T),u&&(u.value=I||"0.25",u.disabled=!T,f()),o&&(o.checked=k==="true",a("anchor",o.checked));let A=!0;_(A);try{localStorage.setItem(this.getSceneStorageKey("play_mode"),A?"true":"false")}catch{}b(T,L(),f()),S(A),o&&window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}))}catch{}c==null||c.addEventListener("change",()=>{let E=L(),M=f();d&&(d.disabled=!c.checked),u&&(u.disabled=!c.checked),h==null||h.classList.toggle("active",c.checked);try{localStorage.setItem(this.getSceneStorageKey("grid_enabled"),c.checked?"true":"false"),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(M))}catch{}b(c.checked,E,M)}),d==null||d.addEventListener("input",()=>{let E=L(),M=f();try{localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(M))}catch{}y(E)}),u==null||u.addEventListener("input",()=>{let E=f(),M=L();try{localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(M))}catch{}v(E)}),g==null||g.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("play_mode"),g.checked?"true":"false")}catch{}m==null||m.classList.toggle("active",g.checked),S(g.checked)}),h==null||h.addEventListener("click",()=>{c&&(c.checked=!c.checked,c.dispatchEvent(new Event("change")))}),m==null||m.addEventListener("click",()=>{g&&(g.checked=!g.checked,g.dispatchEvent(new Event("change")))})}updateInfo(e){}};var si=class{constructor(){this.root=null;this.options=null}render(){return`
|
|
664
|
+
`}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let i=localStorage.getItem("scene-tools-collapsed");i!==null&&(this.isCollapsed=i==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let n=this.root.querySelector("[data-tools-collapse]");n==null||n.addEventListener("click",()=>{var E;this.isCollapsed=!this.isCollapsed,(E=this.root)==null||E.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let a=(E,M)=>{var k;let I=(k=this.root)==null?void 0:k.querySelector(`[data-status="${E}"]`);I&&I.classList.toggle("active",M)},s=this.root.querySelector("#debug-highlight-object");s==null||s.addEventListener("change",()=>{var E;(E=this.options)==null||E.onHighlightObject(!!s.checked),a("bounds",s.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var E;(E=this.options)==null||E.onHighlightAnchor(!!o.checked),a("anchor",o.checked),window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}));try{localStorage.setItem(this.getSceneStorageKey("highlight_anchor"),o.checked?"true":"false")}catch{}});let l=this.root.querySelector("#debug-nudge-enabled");l==null||l.addEventListener("change",()=>{a("nudge",l.checked)});let c=this.root.querySelector("#scene-grid-enabled"),d=this.root.querySelector("#scene-grid-gap"),u=this.root.querySelector("#scene-grid-alpha"),p=this.root.querySelector("#scene-grid-alpha-value"),g=this.root.querySelector("#scene-play-mode"),h=this.root.querySelector("[data-grid-toggle-btn]"),m=this.root.querySelector("[data-play-toggle-btn]"),f=()=>{if(!u)return .25;let E=Number(u.value),M=Number.isFinite(E)?Math.min(1,Math.max(0,E)):.25;return u.value=String(M),p&&(p.textContent=`${Math.round(M*100)}%`),M},b=(E,M,I)=>{var T,A;let k=I!==void 0?I:f();(A=(T=this.options)==null?void 0:T.onGridToggle)==null||A.call(T,E,M,k),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:E,gap:M,alpha:k}}))},y=E=>{var I,k;let M=f();(k=(I=this.options)==null?void 0:I.onGridGapChange)==null||k.call(I,E),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:E,alpha:M}}))},v=E=>{var M,I;(I=(M=this.options)==null?void 0:M.onGridAlphaChange)==null||I.call(M,E),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:L(),alpha:E}}))},S=E=>{var M,I;(I=(M=this.options)==null?void 0:M.onPlayModeChange)==null||I.call(M,E),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:E}}))},L=()=>{if(!d)return 50;let E=Number(d.value),M=Number.isFinite(E)?Math.min(200,Math.max(4,E)):50;return d.value=String(M),M},j=E=>{c&&(c.checked=E),d&&(d.disabled=!E),u&&(u.disabled=!E),h==null||h.classList.toggle("active",E)},_=E=>{g&&(g.checked=E),m==null||m.classList.toggle("active",E)};try{let E=localStorage.getItem(this.getSceneStorageKey("grid_enabled")),M=localStorage.getItem(this.getSceneStorageKey("grid_gap")),I=localStorage.getItem(this.getSceneStorageKey("grid_alpha")),k=localStorage.getItem(this.getSceneStorageKey("highlight_anchor")),T=E?E==="true":!1;j(T),d&&(d.value=M||"50",d.disabled=!T),u&&(u.value=I||"0.25",u.disabled=!T,f()),o&&(o.checked=k==="true",a("anchor",o.checked));let A=!0;_(A),g&&(g.disabled=!0),m&&(m.disabled=!0);try{localStorage.setItem(this.getSceneStorageKey("play_mode"),A?"true":"false")}catch{}b(T,L(),f()),S(A),o&&window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}))}catch{}c==null||c.addEventListener("change",()=>{let E=L(),M=f();d&&(d.disabled=!c.checked),u&&(u.disabled=!c.checked),h==null||h.classList.toggle("active",c.checked);try{localStorage.setItem(this.getSceneStorageKey("grid_enabled"),c.checked?"true":"false"),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(M))}catch{}b(c.checked,E,M)}),d==null||d.addEventListener("input",()=>{let E=L(),M=f();try{localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(M))}catch{}y(E)}),u==null||u.addEventListener("input",()=>{let E=f(),M=L();try{localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(M))}catch{}v(E)}),g==null||g.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("play_mode"),g.checked?"true":"false")}catch{}m==null||m.classList.toggle("active",g.checked),S(g.checked)}),h==null||h.addEventListener("click",()=>{c&&(c.checked=!c.checked,c.dispatchEvent(new Event("change")))}),m==null||m.addEventListener("click",()=>{g&&(g.checked=!g.checked,g.dispatchEvent(new Event("change")))})}updateInfo(e){}};var si=class{constructor(){this.root=null;this.options=null}render(){return`
|
|
665
665
|
<div class="nudge-panel hidden" data-panel="nudge-panel">
|
|
666
666
|
<div class="nudge-panel-header" data-panel-handle>
|
|
667
667
|
<span class="nudge-panel-title">Nudge Controls</span>
|
|
@@ -2251,7 +2251,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
2251
2251
|
<button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
|
|
2252
2252
|
</div>
|
|
2253
2253
|
</div>
|
|
2254
|
-
`,this.modal=e,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var i;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(i=this.options)!=null&&i.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,i=this.cropX+this.cropWidth/2,n=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,i-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,n-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let e=this.panX,t=this.panY,i=this.cropWidth*this.scale,n=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,i,n),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,i,n),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+i-a,t],[e,t+n-a],[e+i-a,t+n-a]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,a,a)})}updatePreview(){if(!this.modal||!this.image)return;let e=this.modal.querySelector(".asset-crop-preview-canvas");if(!e)return;let t=e.getContext("2d");if(!t)return;let i=150;e.width=i,e.height=i;let n=i/this.cropWidth,a=i/this.cropHeight,s=Math.min(n,a),o=this.cropWidth*s,l=this.cropHeight*s,c=(i-o)/2,d=(i-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,d,o,l)}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let e=this.modal.querySelector(".asset-crop-zoom-slider");e==null||e.addEventListener("input",i=>{let n=parseFloat(i.target.value);this.setZoom(n)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",i=>{let n=i.target.value;this.setAspectRatio(n)}),this.modal.addEventListener("click",i=>{switch(i.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",i=>{i.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,i=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,i=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var n;if(!this.image||!((n=this.options)!=null&&n.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let i=e.toDataURL("image/png");this.options.onCrop(i),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(r){new Gn().open(r)};import{Application as $o,Container as Ye,Graphics as xe,Point as Q,Rectangle as hr,Text as Ho,TextStyle as No}from"pixi.js";import{Sprite as Ro,Container as gr}from"pixi.js";var zo=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",qn=zo;if(typeof window!="undefined")try{let r=new XMLHttpRequest;if(r.open("GET","./build-settings.json",!1),r.send(),r.status===200&&r.responseText){let e=JSON.parse(r.responseText);e!=null&&e.buildMode&&(qn=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${qn}`))}}catch{}function Do(r){var t,i,n,a,s;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(r);let e={center:{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};if(Array.isArray(r))return{x:(t=r[0])!=null?t:.5,y:(i=r[1])!=null?i:.5};if(r&&typeof r=="object"&&"x"in r&&"y"in r)return{x:(n=r.x)!=null?n:.5,y:(a=r.y)!=null?a:.5};if(typeof r=="string"){let o=r.trim().toLowerCase();return(s=e[o])!=null?s:{x:.5,y:.5}}return null}var Te=class{static async create(e,t,i){var l,c,d,u,p,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${qn}`);let n=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!n){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let m=new gr;return this.applyTransform(m,t==null?void 0:t.transform,t),m}let a=(c=t==null?void 0:t.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${e}, configId: ${a}, type: ${n.type}, path: ${n.path}`);let s=await en.load(e,n,i,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(d=s==null?void 0:s.constructor)==null?void 0:d.name}`);let o;if(n.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",e),o=new Ro(s),console.log("[ObjectFactory] Created object:",o,"type:",(u=o==null?void 0:o.constructor)==null?void 0:u.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(n.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(p=s==null?void 0:s.constructor)==null?void 0:p.name,s),s&&(((g=s.constructor)==null?void 0:g.name)==="Container"||s instanceof gr)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let m=[n.path,`/assets/${n.path}`,`assets/${n.path}`,`../assets/${n.path}`],f=!1;for(let b of m)try{let y=await fetch(b);if(y.ok){o=await y.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(h=o==null?void 0:o.constructor)==null?void 0:h.name),f=!0;break}}catch{continue}f||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=s)}else o=s;else o=s,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,i){var n,a,s,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(n=t.position.x)!=null?n:0,e.y=(a=t.position.y)!=null?a:0):"position"in e&&e.position&&e.position.set((s=t.position.x)!=null?s:0,(o=t.position.y)!=null?o:0)),t.scale!==void 0&&"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(t.scale):e.scale=t.scale),t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor)){let l=Do(t.anchor);l&&("set"in e.anchor?e.anchor.set(l.x,l.y):(e.anchor.x=l.x,e.anchor.y=l.y))}}};var Ui=class{constructor(e){this.app=null;this.camera=new Ye;this.mainContainer=new Ye;this.uiContainer=new Ye;this.gizmoLayer=new Ye;this.screenFrame=new xe;this.gameFrame=new xe;this.gridLayer=new xe;this.spawnPointLayer=new Ye;this.objectMap=new Map;this.selectedId=null;this.dragMode=null;this.dragStartPointer=null;this.dragStartPos=null;this.dragStartScale=1;this.dragStartRotation=0;this.dragStartAngle=0;this.dragStartDistance=1;this.dragAnchorLocal=null;this.dragStartValue=null;this.dragContainer=null;this.spawnPointDrag=null;this.lastGameFrameSize=null;this.cameraScale=1;this.isPanning=!1;this.panStart=null;this.panStartCamera=null;this.hasUserCamera=!1;this.resizeObserver=null;this.screenSyncRaf=null;this.gizmoOutline=new xe;this.anchorVisualizationLayer=new xe;this.moveHandle=new xe;this.scaleHandle=new xe;this.rotateHandle=new xe;this.isVisible=!0;this.applyQueued=!1;this.applyQueuedId=null;this.gridEnabled=!1;this.gridGap=50;this.gridAlpha=.25;this.lastPickPoint=null;this.lastPickIds=[];this.lastPickIndex=0;this.lastPickTime=0;this.playModeEnabled=!0;this.playModeInitialized=!1;this.layoutScale=1;this.handleScreenChange=e=>{if(!(e!=null&&e.detail))return;let{width:t,height:i}=e.detail;!t||!i||(this.hasUserCamera=!1,this.updateLayout({width:t,height:i}),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid(),this.playModeEnabled?this.schedulePostScreenSync({width:t,height:i}):this.syncFromConfig())};this.handleActiveScreenChanged=()=>{this.isVisible&&this.syncFromConfig()};this.handleConfigChanged=e=>{if(!this.isVisible)return;this.updateLayout(),this.updateGrid();let t=e==null?void 0:e.detail;if(!t){this.syncFromConfig();return}let i=t.objectId,n=t.objectIds;if(i){this.syncFromConfig([i]);return}if(Array.isArray(n)&&n.length>0){this.syncFromConfig(n);return}this.syncFromConfig()};this.handleSceneRefresh=()=>{this.isVisible&&this.syncFromConfig()};this.handleAssetUpdated=e=>{var l;let t=(l=e==null?void 0:e.detail)!=null?l:{},i=t.objectId,n=t.texture;if(!i||!n)return;let a=this.objectMap.get(i);if(!a)return;let s=a.displayObject;if(s!=null&&s.texture)s.texture=n;else if(s!=null&&s.children){let c=s.children.find(d=>d==null?void 0:d.texture);c&&(c.texture=n)}let o=this.getEditableObjectConfig(i);o&&(a.assetKey=this.getAssetKey(o))};this.handleLayoutApplied=e=>{var s;if(!this.isVisible)return;let t=(s=e==null?void 0:e.detail)!=null?s:{},i=Number(t.width),n=Number(t.height),a=Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:this.getScreen();this.updateLayout(a),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.playModeEnabled&&this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid()})};this.handlePreviewSelect=e=>{var i,n;let t=(n=(i=e==null?void 0:e.detail)==null?void 0:i.objectId)!=null?n:null;this.setSelected(t,{silent:!0})};this.onStagePointerDown=e=>{if(!this.app||!this.isVisible||this.getPointerButton(e)!==0||this.isGizmoTarget(e==null?void 0:e.target))return;let i=this.getEventGlobalPoint(e);if(!i)return;let n=new Q(i.x,i.y),a=this.getPickCandidates(n);if(a.length===0){this.setSelected(null),this.lastPickIds=[],this.lastPickIndex=0,this.lastPickPoint=n,this.lastPickTime=performance.now();return}let s=performance.now(),o=this.areSameIds(a,this.lastPickIds),l=this.lastPickPoint&&this.distance(n,this.lastPickPoint)<=6,c=s-this.lastPickTime<1200,d=o&&l&&c?(this.lastPickIndex+1)%a.length:0,u=a[d];this.lastPickIds=a,this.lastPickIndex=d,this.lastPickPoint=n,this.lastPickTime=s,this.setSelected(u)};this.handleGridSettings=e=>{var a,s,o;let t=(a=e==null?void 0:e.detail)==null?void 0:a.enabled,i=(s=e==null?void 0:e.detail)==null?void 0:s.gap,n=(o=e==null?void 0:e.detail)==null?void 0:o.alpha;typeof t=="boolean"&&(this.gridEnabled=t),typeof i=="number"&&Number.isFinite(i)&&i>2&&(this.gridGap=i),typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=1&&(this.gridAlpha=n),this.updateGrid()};this.handlePlayModeChange=e=>{var i;let t=(i=e==null?void 0:e.detail)==null?void 0:i.enabled;typeof t=="boolean"&&(!this.playModeInitialized&&(this.playModeInitialized=!0,!t)||this.applyPlayModeState(t))};this.syncFromGameObjects=()=>{this.syncFromGameObjectsInternal()};this.onSpawnPointDragMove=e=>{if(!this.spawnPointDrag)return;let t=this.getPointerInContainer(e.clientX,e.clientY,this.mainContainer);if(!t)return;let i=t.x+this.spawnPointDrag.offset.x,n=t.y+this.spawnPointDrag.offset.y;this.updateLiveSpawnPoint(this.spawnPointDrag.objectId,this.spawnPointDrag.index,i,n)};this.onSpawnPointDragEnd=()=>{if(!this.spawnPointDrag)return;let{objectId:e,startPoints:t}=this.spawnPointDrag,i=this.getEditableObjectConfig(e),n=i?this.getSpawnPoints(i):null;i&&n&&(this.setNestedValue(i,"logic.props.spawnPoints",t),Ne({objectId:e,path:"logic.props.spawnPoints",value:n},{persist:!0,emitEvent:!0,trackHistory:!0}),this.queueLiveApply(e)),this.spawnPointDrag=null,window.dispatchEvent(new CustomEvent("inspector:refresh")),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd)};this.onDragMove=e=>{var n;if(this.playModeEnabled||!this.dragMode||!this.selectedId||!this.dragContainer||!this.dragStartPointer||!this.dragStartPos)return;let t=this.objectMap.get(this.selectedId);if(!(t!=null&&t.displayObject))return;let i=this.getPointerInContainer(e.clientX,e.clientY,this.dragContainer);if(i){if(this.dragMode==="move"){let a=i.x-this.dragStartPointer.x,s=i.y-this.dragStartPointer.y,o=this.dragStartPos.x+a,l=this.dragStartPos.y+s;t.displayObject.position.set(o,l),this.updateLiveConfigPosition(o,l)}if(this.dragMode==="scale"&&this.dragAnchorLocal){let s=Math.max(1,this.distance(i,this.dragAnchorLocal))/Math.max(1,this.dragStartDistance),o=Math.max(.01,this.dragStartScale*s);(n=t.displayObject.scale)!=null&&n.set?t.displayObject.scale.set(o,o):t.displayObject.scale&&(t.displayObject.scale.x=o,t.displayObject.scale.y=o),this.updateLiveConfigScale(o)}if(this.dragMode==="rotate"&&this.dragAnchorLocal){let a=Math.atan2(i.y-this.dragAnchorLocal.y,i.x-this.dragAnchorLocal.x),s=this.dragStartRotation+(a-this.dragStartAngle);t.displayObject.rotation=s,this.updateLiveConfigRotation(s)}this.queueLiveApply(this.selectedId),this.updateGizmos()}};this.onDragEnd=()=>{var e;if(this.dragMode){if(!this.playModeEnabled&&this.selectedId&&this.dragMode){let t=this.getEditableObjectConfig(this.selectedId),i=(e=t==null?void 0:t.transform)!=null?e:{};this.dragMode==="move"?this.applyFinalOverride(this.selectedId,"transform.position",i.position,this.dragStartValue):this.dragMode==="scale"?this.applyFinalOverride(this.selectedId,"transform.scale",i.scale,this.dragStartValue):this.dragMode==="rotate"&&this.applyFinalOverride(this.selectedId,"transform.rotation",i.rotation,this.dragStartValue)}this.dragMode=null,this.dragStartPointer=null,this.dragStartPos=null,this.dragAnchorLocal=null,this.dragStartValue=null,this.dragContainer=null,window.removeEventListener("pointermove",this.onDragMove),window.removeEventListener("pointerup",this.onDragEnd)}};this.onWheel=e=>{if(!this.app||!this.isVisible)return;e.preventDefault();let i=Math.sign(e.deltaY)<0?1.1:.9,n=Math.min(6,Math.max(.1,this.cameraScale*i)),a=new Q(this.app.renderer.width/2,this.app.renderer.height/2),s=this.camera.toLocal(a);this.cameraScale=n,this.camera.scale.set(n);let o=this.camera.toGlobal(s);this.camera.position.set(this.camera.position.x+(a.x-o.x),this.camera.position.y+(a.y-o.y)),this.hasUserCamera=!0,this.updateGizmos(),this.updateGrid()};this.onPanStart=e=>{e.button===2&&(this.isPanning=!0,this.panStart={x:e.clientX,y:e.clientY},this.panStartCamera={x:this.camera.position.x,y:this.camera.position.y},this.hasUserCamera=!0)};this.onPanMove=e=>{if(!this.isPanning||!this.panStart||!this.panStartCamera)return;let t=e.clientX-this.panStart.x,i=e.clientY-this.panStart.y;this.camera.position.set(this.panStartCamera.x+t,this.panStartCamera.y+i),this.updateGrid()};this.onPanEnd=()=>{this.isPanning=!1,this.panStart=null,this.panStartCamera=null};this.root=e.root,this.getScreen=e.getScreen}async mount(){this.app||(this.app=new $o,await this.app.init({resizeTo:this.root,autoDensity:!0,resolution:window.devicePixelRatio||1,antialias:!0,backgroundAlpha:0}),this.root.innerHTML="",this.root.appendChild(this.app.canvas),this.root.style.position="relative",this.root.style.overflow="hidden",this.app.stage.sortableChildren=!0,this.app.stage.eventMode="static",this.camera.sortableChildren=!0,this.mainContainer.sortableChildren=!0,this.uiContainer.sortableChildren=!0,this.spawnPointLayer.sortableChildren=!0,this.gizmoLayer.sortableChildren=!0,this.app.stage.addChild(this.camera),this.camera.addChild(this.screenFrame),this.camera.addChild(this.mainContainer),this.camera.addChild(this.gridLayer),this.camera.addChild(this.uiContainer),this.camera.addChild(this.spawnPointLayer),this.camera.addChild(this.gameFrame),this.camera.addChild(this.gizmoLayer),this.screenFrame.zIndex=-1,this.screenFrame.eventMode="none",this.mainContainer.zIndex=0,this.gridLayer.zIndex=2e4,this.gridLayer.eventMode="none",this.gridLayer.visible=!0,this.uiContainer.zIndex=5e4,this.spawnPointLayer.zIndex=8e4,this.spawnPointLayer.eventMode="passive",this.gameFrame.zIndex=85e3,this.gameFrame.eventMode="none",this.gizmoLayer.zIndex=1e5,this.gizmoLayer.addChild(this.gizmoOutline),this.gizmoLayer.addChild(this.anchorVisualizationLayer),this.gizmoLayer.addChild(this.moveHandle),this.gizmoLayer.addChild(this.scaleHandle),this.gizmoLayer.addChild(this.rotateHandle),this.gizmoOutline.eventMode="none",this.anchorVisualizationLayer.eventMode="none",this.setupInteractions(),this.setupObservers(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.restoreScenePreferences(),this.refresh(),this.applyPlayModeState(!0),!this.isVisible&&this.app.ticker&&this.app.ticker.stop())}destroy(){var e;this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.screenSyncRaf&&(cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=null),window.removeEventListener("handler-preview:screen",this.handleScreenChange),window.removeEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.removeEventListener("config:changed",this.handleConfigChanged),window.removeEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.removeEventListener("handler:layout-applied",this.handleLayoutApplied),window.removeEventListener("preview:select",this.handlePreviewSelect),window.removeEventListener("scene-editor:grid",this.handleGridSettings),window.removeEventListener("scene-editor:asset-updated",this.handleAssetUpdated),window.removeEventListener("scene-editor:play-mode",this.handlePlayModeChange),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd),this.app&&((e=this.app.ticker)==null||e.remove(this.syncFromGameObjects),this.app.stage.off("pointerdown",this.onStagePointerDown),this.app.destroy(!0),this.app=null)}setVisible(e){this.isVisible=e,!(!this.app||!this.app.ticker)&&(e?(this.app.ticker.start(),this.refresh(),this.updateGrid()):this.app.ticker.stop())}refresh(){this.syncFromConfig()}setupObservers(){window.addEventListener("handler-preview:screen",this.handleScreenChange),window.addEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.addEventListener("config:changed",this.handleConfigChanged),window.addEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.addEventListener("handler:layout-applied",this.handleLayoutApplied),window.addEventListener("preview:select",this.handlePreviewSelect),window.addEventListener("scene-editor:grid",this.handleGridSettings),window.addEventListener("scene-editor:asset-updated",this.handleAssetUpdated),window.addEventListener("scene-editor:play-mode",this.handlePlayModeChange),this.resizeObserver=new ResizeObserver(()=>{this.handleResize()}),this.resizeObserver.observe(this.root)}setupInteractions(){if(!this.app)return;let e=this.app.canvas;e.addEventListener("contextmenu",t=>t.preventDefault()),e.addEventListener("wheel",this.onWheel,{passive:!1}),e.addEventListener("pointerdown",this.onPanStart),window.addEventListener("pointermove",this.onPanMove),window.addEventListener("pointerup",this.onPanEnd),this.app.stage.on("pointerdown",this.onStagePointerDown),this.moveHandle.on("pointerdown",t=>this.startDrag("move",t)),this.scaleHandle.on("pointerdown",t=>this.startDrag("scale",t)),this.rotateHandle.on("pointerdown",t=>this.startDrag("rotate",t)),this.applyEditControls()}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}getPickCandidates(e){var i;let t=[];for(let[n,a]of this.objectMap.entries()){let s=a.displayObject;if(!s||s.visible===!1)continue;let o=(i=s.getBounds)==null?void 0:i.call(s);if(!o||o.width<=0||o.height<=0||e.x<o.x||e.x>o.x+o.width||e.y<o.y||e.y>o.y+o.height)continue;let l=s.parent,c=typeof(l==null?void 0:l.zIndex)=="number"?l.zIndex:0,d=typeof s.zIndex=="number"?s.zIndex:0,u=typeof(l==null?void 0:l.getChildIndex)=="function"?l.getChildIndex(s):0,p=c*1e6+d*1e3+u;t.push({id:n,order:p})}return t.sort((n,a)=>a.order-n.order),t.map(n=>n.id)}areSameIds(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}isGizmoTarget(e){return e&&this.spawnPointLayer.children.indexOf(e)!==-1?!0:e===this.moveHandle||e===this.scaleHandle||e===this.rotateHandle||e===this.gizmoOutline}restoreScenePreferences(){if(typeof window!="undefined"){try{let e=window.localStorage.getItem(this.getSceneStorageKey("grid_enabled")),t=window.localStorage.getItem(this.getSceneStorageKey("grid_gap")),i=window.localStorage.getItem(this.getSceneStorageKey("grid_alpha"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let n=Number(t);Number.isFinite(n)&&n>2&&(this.gridGap=n)}if(i!==null){let n=Number(i);Number.isFinite(n)&&n>=0&&n<=1&&(this.gridAlpha=n)}}catch{}this.updateGrid()}}getSceneStorageKey(e){let t=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${e}::${t}`}applyPlayModeState(e){var t;this.playModeEnabled=e,(t=this.app)!=null&&t.ticker&&(this.app.ticker.remove(this.syncFromGameObjects),e&&this.app.ticker.add(this.syncFromGameObjects)),this.applyEditControls(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.playModeEnabled&&this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid()})}applyEditControls(){let e=!this.playModeEnabled;this.moveHandle.eventMode=e?"static":"none",this.scaleHandle.eventMode=e?"static":"none",this.rotateHandle.eventMode=e?"static":"none"}schedulePostScreenSync(e){this.screenSyncRaf&&cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=requestAnimationFrame(()=>{this.runPostScreenSync(e)})}async runPostScreenSync(e){this.screenSyncRaf=null,this.isVisible&&this.playModeEnabled&&(this.updateLayout(e),this.hasUserCamera||this.centerCamera(),await this.syncFromConfig(),this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid())}getRuntimeScreenSize(){var a,s,o,l,c,d,u;let e=window.gameApp;if(e!=null&&e.renderer){let p=e.renderer.screen,g=Number((a=p==null?void 0:p.width)!=null?a:0),h=Number((s=p==null?void 0:p.height)!=null?s:0);if(Number.isFinite(g)&&g>0&&Number.isFinite(h)&&h>0)return{width:g,height:h};let m=Number((o=e.renderer.resolution)!=null?o:1)||1,f=Number((l=e.renderer.width)!=null?l:0)/m,b=Number((c=e.renderer.height)!=null?c:0)/m;if(Number.isFinite(f)&&f>0&&Number.isFinite(b)&&b>0)return{width:f,height:b}}let t=document.querySelector(".game-container"),i=Number((d=t==null?void 0:t.dataset)==null?void 0:d.screenWidth),n=Number((u=t==null?void 0:t.dataset)==null?void 0:u.screenHeight);return Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:null}getRuntimeLayoutReference(){var a,s,o,l,c,d,u,p,g,h,m,f,b,y,v,S,L,j,_,E,M,I,k,T,A,C,w,x,O,P,R,z,F,G;let e=window.__mainContainer;if(e){let H=(s=(a=e.scale)==null?void 0:a.x)!=null?s:1,B=(l=(o=e.scale)==null?void 0:o.y)!=null?l:H;return console.log("[SceneEditor] getRuntimeLayoutReference: using __mainContainer",{scale:{x:H,y:B},position:{x:(c=e.position)==null?void 0:c.x,y:(d=e.position)==null?void 0:d.y}}),e}let t=window.__screenManager;if(t){let H=["gameplay","start","tutorial","endgame","loading"];for(let B of H){let $=(u=t.get)==null?void 0:u.call(t,B);if($!=null&&$.visible){let U=(p=$.getContentLayer)==null?void 0:p.call($);if(U){let X=(g=$.x)!=null?g:0,se=(h=$.y)!=null?h:0,N=(m=U.x)!=null?m:0,ee=(f=U.y)!=null?f:0,J=(y=(b=U.scale)==null?void 0:b.x)!=null?y:1,ae=(S=(v=U.scale)==null?void 0:v.y)!=null?S:J;return console.log("[SceneEditor] getRuntimeLayoutReference: using visible screen contentLayer",{screenId:B,contentLayerScale:{x:J,y:ae},position:{x:X+N,y:se+ee}}),{scale:{x:J,y:ae},position:{x:X+N,y:se+ee},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}for(let B of H){let $=(L=t.get)==null?void 0:L.call(t,B);if($){if(!$.visible&&typeof $.updateLayout=="function"){let X=window.gameApp;if((j=X==null?void 0:X.renderer)!=null&&j.screen){let se=X.renderer.screen.width,N=X.renderer.screen.height;se>0&&N>0&&$.updateLayout(se,N)}}let U=(_=$.getContentLayer)==null?void 0:_.call($);if(U){let X=(E=$.x)!=null?E:0,se=(M=$.y)!=null?M:0,N=(I=U.x)!=null?I:0,ee=(k=U.y)!=null?k:0,J=(A=(T=U.scale)==null?void 0:T.x)!=null?A:1,ae=(w=(C=U.scale)==null?void 0:C.y)!=null?w:J;return console.log("[SceneEditor] getRuntimeLayoutReference: using any screen contentLayer",{screenId:B,visible:$.visible,contentLayerScale:{x:J,y:ae},position:{x:X+N,y:se+ee}}),{scale:{x:J,y:ae},position:{x:X+N,y:se+ee},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}}let i=window.gameApp,n=(x=i==null?void 0:i.stage)!=null?x:null;if(n){let H=(P=(O=n.scale)==null?void 0:O.x)!=null?P:1,B=(z=(R=n.scale)==null?void 0:R.y)!=null?z:H;console.log("[SceneEditor] getRuntimeLayoutReference: using gameApp.stage (fallback)",{scale:{x:H,y:B},position:{x:(F=n.position)==null?void 0:F.x,y:(G=n.position)==null?void 0:G.y}})}else console.log("[SceneEditor] getRuntimeLayoutReference: no reference found");return n}getRuntimeParentContainer(e){var l,c;let t=window.gameObjectManager;if(!(t!=null&&t.get))return null;let i=t.get(e),n=((l=i==null?void 0:i.getDisplayObject)==null?void 0:l.call(i))||(i==null?void 0:i.pixiObject)||i,a=n==null?void 0:n.parent;if(!a)return null;let s=this.getRuntimeLayoutReference(),o=(c=window.gameApp)==null?void 0:c.stage;return s&&o&&s===o?this.mainContainer:s&&typeof s.contains=="function"&&s.contains(a)?this.mainContainer:a===s||a===o?this.mainContainer:this.uiContainer}applyRuntimeTransform(e){var s,o,l,c,d,u,p,g,h,m;if(!e)return console.log("[SceneEditor] applyRuntimeTransform: no reference"),!1;let t=1,i=1,n=Number((o=(s=e.position)==null?void 0:s.x)!=null?o:0),a=Number((c=(l=e.position)==null?void 0:l.y)!=null?c:0);if(!Number.isFinite(n)||!Number.isFinite(a))return console.log("[SceneEditor] applyRuntimeTransform: invalid position",{posX:n,posY:a}),!1;if(console.log("[SceneEditor] applyRuntimeTransform: applying (scale always 1)",{scale:{x:t,y:i},position:{x:n,y:a}}),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.position.set(n,a),this.uiContainer.position.set(n,a),e.pivot&&((d=this.mainContainer.pivot)!=null&&d.set)&&((u=this.uiContainer.pivot)!=null&&u.set)){let f=Number((g=(p=e.pivot)==null?void 0:p.x)!=null?g:0),b=Number((m=(h=e.pivot)==null?void 0:h.y)!=null?m:0);Number.isFinite(f)&&Number.isFinite(b)&&(this.mainContainer.pivot.set(f,b),this.uiContainer.pivot.set(f,b))}return typeof e.rotation=="number"&&(this.mainContainer.rotation=e.rotation,this.uiContainer.rotation=e.rotation),!0}getEditableConfig(){return window.__editableConfig||null}getEditableObjectConfig(e){var n,a;let t=window.getEditableObjectConfig;if(typeof t=="function")return t(e);let i=this.getEditableConfig();return i!=null&&i.objects?typeof i.objects.get=="function"?(n=i.objects.get(e))!=null?n:null:(a=i.objects[e])!=null?a:null:null}getEditableObjectIds(){let e=window.getEditableObjectList;if(typeof e=="function"){let i=e();if(Array.isArray(i))return i}let t=this.getEditableConfig();return t!=null&&t.objects?typeof t.objects.keys=="function"?Array.from(t.objects.keys()):Object.keys(t.objects):[]}async syncFromConfig(e){if(!this.app)return;let t=this.getEditableConfig();if(!(t!=null&&t.objects))return;let i=e!=null&&e.length?e:this.getEditableObjectIds(),n=new Set(i);if(!e)for(let a of Array.from(this.objectMap.keys()))n.has(a)||this.removeObject(a);for(let a of i){let s=this.getEditableObjectConfig(a);if(!s){this.removeObject(a);continue}await this.upsertObject(a,s)}this.updateGizmos(),this.updateSpawnPointHandles(),this.updateGameFrame(this.getScreen())}removeObject(e){var i,n;let t=this.objectMap.get(e);if(t){try{(n=(i=t.displayObject)==null?void 0:i.destroy)==null||n.call(i)}catch{}this.objectMap.delete(e),this.selectedId===e&&this.setSelected(null,{silent:!0})}}async upsertObject(e,t){let i=this.getAssetKey(t),n=this.objectMap.get(e),a=this.isUiConfig(e,t),s=this.playModeEnabled?this.getRuntimeParentContainer(e):null,o=a?this.uiContainer:this.mainContainer,l=s!=null?s:o;if(!n||n.assetKey!==i||n.isUi!==a){n&&this.removeObject(e);let d=await this.createDisplayObject(e,t);if(!d)return;l.addChild(d),this.objectMap.set(e,{id:e,displayObject:d,assetKey:i,isUi:a}),this.attachObjectInteraction(d,e)}let c=this.objectMap.get(e);c&&(c.displayObject.parent!==l&&l.addChild(c.displayObject),this.applyVisualConfig(c.displayObject,t),this.playModeEnabled||this.applyTransformFromConfig(e,c.displayObject,t))}async createDisplayObject(e,t){var o,l,c,d,u,p,g,h,m,f,b,y,v,S,L;if((o=t==null?void 0:t.render)!=null&&o.asset)try{if(((c=(l=t==null?void 0:t.render)==null?void 0:l.asset)==null?void 0:c.type)!=="json"){let _=await Te.create(e,t,this.app);if(_ instanceof Ye)return _}}catch(j){console.warn("[SceneEditor] ObjectFactory failed for",e,j)}let i=t==null?void 0:t.ui,n=(d=t==null?void 0:t.render)!=null?d:{},a=(i==null?void 0:i.text)||(i==null?void 0:i.kind)==="text";if(!!n.background_color){let j=this.getScreen(),_=(u=j==null?void 0:j.width)!=null?u:0,E=(p=j==null?void 0:j.height)!=null?p:0,M=new xe,I=this.parseColor(n.background_color,0),k=typeof n.background_alpha=="number"?n.background_alpha:1;_>0&&E>0&&M.rect(0,0,_,E).fill({color:I,alpha:k});let T=new Ye;return T.addChild(M),T}if(a){let j=(h=(g=i==null?void 0:i.color)!=null?g:n==null?void 0:n.tint)!=null?h:"#ffffff",_=new No({fontFamily:"Arial, sans-serif",fontSize:(m=i==null?void 0:i.fontSize)!=null?m:16,fill:j,align:(f=i==null?void 0:i.align)!=null?f:"center",letterSpacing:(b=i==null?void 0:i.letterSpacing)!=null?b:0});return new Ho({text:(y=i==null?void 0:i.text)!=null?y:"",style:_})}if((v=t==null?void 0:t.effects)!=null&&v.width||(S=t==null?void 0:t.effects)!=null&&S.height){let j=new xe,_=typeof t.effects.width=="number"?t.effects.width:100,E=typeof t.effects.height=="number"?t.effects.height:100,M=(L=t.effects.fill_color)!=null?L:"#ffffff",I=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,k=Number.parseInt(String(M).replace("#",""),16);return j.rect(0,0,_,E).fill({color:Number.isFinite(k)?k:16777215,alpha:I}),j}return new Ye}attachObjectInteraction(e,t){if(e&&(e.eventMode="static",e.cursor="pointer",!e.hitArea&&typeof e.getLocalBounds=="function")){let i=e.getLocalBounds();i&&i.width>0&&i.height>0&&(e.hitArea=new hr(i.x,i.y,i.width,i.height))}}getAssetKey(e){var i;let t=(i=e==null?void 0:e.render)==null?void 0:i.asset;return t?`${t.type||"asset"}::${t.path||""}`:null}isUiConfig(e,t){var a,s;let i=(((a=t==null?void 0:t.identity)==null?void 0:a.category)||"").toString().toLowerCase(),n=(((s=t==null?void 0:t.identity)==null?void 0:s.id)||e||"").toString().toLowerCase();return i.includes("ui")||n.startsWith("ui")||n.includes("label")}applyVisualConfig(e,t){var s,o,l,c,d,u,p,g,h;if(!e)return;let i=(s=t==null?void 0:t.render)!=null?s:{};typeof i.alpha=="number"&&(e.alpha=i.alpha),e.visible=i.visible!==!1,e.zIndex=typeof i.z_index=="number"?i.z_index:0;let n=(d=(c=(o=t==null?void 0:t.render)==null?void 0:o.anchor)!=null?c:(l=t==null?void 0:t.transform)==null?void 0:l.anchor)!=null?d:"top-right";n==="top-right"&&!((u=t==null?void 0:t.render)!=null&&u.anchor)&&!((p=t==null?void 0:t.transform)!=null&&p.anchor)&&console.log("[DEBUG FALLBACK] applyVisualConfig (SceneEditor) \u2192 top-right");let a=ye(n,{x:.5,y:.5});if((g=e.anchor)!=null&&g.set)e.anchor.set(a.x,a.y);else if(e.pivot){let m=(h=e.getLocalBounds)==null?void 0:h.call(e);m&&e.pivot.set(m.width*a.x,m.height*a.y)}}applyTransformFromConfig(e,t,i){var _,E,M,I,k,T,A,C,w,x,O;if(!t)return;let n=this.getScreen();if(!(n!=null&&n.width)||!(n!=null&&n.height))return;let a=(_=i==null?void 0:i.transform)!=null?_:{},s=this.getPositioningAnchor(e,a),o=a==null?void 0:a.position_ratio,l=a==null?void 0:a.position,c=a==null?void 0:a.offset,d=Array.isArray(l)?Number((E=l[0])!=null?E:0):Number((M=l==null?void 0:l.x)!=null?M:0),u=Array.isArray(l)?Number((I=l[1])!=null?I:0):Number((k=l==null?void 0:l.y)!=null?k:0),p=Array.isArray(c)?Number((T=c[0])!=null?T:0):Number((A=c==null?void 0:c.x)!=null?A:0),g=Array.isArray(c)?Number((C=c[1])!=null?C:0):Number((w=c==null?void 0:c.y)!=null?w:0),h=(Number.isFinite(d)?d:0)+(Number.isFinite(p)?p:0),m=(Number.isFinite(u)?u:0)+(Number.isFinite(g)?g:0),f=o!=null?Ge(n.width,n.height,o):Ue(n.width,n.height,s),b=Number.isFinite(this.layoutScale)&&this.layoutScale>0?this.layoutScale:1,y=(f.x-n.width/2)/b+h,v=(f.y-n.height/2)/b+m;(x=t.position)!=null&&x.set?t.position.set(y,v):t.position&&(t.position.x=y,t.position.y=v);let L=(typeof(a==null?void 0:a.scale)=="number"?a.scale:1)*(Number.isFinite(this.layoutScale)&&this.layoutScale>0?this.layoutScale:1);(O=t.scale)!=null&&O.set?t.scale.set(L,L):t.scale&&(t.scale.x=L,t.scale.y=L);let j=typeof(a==null?void 0:a.rotation)=="number"?a.rotation:0;t.rotation=this.toRadians(j)}getAnchorLocalPoint(e,t=this.mainContainer){var d;let i=this.playModeEnabled?(d=this.getScreen())!=null?d:this.getRuntimeScreenSize():this.getScreen();if(!(i!=null&&i.width)||!(i!=null&&i.height))return null;let n="top-right",a=this.getPositioningAnchor(this.selectedId,e!=null?e:{}),s=(e==null?void 0:e.position_ratio)!=null?Ge(i.width,i.height,e.position_ratio):Ue(i.width,i.height,a!=null?a:n),o=Number.isFinite(this.layoutScale)&&this.layoutScale>0?this.layoutScale:1,l=(s.x-i.width/2)/o,c=(s.y-i.height/2)/o;return new Q(l,c)}getPositioningAnchor(e,t){var i,n,a;if((t==null?void 0:t.anchor)!=null&&t.anchor!=="")return t.anchor;if(typeof window!="undefined"&&e){let o=window.__editableConfigBaseline,l=(n=(i=o==null?void 0:o.objects)==null?void 0:i.get)==null?void 0:n.call(i,e),c=(a=l==null?void 0:l.transform)==null?void 0:a.anchor;if(c!=null&&c!=="")return c}return"top-left"}updateLayout(e){var i,n,a,s,o,l,c,d,u;let t=e!=null?e:this.getScreen();if(!(!(t!=null&&t.width)||!(t!=null&&t.height))){if(console.log("[SceneEditor] updateLayout: called",{screen:{width:t.width,height:t.height},currentScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}}),this.playModeEnabled){let p=this.getRuntimeLayoutReference();if(p){let g=Number((n=(i=p.position)==null?void 0:i.x)!=null?n:t.width/2),h=Number((s=(a=p.position)==null?void 0:a.y)!=null?s:t.height/2);this.mainContainer.position.set(g,h),this.uiContainer.position.set(g,h);let m=Number((l=(o=p.scale)==null?void 0:o.x)!=null?l:1);Number.isFinite(m)&&m>0&&(this.layoutScale=m)}this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1)}else this.mainContainer.position.set(t.width/2,t.height/2),this.uiContainer.position.set(t.width/2,t.height/2),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.rotation=0,this.uiContainer.rotation=0,(c=this.mainContainer.pivot)!=null&&c.set&&this.mainContainer.pivot.set(0,0),(d=this.uiContainer.pivot)!=null&&d.set&&this.uiContainer.pivot.set(0,0);console.log("[SceneEditor] updateLayout: result",{finalScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y},position:{x:this.mainContainer.position.x,y:this.mainContainer.position.y}}),this.screenFrame.clear(),this.screenFrame.rect(0,0,t.width,t.height),this.screenFrame.stroke({width:2,color:2894892,alpha:.5}),this.updateGameFrame(t),(u=this.app)!=null&&u.stage&&(this.app.stage.hitArea=new hr(0,0,this.app.renderer.width,this.app.renderer.height)),this.updateSpawnPointHandles()}}updateGrid(){if(!this.app)return;if(!this.gridEnabled){this.gridLayer.clear(),this.gridLayer.visible=!0;return}let e=Math.max(4,this.gridGap),t=this.app.renderer,i=this.camera.toLocal(new Q(0,0)),n=this.camera.toLocal(new Q(t.width,t.height)),a=Math.min(i.x,n.x),s=Math.max(i.x,n.x),o=Math.min(i.y,n.y),l=Math.max(i.y,n.y),c=400,d=Math.ceil((s-a)/e),u=Math.ceil((l-o)/e),p=e*Math.max(1,Math.ceil(d/c)),g=e*Math.max(1,Math.ceil(u/c)),h=Math.floor(a/p)*p,m=Math.floor(o/g)*g;this.gridLayer.clear(),this.gridLayer.visible=!0;for(let f=h;f<=s;f+=p)this.gridLayer.moveTo(f,o),this.gridLayer.lineTo(f,l);for(let f=m;f<=l;f+=g)this.gridLayer.moveTo(a,f),this.gridLayer.lineTo(s,f);this.gridLayer.stroke({width:1,color:16777215,alpha:this.gridAlpha})}updateGameFrame(e){var o;let t=this.playModeEnabled?(o=e!=null?e:this.getScreen())!=null?o:this.getRuntimeScreenSize():e!=null?e:this.getScreen();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;let i=t.width,n=t.height,a=0,s=0;this.lastGameFrameSize&&this.lastGameFrameSize.width===t.width&&this.lastGameFrameSize.height===t.height||(this.lastGameFrameSize={width:t.width,height:t.height},this.gameFrame.clear(),this.gameFrame.rect(a,s,i,n),this.gameFrame.stroke({width:2,color:6333946,alpha:.35}))}syncFromGameObjectsInternal(){var i,n,a,s,o,l,c,d;if(!this.playModeEnabled||!this.app||!this.isVisible)return;let e=window.gameObjectManager;if(!(e!=null&&e.get))return;let t=this.dragMode?this.selectedId:null;for(let[u,p]of this.objectMap.entries()){if(t&&u===t)continue;let g=e.get(u),h=((i=g==null?void 0:g.getDisplayObject)==null?void 0:i.call(g))||(g==null?void 0:g.pixiObject)||g;if(!h)continue;let m=(a=(n=p.displayObject)==null?void 0:n.parent)!=null?a:this.mainContainer,f=new Q;if(typeof h.getGlobalPosition=="function"){h.getGlobalPosition(f);let L=m.toLocal(f,this.camera);p.displayObject.position.set(L.x,L.y)}else if(h.worldTransform){f.set(h.worldTransform.tx,h.worldTransform.ty);let L=m.toLocal(f,this.camera);p.displayObject.position.set(L.x,L.y)}let b=this.getWorldScale(h);if(b){let L=Number((o=(s=m.scale)==null?void 0:s.x)!=null?o:1)||1,j=Number((c=(l=m.scale)==null?void 0:l.y)!=null?c:1)||1,_=b.x/L,E=b.y/j;(d=p.displayObject.scale)!=null&&d.set?p.displayObject.scale.set(_,E):p.displayObject.scale&&(p.displayObject.scale.x=_,p.displayObject.scale.y=E)}let y=this.getWorldRotation(h);if(typeof y=="number"){let L=m?m.rotation:0;p.displayObject.rotation=y-L}let v=h.parent,S=typeof(v==null?void 0:v.getChildIndex)=="function"?v.getChildIndex(h):0;typeof h.zIndex=="number"?p.displayObject.zIndex=h.zIndex:Number.isFinite(S)&&(p.displayObject.zIndex=S)}this.updateGizmos()}getWorldScale(e){var a,s;let t=(s=e==null?void 0:e.worldTransform)!=null?s:(a=e==null?void 0:e.transform)==null?void 0:a.worldTransform;if(!t)return null;let i=Math.sqrt(t.a*t.a+t.b*t.b),n=Math.sqrt(t.c*t.c+t.d*t.d);return!Number.isFinite(i)||!Number.isFinite(n)?null:{x:i,y:n}}getWorldRotation(e){var i,n;let t=(n=e==null?void 0:e.worldTransform)!=null?n:(i=e==null?void 0:e.transform)==null?void 0:i.worldTransform;if(t){let a=Math.atan2(t.b,t.a);return Number.isFinite(a)?a:null}return typeof(e==null?void 0:e.rotation)=="number"?e.rotation:null}centerCamera(){var a;if(!this.app)return;let e=this.playModeEnabled?(a=this.getScreen())!=null?a:this.getRuntimeScreenSize():this.getScreen();if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=this.app.renderer.width,i=this.app.renderer.height,n=Math.max(.01,Math.min(t/e.width,i/e.height));this.cameraScale=n,this.camera.scale.set(n),this.camera.position.set((t-e.width*n)/2,(i-e.height*n)/2)}updateGizmos(){var m,f;if(!this.selectedId||!this.isVisible){this.clearGizmos();return}let e=this.objectMap.get(this.selectedId);if(!(e!=null&&e.displayObject)){this.clearGizmos();return}let t=(f=(m=e.displayObject).getBounds)==null?void 0:f.call(m);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let i=this.camera.toLocal(new Q(t.x,t.y)),n=this.camera.toLocal(new Q(t.x+t.width,t.y+t.height)),a=n.x-i.x,s=n.y-i.y,o=i.x+a/2,l=i.y+s/2;if(this.gizmoOutline.clear(),this.gizmoOutline.rect(i.x,i.y,a,s),this.gizmoOutline.stroke({width:2,color:16752394,alpha:.9}),this.playModeEnabled){this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear();return}let c=7,d={width:2,color:988970,alpha:.6};this.moveHandle.clear(),this.moveHandle.circle(o,l,c).fill({color:2278750,alpha:.95}),this.moveHandle.stroke(d),this.moveHandle.cursor="move";let u=i.x+a,p=i.y+s;this.scaleHandle.clear(),this.scaleHandle.rect(u-c,p-c,c*2,c*2).fill({color:3718648,alpha:.95}),this.scaleHandle.stroke(d),this.scaleHandle.cursor="nwse-resize";let g=o,h=i.y-c*2;this.rotateHandle.clear(),this.rotateHandle.circle(g,h,c).fill({color:16347926,alpha:.95}),this.rotateHandle.stroke(d),this.rotateHandle.cursor="crosshair"}clearGizmos(){this.gizmoOutline.clear(),this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear()}updateSpawnPointHandles(){if(this.clearSpawnPointHandles(),!this.selectedId)return;let e=this.getEditableObjectConfig(this.selectedId);if(!e||!this.isSpawnerConfig(e))return;let t=this.getSpawnPoints(e);!t||t.length===0||t.forEach((i,n)=>{let a=new xe;a.circle(0,0,5).fill({color:16096779,alpha:.9}),a.circle(0,0,9).stroke({width:1,color:16096779,alpha:.45});let s=this.toCameraFromMain(i);a.position.set(s.x,s.y),a.cursor="move",this.playModeEnabled?a.eventMode="none":(a.eventMode="static",a.on("pointerdown",o=>this.startSpawnPointDrag(n,o))),this.spawnPointLayer.addChild(a)})}clearSpawnPointHandles(){this.spawnPointLayer.removeChildren().forEach(t=>{var i;(i=t.destroy)==null||i.call(t)})}isSpawnerConfig(e){var i,n;return((i=e==null?void 0:e.logic)==null?void 0:i.id)==="Spawner"?!0:String(((n=e==null?void 0:e.identity)==null?void 0:n.system_role)||"").toLowerCase().includes("spawner")}getSpawnPoints(e){var i,n;let t=(n=(i=e==null?void 0:e.logic)==null?void 0:i.props)==null?void 0:n.spawnPoints;return Array.isArray(t)?t.map(a=>{var s,o;return{x:Number((s=a==null?void 0:a.x)!=null?s:0),y:Number((o=a==null?void 0:a.y)!=null?o:0)}}):null}toCameraFromMain(e){let t=this.mainContainer.toGlobal(new Q(e.x,e.y)),i=new Q;return this.camera.toLocal(t,void 0,i),i}startSpawnPointDrag(e,t){var o,l;if(!this.selectedId)return;let i=this.getEditableObjectConfig(this.selectedId);if(!i)return;let n=this.getSpawnPoints(i);if(!n||!n[e])return;(o=t==null?void 0:t.stopPropagation)==null||o.call(t),(l=t==null?void 0:t.stopImmediatePropagation)==null||l.call(t);let a=this.getEventLocalPoint(t,this.mainContainer);if(!a)return;let s=n[e];this.spawnPointDrag={objectId:this.selectedId,index:e,offset:new Q(s.x-a.x,s.y-a.y),startPoints:n.map(c=>({x:c.x,y:c.y}))},window.addEventListener("pointermove",this.onSpawnPointDragMove),window.addEventListener("pointerup",this.onSpawnPointDragEnd)}updateLiveSpawnPoint(e,t,i,n){let a=this.getEditableObjectConfig(e);if(!a)return;let s=this.getSpawnPoints(a);if(!s||!s[t])return;let o=s.map((l,c)=>c===t?{x:i,y:n}:{x:l.x,y:l.y});this.setNestedValue(a,"logic.props.spawnPoints",o),this.queueLiveApply(e),this.updateSpawnPointHandles()}setSelected(e,t={}){if(this.selectedId!==e&&(this.selectedId=e,this.updateGizmos(),this.updateSpawnPointHandles(),!t.silent&&e)){let i=window.__previewSelectObject;typeof i=="function"&&i(e)}}startDrag(e,t){var l,c,d,u,p;if(this.playModeEnabled||!this.selectedId)return;let i=this.objectMap.get(this.selectedId);if(!(i!=null&&i.displayObject))return;let n=this.getEditableObjectConfig(this.selectedId);if(!n)return;let a=(l=n.transform)!=null?l:{},s=(c=i.displayObject.parent)!=null?c:this.mainContainer,o=this.getEventLocalPoint(t,s);o&&((d=t==null?void 0:t.stopPropagation)==null||d.call(t),(u=t==null?void 0:t.stopImmediatePropagation)==null||u.call(t),this.dragMode=e,this.dragContainer=s,this.dragStartPointer=new Q(o.x,o.y),this.dragStartPos=new Q(i.displayObject.position.x,i.displayObject.position.y),this.dragStartScale=typeof((p=i.displayObject.scale)==null?void 0:p.x)=="number"?i.displayObject.scale.x:1,this.dragStartRotation=typeof i.displayObject.rotation=="number"?i.displayObject.rotation:0,this.dragAnchorLocal=this.getAnchorLocalPoint(a,s),this.dragStartValue=this.getDragStartValue(e,a),this.dragAnchorLocal&&(this.dragStartAngle=Math.atan2(o.y-this.dragAnchorLocal.y,o.x-this.dragAnchorLocal.x),this.dragStartDistance=Math.max(1,this.distance(o,this.dragAnchorLocal))),window.addEventListener("pointermove",this.onDragMove),window.addEventListener("pointerup",this.onDragEnd))}getDragStartValue(e,t){var i,n,a;return e==="move"?(i=t==null?void 0:t.position)!=null?i:{x:0,y:0}:e==="scale"?(n=t==null?void 0:t.scale)!=null?n:1:e==="rotate"?(a=t==null?void 0:t.rotation)!=null?a:0:null}updateLiveConfigPosition(e,t){var u,p,g,h,m,f;if(!this.selectedId||!this.dragAnchorLocal)return;let i=e-this.dragAnchorLocal.x,n=t-this.dragAnchorLocal.y,a=this.getEditableObjectConfig(this.selectedId);if(!a)return;let s=(u=a.transform)!=null?u:{};a.transform||(a.transform=s);let o=(p=s.offset)!=null?p:{x:0,y:0},l=Array.isArray(o)?Number((g=o[0])!=null?g:0):Number((h=o==null?void 0:o.x)!=null?h:0),c=Array.isArray(o)?Number((m=o[1])!=null?m:0):Number((f=o==null?void 0:o.y)!=null?f:0),d=this.buildPositionValue(s,{x:i-l,y:n-c});this.setNestedValue(s,"position",d)}updateLiveConfigScale(e){var a;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(a=t.transform)!=null?a:{};t.transform||(t.transform=i);let n=!this.playModeEnabled&&Number.isFinite(this.layoutScale)&&this.layoutScale>0?this.layoutScale:1;i.scale=Math.round(e/n*100)/100}updateLiveConfigRotation(e){var s;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(s=t.transform)!=null?s:{};t.transform||(t.transform=i);let n=this.toDegrees(e),a=typeof i.rotation=="number"?i.rotation:0;Math.abs(n-a)>.01&&(i.rotation=Math.round(n*100)/100)}applyFinalOverride(e,t,i,n){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),n),Ne({objectId:e,path:t,value:i},{persist:!0,emitEvent:!0,trackHistory:!0})}queueLiveApply(e){this.applyQueuedId=e,!this.applyQueued&&(this.applyQueued=!0,requestAnimationFrame(()=>{this.applyQueued=!1;let t=this.applyQueuedId;if(!t)return;let i=this.getEditableObjectConfig(t),n=window.applyEditableObjectConfig;typeof n=="function"&&i&&(n(t,i),window.dispatchEvent(new CustomEvent("inspector:refresh")))}))}setNestedValue(e,t,i){let n=t.split("."),a=e;for(let s=0;s<n.length-1;s+=1){let o=n[s];(!a[o]||typeof a[o]!="object")&&(a[o]={}),a=a[o]}a[n[n.length-1]]=i}buildPositionValue(e,t){let i=e==null?void 0:e.position,n=Math.round(t.x*100)/100,a=Math.round(t.y*100)/100;return Array.isArray(i)?[n,a]:{x:n,y:a}}toRadians(e){return e*Math.PI/180}toDegrees(e){return e*180/Math.PI}distance(e,t){let i=e.x-t.x,n=e.y-t.y;return Math.sqrt(i*i+n*n)}getPointerButton(e){var t,i,n;return typeof(e==null?void 0:e.button)=="number"?e.button:typeof((t=e==null?void 0:e.data)==null?void 0:t.button)=="number"?e.data.button:typeof((n=(i=e==null?void 0:e.data)==null?void 0:i.originalEvent)==null?void 0:n.button)=="number"?e.data.originalEvent.button:0}getEventGlobalPoint(e){var l,c;let t=(c=e==null?void 0:e.global)!=null?c:(l=e==null?void 0:e.data)==null?void 0:l.global;if(t)return new Q(t.x,t.y);if(!this.app)return null;let i=e==null?void 0:e.clientX,n=e==null?void 0:e.clientY;if(typeof i!="number"||typeof n!="number")return null;let a=this.app.canvas.getBoundingClientRect(),s=(i-a.left)*(this.app.renderer.width/a.width),o=(n-a.top)*(this.app.renderer.height/a.height);return new Q(s,o)}getEventLocalPoint(e,t=this.mainContainer){var a,s;if(!this.app)return null;if(typeof(e==null?void 0:e.getLocalPosition)=="function"){let o=e.getLocalPosition(t);return new Q(o.x,o.y)}let i=(s=e==null?void 0:e.global)!=null?s:(a=e==null?void 0:e.data)==null?void 0:a.global;if(!i)return null;let n=new Q;return t.toLocal(new Q(i.x,i.y),void 0,n),n}getPointerInContainer(e,t,i){if(!this.app)return null;let n=this.app.canvas.getBoundingClientRect(),a=(e-n.left)*(this.app.renderer.width/n.width),s=(t-n.top)*(this.app.renderer.height/n.height),o=new Q;return i.toLocal(new Q(a,s),void 0,o),o}parseColor(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=e.trim().replace("#",""),n=Number.parseInt(i,16);if(Number.isFinite(n))return n}return t}};var Vn=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[ct("playable-portrait"),ct("iphone-14"),ct("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.isSpaceKeyPressed=!1;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.originalConsole={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console)};this.sceneEditor=null;this.sceneVisiblePreference=!0;this.sceneVisible=!0;this.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.hasUnsavedChanges=!1;this.hasForceSynced=!1;this.onWindowResize=e=>{if(this.ignoreNextWindowResize){this.ignoreNextWindowResize=!1;return}this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()};this.onFrameDragMove=e=>{if(!this.frameDragActive)return;let t=e.clientX-this.frameDragStartX,i=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+i,this.applyFrameDrag(),this.updateDragCursor()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd),this.updateDragCursor())};this.options=e,this.currentPreset=ct(e.defaultDevice||un.id),this.debugPanel=new Bi,this.container=this.createShell(),this.previewContainer=this.mustQuery(".preview-container"),this.singleStage=this.mustQuery('[data-preview-stage="single"]'),this.compareStage=this.mustQuery('[data-preview-stage="compare"]'),this.frameDragger=this.mustQuery(".frame-dragger"),this.frameWrapper=this.mustQuery(".frame-wrapper"),this.deviceFrame=this.mustQuery(".device-frame"),this.gameContainer=this.mustQuery(".game-container"),this.scenePane=this.mustQuery("[data-scene-pane]"),this.sceneRoot=this.mustQuery("#scene-editor-root"),this.sceneSplitter=this.mustQuery("[data-scene-splitter]"),this.gameViewPane=this.mustQuery("[data-game-pane]"),this.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners();try{let i=window.localStorage.getItem(this.getSceneVisibilityStorageKey());this.sceneVisiblePreference=i===null?!0:i==="true"}catch{}let t="dark";try{let i=window.localStorage.getItem(this.getThemeStorageKey());(i==="light"||i==="dark")&&(t=i)}catch{}this.setTheme(t),this.sceneEditor=new Ui({root:this.sceneRoot,getScreen:()=>this.getScreen()}),this.sceneEditor.mount(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setupShortcutListeners(),this.setupUnsavedChangesIndicator(),this.setupScenePaneInteractions(),this.updateSceneVisibility(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.updateDockState(),this.isInitialized=!0,this.scheduleForceSync()}getShortcutKey(){return typeof navigator!="undefined"&&navigator.platform.toUpperCase().indexOf("MAC")>=0?"CMD":"CTRL"}mount(e=document.body){e.innerHTML="",e.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}scheduleForceSync(){this.hasForceSynced||(this.hasForceSynced=!0,window.setTimeout(()=>{let e=window.__HANDLER_ACTIVE_SCREEN;fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"})}).catch(i=>{console.warn("[PreviewShell] Force sync on refresh failed:",i)})},250))}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1,this.sceneEditor&&(this.sceneEditor.destroy(),this.sceneEditor=null)}getGameContainer(){return this.gameContainer}getScreen(){let e=this.getEffectivePreset();return{width:e.width,height:e.height}}getEffectivePreset(){var e;return this.isLandscape?{...this.currentPreset,width:this.currentPreset.height,height:this.currentPreset.width,ratio:((e=this.currentPreset.ratio)==null?void 0:e.split(":").reverse().join(":"))||this.currentPreset.ratio}:this.currentPreset}notifyGameLoaded(){var e;this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh(),(e=this.sceneEditor)==null||e.refresh(),requestAnimationFrame(()=>this.updatePanelPositions())}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(e,t={}){var n,a;let i=this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=ct(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:i}),t.suppressCallback||(a=(n=this.options).onDeviceChange)==null||a.call(n,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark");try{window.localStorage.setItem(this.getThemeStorageKey(),e)}catch{}let t=this.container.querySelector("#theme-select");t&&(t.value=e),requestAnimationFrame(()=>this.updatePanelPositions())}setLayoutMode(e){if(this.layoutMode===e)return;this.layoutMode=e,this.container.classList.toggle("layout-fixed",e==="fixed"),this.container.classList.toggle("layout-draggable",e==="draggable"),Array.from(this.container.querySelectorAll("[data-layout-toggle]")).forEach(n=>n.classList.toggle("active",n.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(n=>{n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),this.updateSceneVisibility(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}updateDockState(){let e=this.container.querySelector("#bottom-dock");e==null||e.classList.remove("hidden");let t=this.container.querySelector("#console-messages"),i=this.container.querySelector("#dock-console-content");t&&i&&t.parentElement!==i&&i.appendChild(t)}makeBottomDockResizable(e,t){let i,n,a=o=>{let l=o.clientY-i,c=Math.max(100,Math.min(800,n-l));e.style.height=`${c}px`;let d=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:d})},s=()=>{document.removeEventListener("pointermove",a),document.removeEventListener("pointerup",s),e.classList.remove("resizing")};t.addEventListener("pointerdown",o=>{o.preventDefault(),i=o.clientY,n=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",s),e.classList.add("resizing")})}makeSidebarResizable(e,t,i){let n,a,s=()=>{let c=this.container.querySelector(".preview-main");if(!c)return 600;let u=c.getBoundingClientRect().width,p=i==="left"?this.container.querySelector(".debug-workbench"):this.container.querySelector(".scene-panel.scene-objects"),g=p?p.offsetWidth:i==="left"?350:300,m=u-g-200;return Math.max(200,m)},o=c=>{let d=i==="left"?c.clientX-n:n-c.clientX,u=s(),p=Math.max(200,Math.min(u,a+d));e.style.width=`${p}px`;let g=this.container.querySelector(".preview-main");if(g){let m=i==="left"?`${p}px`:g.style.gridTemplateColumns.split(" ")[0]||"300px",f=i==="right"?`${p}px`:g.style.gridTemplateColumns.split(" ")[2]||"350px",b=400;g.style.gridTemplateColumns=`${m} minmax(${b}px, 1fr) ${f}`}let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},l=()=>{document.removeEventListener("pointermove",o),document.removeEventListener("pointerup",l),e.classList.remove("resizing")};t.addEventListener("pointerdown",c=>{c.preventDefault(),n=c.clientX,a=e.offsetWidth,document.addEventListener("pointermove",o),document.addEventListener("pointerup",l),e.classList.add("resizing")})}getSceneVisibilityStorageKey(){return`handler_preview_scene_visible::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getSceneWidthStorageKey(){return`handler_preview_scene_width::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getThemeStorageKey(){return`handler_preview_theme::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}setupScenePaneInteractions(){let e=this.scenePane.querySelector("[data-scene-drag-handle]"),t=this.scenePane.querySelector("[data-scene-resize]"),i=this.container.querySelector("[data-preview-split]");e&&et(this.scenePane,e,i!=null?i:this.previewContainer),t&&Hi(this.scenePane,t,void 0,260,200);let n=this.getStoredSceneWidth();n&&(this.scenePane.style.width=`${n}px`),this.sceneSplitter.addEventListener("pointerdown",a=>{if(this.layoutMode!=="fixed"||!this.sceneVisible)return;a.preventDefault();let s=a.clientX,o=this.scenePane.offsetWidth,l=Math.max(260,Math.min(720,this.previewContainer.clientWidth*.6)),c=u=>{let p=u.clientX-s,g=Math.max(240,Math.min(l,o+p));this.scenePane.style.width=`${g}px`;let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},d=()=>{document.removeEventListener("pointermove",c),document.removeEventListener("pointerup",d),this.storeSceneWidth(this.scenePane.offsetWidth)};document.addEventListener("pointermove",c),document.addEventListener("pointerup",d)})}storeSceneWidth(e){try{window.localStorage.setItem(this.getSceneWidthStorageKey(),String(e))}catch{}}getStoredSceneWidth(){try{let e=window.localStorage.getItem(this.getSceneWidthStorageKey()),t=e?Number(e):null;return Number.isFinite(t)&&t?t:null}catch{return null}}updateSceneVisibility(){let e=this.viewMode==="single"&&this.sceneVisiblePreference;this.setSceneVisible(e,{persist:!1});let t=this.container.querySelector("#scene-toggle");t&&(t.classList.toggle("active",this.sceneVisiblePreference),t.setAttribute("aria-pressed",String(this.sceneVisiblePreference)))}setSceneVisible(e,t={}){var i;if(this.sceneVisible=e,this.container.classList.toggle("scene-hidden",!e),(i=this.sceneEditor)==null||i.setVisible(e),t.persist!==!1){this.sceneVisiblePreference=e;try{window.localStorage.setItem(this.getSceneVisibilityStorageKey(),String(e))}catch{}}this.scheduleFit()}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell layout-fixed",e.innerHTML=`
|
|
2254
|
+
`,this.modal=e,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var i;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(i=this.options)!=null&&i.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,i=this.cropX+this.cropWidth/2,n=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,i-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,n-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let e=this.panX,t=this.panY,i=this.cropWidth*this.scale,n=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,i,n),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,i,n),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+i-a,t],[e,t+n-a],[e+i-a,t+n-a]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,a,a)})}updatePreview(){if(!this.modal||!this.image)return;let e=this.modal.querySelector(".asset-crop-preview-canvas");if(!e)return;let t=e.getContext("2d");if(!t)return;let i=150;e.width=i,e.height=i;let n=i/this.cropWidth,a=i/this.cropHeight,s=Math.min(n,a),o=this.cropWidth*s,l=this.cropHeight*s,c=(i-o)/2,d=(i-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,d,o,l)}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let e=this.modal.querySelector(".asset-crop-zoom-slider");e==null||e.addEventListener("input",i=>{let n=parseFloat(i.target.value);this.setZoom(n)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",i=>{let n=i.target.value;this.setAspectRatio(n)}),this.modal.addEventListener("click",i=>{switch(i.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",i=>{i.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,i=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,i=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var n;if(!this.image||!((n=this.options)!=null&&n.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let i=e.toDataURL("image/png");this.options.onCrop(i),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(r){new Gn().open(r)};import{Application as $o,Container as Ye,Graphics as xe,Point as Q,Rectangle as hr,Text as Ho,TextStyle as No}from"pixi.js";import{Sprite as Ro,Container as gr}from"pixi.js";var zo=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",qn=zo;if(typeof window!="undefined")try{let r=new XMLHttpRequest;if(r.open("GET","./build-settings.json",!1),r.send(),r.status===200&&r.responseText){let e=JSON.parse(r.responseText);e!=null&&e.buildMode&&(qn=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${qn}`))}}catch{}function Do(r){var t,i,n,a,s;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(r);let e={center:{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};if(Array.isArray(r))return{x:(t=r[0])!=null?t:.5,y:(i=r[1])!=null?i:.5};if(r&&typeof r=="object"&&"x"in r&&"y"in r)return{x:(n=r.x)!=null?n:.5,y:(a=r.y)!=null?a:.5};if(typeof r=="string"){let o=r.trim().toLowerCase();return(s=e[o])!=null?s:{x:.5,y:.5}}return null}var Te=class{static async create(e,t,i){var l,c,d,u,p,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${qn}`);let n=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!n){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let m=new gr;return this.applyTransform(m,t==null?void 0:t.transform,t),m}let a=(c=t==null?void 0:t.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${e}, configId: ${a}, type: ${n.type}, path: ${n.path}`);let s=await en.load(e,n,i,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(d=s==null?void 0:s.constructor)==null?void 0:d.name}`);let o;if(n.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",e),o=new Ro(s),console.log("[ObjectFactory] Created object:",o,"type:",(u=o==null?void 0:o.constructor)==null?void 0:u.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(n.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(p=s==null?void 0:s.constructor)==null?void 0:p.name,s),s&&(((g=s.constructor)==null?void 0:g.name)==="Container"||s instanceof gr)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let m=[n.path,`/assets/${n.path}`,`assets/${n.path}`,`../assets/${n.path}`],f=!1;for(let b of m)try{let y=await fetch(b);if(y.ok){o=await y.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(h=o==null?void 0:o.constructor)==null?void 0:h.name),f=!0;break}}catch{continue}f||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=s)}else o=s;else o=s,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,i){var n,a,s,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(n=t.position.x)!=null?n:0,e.y=(a=t.position.y)!=null?a:0):"position"in e&&e.position&&e.position.set((s=t.position.x)!=null?s:0,(o=t.position.y)!=null?o:0)),t.scale!==void 0&&"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(t.scale):e.scale=t.scale),t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor)){let l=Do(t.anchor);l&&("set"in e.anchor?e.anchor.set(l.x,l.y):(e.anchor.x=l.x,e.anchor.y=l.y))}}};var Ui=class{constructor(e){this.app=null;this.camera=new Ye;this.mainContainer=new Ye;this.uiContainer=new Ye;this.gizmoLayer=new Ye;this.screenFrame=new xe;this.gameFrame=new xe;this.gridLayer=new xe;this.spawnPointLayer=new Ye;this.objectMap=new Map;this.selectedId=null;this.dragMode=null;this.dragStartPointer=null;this.dragStartPos=null;this.dragStartScale=1;this.dragStartRotation=0;this.dragStartAngle=0;this.dragStartDistance=1;this.dragAnchorLocal=null;this.dragStartValue=null;this.dragContainer=null;this.spawnPointDrag=null;this.lastGameFrameSize=null;this.cameraScale=1;this.isPanning=!1;this.panStart=null;this.panStartCamera=null;this.hasUserCamera=!1;this.resizeObserver=null;this.screenSyncRaf=null;this.gizmoOutline=new xe;this.anchorVisualizationLayer=new xe;this.moveHandle=new xe;this.scaleHandle=new xe;this.rotateHandle=new xe;this.isVisible=!0;this.applyQueued=!1;this.applyQueuedId=null;this.gridEnabled=!1;this.gridGap=50;this.gridAlpha=.25;this.lastPickPoint=null;this.lastPickIds=[];this.lastPickIndex=0;this.lastPickTime=0;this.playModeEnabled=!0;this.playModeInitialized=!1;this.layoutScale=1;this.handleScreenChange=e=>{if(!(e!=null&&e.detail))return;let{width:t,height:i}=e.detail;!t||!i||(this.hasUserCamera=!1,this.updateLayout({width:t,height:i}),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid(),this.playModeEnabled?this.schedulePostScreenSync({width:t,height:i}):this.syncFromConfig())};this.handleActiveScreenChanged=()=>{this.isVisible&&this.syncFromConfig()};this.handleConfigChanged=e=>{if(!this.isVisible)return;this.updateLayout(),this.updateGrid();let t=e==null?void 0:e.detail;if(!t){this.syncFromConfig();return}let i=t.objectId,n=t.objectIds;if(i){this.syncFromConfig([i]);return}if(Array.isArray(n)&&n.length>0){this.syncFromConfig(n);return}this.syncFromConfig()};this.handleSceneRefresh=()=>{this.isVisible&&this.syncFromConfig()};this.handleAssetUpdated=e=>{var l;let t=(l=e==null?void 0:e.detail)!=null?l:{},i=t.objectId,n=t.texture;if(!i||!n)return;let a=this.objectMap.get(i);if(!a)return;let s=a.displayObject;if(s!=null&&s.texture)s.texture=n;else if(s!=null&&s.children){let c=s.children.find(d=>d==null?void 0:d.texture);c&&(c.texture=n)}let o=this.getEditableObjectConfig(i);o&&(a.assetKey=this.getAssetKey(o))};this.handleLayoutApplied=e=>{var s;if(!this.isVisible)return;let t=(s=e==null?void 0:e.detail)!=null?s:{},i=Number(t.width),n=Number(t.height),a=Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:this.getScreen();this.updateLayout(a),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.playModeEnabled&&this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid()})};this.handlePreviewSelect=e=>{var i,n;let t=(n=(i=e==null?void 0:e.detail)==null?void 0:i.objectId)!=null?n:null;this.setSelected(t,{silent:!0})};this.onStagePointerDown=e=>{if(!this.app||!this.isVisible||this.getPointerButton(e)!==0||this.isGizmoTarget(e==null?void 0:e.target))return;let i=this.getEventGlobalPoint(e);if(!i)return;let n=new Q(i.x,i.y),a=this.getPickCandidates(n);if(a.length===0){this.setSelected(null),this.lastPickIds=[],this.lastPickIndex=0,this.lastPickPoint=n,this.lastPickTime=performance.now();return}let s=performance.now(),o=this.areSameIds(a,this.lastPickIds),l=this.lastPickPoint&&this.distance(n,this.lastPickPoint)<=6,c=s-this.lastPickTime<1200,d=o&&l&&c?(this.lastPickIndex+1)%a.length:0,u=a[d];this.lastPickIds=a,this.lastPickIndex=d,this.lastPickPoint=n,this.lastPickTime=s,this.setSelected(u)};this.handleGridSettings=e=>{var a,s,o;let t=(a=e==null?void 0:e.detail)==null?void 0:a.enabled,i=(s=e==null?void 0:e.detail)==null?void 0:s.gap,n=(o=e==null?void 0:e.detail)==null?void 0:o.alpha;typeof t=="boolean"&&(this.gridEnabled=t),typeof i=="number"&&Number.isFinite(i)&&i>2&&(this.gridGap=i),typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=1&&(this.gridAlpha=n),this.updateGrid()};this.handlePlayModeChange=e=>{var i;let t=(i=e==null?void 0:e.detail)==null?void 0:i.enabled;typeof t=="boolean"&&(!this.playModeInitialized&&(this.playModeInitialized=!0,!t)||t&&this.applyPlayModeState(!0))};this.syncFromGameObjects=()=>{this.syncFromGameObjectsInternal()};this.onSpawnPointDragMove=e=>{if(!this.spawnPointDrag)return;let t=this.getPointerInContainer(e.clientX,e.clientY,this.mainContainer);if(!t)return;let i=t.x+this.spawnPointDrag.offset.x,n=t.y+this.spawnPointDrag.offset.y;this.updateLiveSpawnPoint(this.spawnPointDrag.objectId,this.spawnPointDrag.index,i,n)};this.onSpawnPointDragEnd=()=>{if(!this.spawnPointDrag)return;let{objectId:e,startPoints:t}=this.spawnPointDrag,i=this.getEditableObjectConfig(e),n=i?this.getSpawnPoints(i):null;i&&n&&(this.setNestedValue(i,"logic.props.spawnPoints",t),Ne({objectId:e,path:"logic.props.spawnPoints",value:n},{persist:!0,emitEvent:!0,trackHistory:!0}),this.queueLiveApply(e)),this.spawnPointDrag=null,window.dispatchEvent(new CustomEvent("inspector:refresh")),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd)};this.onDragMove=e=>{var n;if(!this.dragMode||!this.selectedId||!this.dragContainer||!this.dragStartPointer||!this.dragStartPos)return;let t=this.objectMap.get(this.selectedId);if(!(t!=null&&t.displayObject))return;let i=this.getPointerInContainer(e.clientX,e.clientY,this.dragContainer);if(i){if(this.dragMode==="move"){let a=i.x-this.dragStartPointer.x,s=i.y-this.dragStartPointer.y,o=this.dragStartPos.x+a,l=this.dragStartPos.y+s;t.displayObject.position.set(o,l),this.updateLiveConfigPosition(o,l)}if(this.dragMode==="scale"&&this.dragAnchorLocal){let s=Math.max(1,this.distance(i,this.dragAnchorLocal))/Math.max(1,this.dragStartDistance),o=Math.max(.01,this.dragStartScale*s);(n=t.displayObject.scale)!=null&&n.set?t.displayObject.scale.set(o,o):t.displayObject.scale&&(t.displayObject.scale.x=o,t.displayObject.scale.y=o),this.updateLiveConfigScale(o)}if(this.dragMode==="rotate"&&this.dragAnchorLocal){let a=Math.atan2(i.y-this.dragAnchorLocal.y,i.x-this.dragAnchorLocal.x),s=this.dragStartRotation+(a-this.dragStartAngle);t.displayObject.rotation=s,this.updateLiveConfigRotation(s)}this.queueLiveApply(this.selectedId),this.updateGizmos()}};this.onDragEnd=()=>{var e;if(this.dragMode){if(!this.playModeEnabled&&this.selectedId&&this.dragMode){let t=this.getEditableObjectConfig(this.selectedId),i=(e=t==null?void 0:t.transform)!=null?e:{};this.dragMode==="move"?this.applyFinalOverride(this.selectedId,"transform.position",i.position,this.dragStartValue):this.dragMode==="scale"?this.applyFinalOverride(this.selectedId,"transform.scale",i.scale,this.dragStartValue):this.dragMode==="rotate"&&this.applyFinalOverride(this.selectedId,"transform.rotation",i.rotation,this.dragStartValue)}this.dragMode=null,this.dragStartPointer=null,this.dragStartPos=null,this.dragAnchorLocal=null,this.dragStartValue=null,this.dragContainer=null,window.removeEventListener("pointermove",this.onDragMove),window.removeEventListener("pointerup",this.onDragEnd)}};this.onWheel=e=>{if(!this.app||!this.isVisible)return;e.preventDefault();let i=Math.sign(e.deltaY)<0?1.1:.9,n=Math.min(6,Math.max(.1,this.cameraScale*i)),a=new Q(this.app.renderer.width/2,this.app.renderer.height/2),s=this.camera.toLocal(a);this.cameraScale=n,this.camera.scale.set(n);let o=this.camera.toGlobal(s);this.camera.position.set(this.camera.position.x+(a.x-o.x),this.camera.position.y+(a.y-o.y)),this.hasUserCamera=!0,this.updateGizmos(),this.updateGrid()};this.onPanStart=e=>{e.button===2&&(this.isPanning=!0,this.panStart={x:e.clientX,y:e.clientY},this.panStartCamera={x:this.camera.position.x,y:this.camera.position.y},this.hasUserCamera=!0)};this.onPanMove=e=>{if(!this.isPanning||!this.panStart||!this.panStartCamera)return;let t=e.clientX-this.panStart.x,i=e.clientY-this.panStart.y;this.camera.position.set(this.panStartCamera.x+t,this.panStartCamera.y+i),this.updateGrid()};this.onPanEnd=()=>{this.isPanning=!1,this.panStart=null,this.panStartCamera=null};this.root=e.root,this.getScreen=e.getScreen}async mount(){this.app||(this.app=new $o,await this.app.init({resizeTo:this.root,autoDensity:!0,resolution:window.devicePixelRatio||1,antialias:!0,backgroundAlpha:0}),this.root.innerHTML="",this.root.appendChild(this.app.canvas),this.root.style.position="relative",this.root.style.overflow="hidden",this.app.stage.sortableChildren=!0,this.app.stage.eventMode="static",this.camera.sortableChildren=!0,this.mainContainer.sortableChildren=!0,this.uiContainer.sortableChildren=!0,this.spawnPointLayer.sortableChildren=!0,this.gizmoLayer.sortableChildren=!0,this.app.stage.addChild(this.camera),this.camera.addChild(this.screenFrame),this.camera.addChild(this.mainContainer),this.camera.addChild(this.gridLayer),this.camera.addChild(this.uiContainer),this.camera.addChild(this.spawnPointLayer),this.camera.addChild(this.gameFrame),this.camera.addChild(this.gizmoLayer),this.screenFrame.zIndex=-1,this.screenFrame.eventMode="none",this.mainContainer.zIndex=0,this.gridLayer.zIndex=2e4,this.gridLayer.eventMode="none",this.gridLayer.visible=!0,this.uiContainer.zIndex=5e4,this.spawnPointLayer.zIndex=8e4,this.spawnPointLayer.eventMode="passive",this.gameFrame.zIndex=85e3,this.gameFrame.eventMode="none",this.gizmoLayer.zIndex=1e5,this.gizmoLayer.addChild(this.gizmoOutline),this.gizmoLayer.addChild(this.anchorVisualizationLayer),this.gizmoLayer.addChild(this.moveHandle),this.gizmoLayer.addChild(this.scaleHandle),this.gizmoLayer.addChild(this.rotateHandle),this.gizmoOutline.eventMode="none",this.anchorVisualizationLayer.eventMode="none",this.setupInteractions(),this.setupObservers(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.restoreScenePreferences(),this.refresh(),this.applyPlayModeState(!0),!this.isVisible&&this.app.ticker&&this.app.ticker.stop())}destroy(){var e;this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.screenSyncRaf&&(cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=null),window.removeEventListener("handler-preview:screen",this.handleScreenChange),window.removeEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.removeEventListener("config:changed",this.handleConfigChanged),window.removeEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.removeEventListener("handler:layout-applied",this.handleLayoutApplied),window.removeEventListener("preview:select",this.handlePreviewSelect),window.removeEventListener("scene-editor:grid",this.handleGridSettings),window.removeEventListener("scene-editor:asset-updated",this.handleAssetUpdated),window.removeEventListener("scene-editor:play-mode",this.handlePlayModeChange),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd),this.app&&((e=this.app.ticker)==null||e.remove(this.syncFromGameObjects),this.app.stage.off("pointerdown",this.onStagePointerDown),this.app.destroy(!0),this.app=null)}setVisible(e){this.isVisible=e,!(!this.app||!this.app.ticker)&&(e?(this.app.ticker.start(),this.refresh(),this.updateGrid()):this.app.ticker.stop())}refresh(){this.syncFromConfig()}setupObservers(){window.addEventListener("handler-preview:screen",this.handleScreenChange),window.addEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.addEventListener("config:changed",this.handleConfigChanged),window.addEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.addEventListener("handler:layout-applied",this.handleLayoutApplied),window.addEventListener("preview:select",this.handlePreviewSelect),window.addEventListener("scene-editor:grid",this.handleGridSettings),window.addEventListener("scene-editor:asset-updated",this.handleAssetUpdated),window.addEventListener("scene-editor:play-mode",this.handlePlayModeChange),this.resizeObserver=new ResizeObserver(()=>{this.handleResize()}),this.resizeObserver.observe(this.root)}setupInteractions(){if(!this.app)return;let e=this.app.canvas;e.addEventListener("contextmenu",t=>t.preventDefault()),e.addEventListener("wheel",this.onWheel,{passive:!1}),e.addEventListener("pointerdown",this.onPanStart),window.addEventListener("pointermove",this.onPanMove),window.addEventListener("pointerup",this.onPanEnd),this.app.stage.on("pointerdown",this.onStagePointerDown),this.moveHandle.on("pointerdown",t=>this.startDrag("move",t)),this.scaleHandle.on("pointerdown",t=>this.startDrag("scale",t)),this.rotateHandle.on("pointerdown",t=>this.startDrag("rotate",t)),this.applyEditControls()}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}getPickCandidates(e){var i;let t=[];for(let[n,a]of this.objectMap.entries()){let s=a.displayObject;if(!s||s.visible===!1)continue;let o=(i=s.getBounds)==null?void 0:i.call(s);if(!o||o.width<=0||o.height<=0||e.x<o.x||e.x>o.x+o.width||e.y<o.y||e.y>o.y+o.height)continue;let l=s.parent,c=typeof(l==null?void 0:l.zIndex)=="number"?l.zIndex:0,d=typeof s.zIndex=="number"?s.zIndex:0,u=typeof(l==null?void 0:l.getChildIndex)=="function"?l.getChildIndex(s):0,p=c*1e6+d*1e3+u;t.push({id:n,order:p})}return t.sort((n,a)=>a.order-n.order),t.map(n=>n.id)}areSameIds(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}isGizmoTarget(e){return e&&this.spawnPointLayer.children.indexOf(e)!==-1?!0:e===this.moveHandle||e===this.scaleHandle||e===this.rotateHandle||e===this.gizmoOutline}restoreScenePreferences(){if(typeof window!="undefined"){try{let e=window.localStorage.getItem(this.getSceneStorageKey("grid_enabled")),t=window.localStorage.getItem(this.getSceneStorageKey("grid_gap")),i=window.localStorage.getItem(this.getSceneStorageKey("grid_alpha"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let n=Number(t);Number.isFinite(n)&&n>2&&(this.gridGap=n)}if(i!==null){let n=Number(i);Number.isFinite(n)&&n>=0&&n<=1&&(this.gridAlpha=n)}}catch{}this.updateGrid()}}getSceneStorageKey(e){let t=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${e}::${t}`}applyPlayModeState(e){var t;this.playModeEnabled=e,(t=this.app)!=null&&t.ticker&&(this.app.ticker.remove(this.syncFromGameObjects),e&&this.app.ticker.add(this.syncFromGameObjects)),this.applyEditControls(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.playModeEnabled&&this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid()})}applyEditControls(){this.moveHandle.eventMode="static",this.scaleHandle.eventMode="static",this.rotateHandle.eventMode="static"}schedulePostScreenSync(e){this.screenSyncRaf&&cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=requestAnimationFrame(()=>{this.runPostScreenSync(e)})}async runPostScreenSync(e){this.screenSyncRaf=null,this.isVisible&&this.playModeEnabled&&(this.updateLayout(e),this.hasUserCamera||this.centerCamera(),await this.syncFromConfig(),this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid())}getRuntimeScreenSize(){var a,s,o,l,c,d,u;let e=window.gameApp;if(e!=null&&e.renderer){let p=e.renderer.screen,g=Number((a=p==null?void 0:p.width)!=null?a:0),h=Number((s=p==null?void 0:p.height)!=null?s:0);if(Number.isFinite(g)&&g>0&&Number.isFinite(h)&&h>0)return{width:g,height:h};let m=Number((o=e.renderer.resolution)!=null?o:1)||1,f=Number((l=e.renderer.width)!=null?l:0)/m,b=Number((c=e.renderer.height)!=null?c:0)/m;if(Number.isFinite(f)&&f>0&&Number.isFinite(b)&&b>0)return{width:f,height:b}}let t=document.querySelector(".game-container"),i=Number((d=t==null?void 0:t.dataset)==null?void 0:d.screenWidth),n=Number((u=t==null?void 0:t.dataset)==null?void 0:u.screenHeight);return Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:null}getRuntimeLayoutReference(){var a,s,o,l,c,d,u,p,g,h,m,f,b,y,v,S,L,j,_,E,M,I,k,T,A,C,w,x,O,P,R,z,F,G;let e=window.__mainContainer;if(e){let H=(s=(a=e.scale)==null?void 0:a.x)!=null?s:1,B=(l=(o=e.scale)==null?void 0:o.y)!=null?l:H;return console.log("[SceneEditor] getRuntimeLayoutReference: using __mainContainer",{scale:{x:H,y:B},position:{x:(c=e.position)==null?void 0:c.x,y:(d=e.position)==null?void 0:d.y}}),e}let t=window.__screenManager;if(t){let H=["gameplay","start","tutorial","endgame","loading"];for(let B of H){let $=(u=t.get)==null?void 0:u.call(t,B);if($!=null&&$.visible){let U=(p=$.getContentLayer)==null?void 0:p.call($);if(U){let X=(g=$.x)!=null?g:0,se=(h=$.y)!=null?h:0,N=(m=U.x)!=null?m:0,ee=(f=U.y)!=null?f:0,J=(y=(b=U.scale)==null?void 0:b.x)!=null?y:1,ae=(S=(v=U.scale)==null?void 0:v.y)!=null?S:J;return console.log("[SceneEditor] getRuntimeLayoutReference: using visible screen contentLayer",{screenId:B,contentLayerScale:{x:J,y:ae},position:{x:X+N,y:se+ee}}),{scale:{x:J,y:ae},position:{x:X+N,y:se+ee},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}for(let B of H){let $=(L=t.get)==null?void 0:L.call(t,B);if($){if(!$.visible&&typeof $.updateLayout=="function"){let X=window.gameApp;if((j=X==null?void 0:X.renderer)!=null&&j.screen){let se=X.renderer.screen.width,N=X.renderer.screen.height;se>0&&N>0&&$.updateLayout(se,N)}}let U=(_=$.getContentLayer)==null?void 0:_.call($);if(U){let X=(E=$.x)!=null?E:0,se=(M=$.y)!=null?M:0,N=(I=U.x)!=null?I:0,ee=(k=U.y)!=null?k:0,J=(A=(T=U.scale)==null?void 0:T.x)!=null?A:1,ae=(w=(C=U.scale)==null?void 0:C.y)!=null?w:J;return console.log("[SceneEditor] getRuntimeLayoutReference: using any screen contentLayer",{screenId:B,visible:$.visible,contentLayerScale:{x:J,y:ae},position:{x:X+N,y:se+ee}}),{scale:{x:J,y:ae},position:{x:X+N,y:se+ee},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}}let i=window.gameApp,n=(x=i==null?void 0:i.stage)!=null?x:null;if(n){let H=(P=(O=n.scale)==null?void 0:O.x)!=null?P:1,B=(z=(R=n.scale)==null?void 0:R.y)!=null?z:H;console.log("[SceneEditor] getRuntimeLayoutReference: using gameApp.stage (fallback)",{scale:{x:H,y:B},position:{x:(F=n.position)==null?void 0:F.x,y:(G=n.position)==null?void 0:G.y}})}else console.log("[SceneEditor] getRuntimeLayoutReference: no reference found");return n}getRuntimeParentContainer(e){var l,c;let t=window.gameObjectManager;if(!(t!=null&&t.get))return null;let i=t.get(e),n=((l=i==null?void 0:i.getDisplayObject)==null?void 0:l.call(i))||(i==null?void 0:i.pixiObject)||i,a=n==null?void 0:n.parent;if(!a)return null;let s=this.getRuntimeLayoutReference(),o=(c=window.gameApp)==null?void 0:c.stage;return s&&o&&s===o?this.mainContainer:s&&typeof s.contains=="function"&&s.contains(a)?this.mainContainer:a===s||a===o?this.mainContainer:this.uiContainer}applyRuntimeTransform(e){var s,o,l,c,d,u,p,g,h,m;if(!e)return console.log("[SceneEditor] applyRuntimeTransform: no reference"),!1;let t=1,i=1,n=Number((o=(s=e.position)==null?void 0:s.x)!=null?o:0),a=Number((c=(l=e.position)==null?void 0:l.y)!=null?c:0);if(!Number.isFinite(n)||!Number.isFinite(a))return console.log("[SceneEditor] applyRuntimeTransform: invalid position",{posX:n,posY:a}),!1;if(console.log("[SceneEditor] applyRuntimeTransform: applying (scale always 1)",{scale:{x:t,y:i},position:{x:n,y:a}}),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.position.set(n,a),this.uiContainer.position.set(n,a),e.pivot&&((d=this.mainContainer.pivot)!=null&&d.set)&&((u=this.uiContainer.pivot)!=null&&u.set)){let f=Number((g=(p=e.pivot)==null?void 0:p.x)!=null?g:0),b=Number((m=(h=e.pivot)==null?void 0:h.y)!=null?m:0);Number.isFinite(f)&&Number.isFinite(b)&&(this.mainContainer.pivot.set(f,b),this.uiContainer.pivot.set(f,b))}return typeof e.rotation=="number"&&(this.mainContainer.rotation=e.rotation,this.uiContainer.rotation=e.rotation),!0}getEditableConfig(){return window.__editableConfig||null}getEditableObjectConfig(e){var n,a;let t=window.getEditableObjectConfig;if(typeof t=="function")return t(e);let i=this.getEditableConfig();return i!=null&&i.objects?typeof i.objects.get=="function"?(n=i.objects.get(e))!=null?n:null:(a=i.objects[e])!=null?a:null:null}getEditableObjectIds(){let e=window.getEditableObjectList;if(typeof e=="function"){let i=e();if(Array.isArray(i))return i}let t=this.getEditableConfig();return t!=null&&t.objects?typeof t.objects.keys=="function"?Array.from(t.objects.keys()):Object.keys(t.objects):[]}async syncFromConfig(e){if(!this.app)return;let t=this.getEditableConfig();if(!(t!=null&&t.objects))return;let i=e!=null&&e.length?e:this.getEditableObjectIds(),n=new Set(i);if(!e)for(let a of Array.from(this.objectMap.keys()))n.has(a)||this.removeObject(a);for(let a of i){let s=this.getEditableObjectConfig(a);if(!s){this.removeObject(a);continue}await this.upsertObject(a,s)}this.updateGizmos(),this.updateSpawnPointHandles(),this.updateGameFrame(this.getScreen())}removeObject(e){var i,n;let t=this.objectMap.get(e);if(t){try{(n=(i=t.displayObject)==null?void 0:i.destroy)==null||n.call(i)}catch{}this.objectMap.delete(e),this.selectedId===e&&this.setSelected(null,{silent:!0})}}async upsertObject(e,t){let i=this.getAssetKey(t),n=this.objectMap.get(e),a=this.isUiConfig(e,t),s=this.playModeEnabled?this.getRuntimeParentContainer(e):null,o=a?this.uiContainer:this.mainContainer,l=s!=null?s:o;if(!n||n.assetKey!==i||n.isUi!==a){n&&this.removeObject(e);let d=await this.createDisplayObject(e,t);if(!d)return;l.addChild(d),this.objectMap.set(e,{id:e,displayObject:d,assetKey:i,isUi:a}),this.attachObjectInteraction(d,e)}let c=this.objectMap.get(e);c&&(c.displayObject.parent!==l&&l.addChild(c.displayObject),this.applyVisualConfig(c.displayObject,t),this.playModeEnabled||this.applyTransformFromConfig(e,c.displayObject,t))}async createDisplayObject(e,t){var o,l,c,d,u,p,g,h,m,f,b,y,v,S,L;if((o=t==null?void 0:t.render)!=null&&o.asset)try{if(((c=(l=t==null?void 0:t.render)==null?void 0:l.asset)==null?void 0:c.type)!=="json"){let _=await Te.create(e,t,this.app);if(_ instanceof Ye)return _}}catch(j){console.warn("[SceneEditor] ObjectFactory failed for",e,j)}let i=t==null?void 0:t.ui,n=(d=t==null?void 0:t.render)!=null?d:{},a=(i==null?void 0:i.text)||(i==null?void 0:i.kind)==="text";if(!!n.background_color){let j=this.getScreen(),_=(u=j==null?void 0:j.width)!=null?u:0,E=(p=j==null?void 0:j.height)!=null?p:0,M=new xe,I=this.parseColor(n.background_color,0),k=typeof n.background_alpha=="number"?n.background_alpha:1;_>0&&E>0&&M.rect(0,0,_,E).fill({color:I,alpha:k});let T=new Ye;return T.addChild(M),T}if(a){let j=(h=(g=i==null?void 0:i.color)!=null?g:n==null?void 0:n.tint)!=null?h:"#ffffff",_=new No({fontFamily:"Arial, sans-serif",fontSize:(m=i==null?void 0:i.fontSize)!=null?m:16,fill:j,align:(f=i==null?void 0:i.align)!=null?f:"center",letterSpacing:(b=i==null?void 0:i.letterSpacing)!=null?b:0});return new Ho({text:(y=i==null?void 0:i.text)!=null?y:"",style:_})}if((v=t==null?void 0:t.effects)!=null&&v.width||(S=t==null?void 0:t.effects)!=null&&S.height){let j=new xe,_=typeof t.effects.width=="number"?t.effects.width:100,E=typeof t.effects.height=="number"?t.effects.height:100,M=(L=t.effects.fill_color)!=null?L:"#ffffff",I=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,k=Number.parseInt(String(M).replace("#",""),16);return j.rect(0,0,_,E).fill({color:Number.isFinite(k)?k:16777215,alpha:I}),j}return new Ye}attachObjectInteraction(e,t){if(e&&(e.eventMode="static",e.cursor="pointer",!e.hitArea&&typeof e.getLocalBounds=="function")){let i=e.getLocalBounds();i&&i.width>0&&i.height>0&&(e.hitArea=new hr(i.x,i.y,i.width,i.height))}}getAssetKey(e){var i;let t=(i=e==null?void 0:e.render)==null?void 0:i.asset;return t?`${t.type||"asset"}::${t.path||""}`:null}isUiConfig(e,t){var a,s;let i=(((a=t==null?void 0:t.identity)==null?void 0:a.category)||"").toString().toLowerCase(),n=(((s=t==null?void 0:t.identity)==null?void 0:s.id)||e||"").toString().toLowerCase();return i.includes("ui")||n.startsWith("ui")||n.includes("label")}applyVisualConfig(e,t){var s,o,l,c,d,u,p,g,h;if(!e)return;let i=(s=t==null?void 0:t.render)!=null?s:{};typeof i.alpha=="number"&&(e.alpha=i.alpha),e.visible=i.visible!==!1,e.zIndex=typeof i.z_index=="number"?i.z_index:0;let n=(d=(c=(o=t==null?void 0:t.render)==null?void 0:o.anchor)!=null?c:(l=t==null?void 0:t.transform)==null?void 0:l.anchor)!=null?d:"top-right";n==="top-right"&&!((u=t==null?void 0:t.render)!=null&&u.anchor)&&!((p=t==null?void 0:t.transform)!=null&&p.anchor)&&console.log("[DEBUG FALLBACK] applyVisualConfig (SceneEditor) \u2192 top-right");let a=ye(n,{x:.5,y:.5});if((g=e.anchor)!=null&&g.set)e.anchor.set(a.x,a.y);else if(e.pivot){let m=(h=e.getLocalBounds)==null?void 0:h.call(e);m&&e.pivot.set(m.width*a.x,m.height*a.y)}}applyTransformFromConfig(e,t,i){var _,E,M,I,k,T,A,C,w,x,O;if(!t)return;let n=this.getScreen();if(!(n!=null&&n.width)||!(n!=null&&n.height))return;let a=(_=i==null?void 0:i.transform)!=null?_:{},s=this.getPositioningAnchor(e,a),o=a==null?void 0:a.position_ratio,l=a==null?void 0:a.position,c=a==null?void 0:a.offset,d=Array.isArray(l)?Number((E=l[0])!=null?E:0):Number((M=l==null?void 0:l.x)!=null?M:0),u=Array.isArray(l)?Number((I=l[1])!=null?I:0):Number((k=l==null?void 0:l.y)!=null?k:0),p=Array.isArray(c)?Number((T=c[0])!=null?T:0):Number((A=c==null?void 0:c.x)!=null?A:0),g=Array.isArray(c)?Number((C=c[1])!=null?C:0):Number((w=c==null?void 0:c.y)!=null?w:0),h=(Number.isFinite(d)?d:0)+(Number.isFinite(p)?p:0),m=(Number.isFinite(u)?u:0)+(Number.isFinite(g)?g:0),f=o!=null?Ge(n.width,n.height,o):Ue(n.width,n.height,s),b=Number.isFinite(this.layoutScale)&&this.layoutScale>0?this.layoutScale:1,y=(f.x-n.width/2)/b+h,v=(f.y-n.height/2)/b+m;(x=t.position)!=null&&x.set?t.position.set(y,v):t.position&&(t.position.x=y,t.position.y=v);let L=(typeof(a==null?void 0:a.scale)=="number"?a.scale:1)*(Number.isFinite(this.layoutScale)&&this.layoutScale>0?this.layoutScale:1);(O=t.scale)!=null&&O.set?t.scale.set(L,L):t.scale&&(t.scale.x=L,t.scale.y=L);let j=typeof(a==null?void 0:a.rotation)=="number"?a.rotation:0;t.rotation=this.toRadians(j)}getAnchorLocalPoint(e,t=this.mainContainer){var d;let i=this.playModeEnabled?(d=this.getScreen())!=null?d:this.getRuntimeScreenSize():this.getScreen();if(!(i!=null&&i.width)||!(i!=null&&i.height))return null;let n="top-right",a=this.getPositioningAnchor(this.selectedId,e!=null?e:{}),s=(e==null?void 0:e.position_ratio)!=null?Ge(i.width,i.height,e.position_ratio):Ue(i.width,i.height,a!=null?a:n),o=Number.isFinite(this.layoutScale)&&this.layoutScale>0?this.layoutScale:1,l=(s.x-i.width/2)/o,c=(s.y-i.height/2)/o;return new Q(l,c)}getPositioningAnchor(e,t){var i,n,a;if((t==null?void 0:t.anchor)!=null&&t.anchor!=="")return t.anchor;if(typeof window!="undefined"&&e){let o=window.__editableConfigBaseline,l=(n=(i=o==null?void 0:o.objects)==null?void 0:i.get)==null?void 0:n.call(i,e),c=(a=l==null?void 0:l.transform)==null?void 0:a.anchor;if(c!=null&&c!=="")return c}return"top-left"}updateLayout(e){var i,n,a,s,o,l,c,d,u;let t=e!=null?e:this.getScreen();if(!(!(t!=null&&t.width)||!(t!=null&&t.height))){if(console.log("[SceneEditor] updateLayout: called",{screen:{width:t.width,height:t.height},currentScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}}),this.playModeEnabled){let p=this.getRuntimeLayoutReference();if(p){let g=Number((n=(i=p.position)==null?void 0:i.x)!=null?n:t.width/2),h=Number((s=(a=p.position)==null?void 0:a.y)!=null?s:t.height/2);this.mainContainer.position.set(g,h),this.uiContainer.position.set(g,h);let m=Number((l=(o=p.scale)==null?void 0:o.x)!=null?l:1);Number.isFinite(m)&&m>0&&(this.layoutScale=m)}this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1)}else this.mainContainer.position.set(t.width/2,t.height/2),this.uiContainer.position.set(t.width/2,t.height/2),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.rotation=0,this.uiContainer.rotation=0,(c=this.mainContainer.pivot)!=null&&c.set&&this.mainContainer.pivot.set(0,0),(d=this.uiContainer.pivot)!=null&&d.set&&this.uiContainer.pivot.set(0,0);console.log("[SceneEditor] updateLayout: result",{finalScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y},position:{x:this.mainContainer.position.x,y:this.mainContainer.position.y}}),this.screenFrame.clear(),this.screenFrame.rect(0,0,t.width,t.height),this.screenFrame.stroke({width:2,color:2894892,alpha:.5}),this.updateGameFrame(t),(u=this.app)!=null&&u.stage&&(this.app.stage.hitArea=new hr(0,0,this.app.renderer.width,this.app.renderer.height)),this.updateSpawnPointHandles()}}updateGrid(){if(!this.app)return;if(!this.gridEnabled){this.gridLayer.clear(),this.gridLayer.visible=!0;return}let e=Math.max(4,this.gridGap),t=this.app.renderer,i=this.camera.toLocal(new Q(0,0)),n=this.camera.toLocal(new Q(t.width,t.height)),a=Math.min(i.x,n.x),s=Math.max(i.x,n.x),o=Math.min(i.y,n.y),l=Math.max(i.y,n.y),c=400,d=Math.ceil((s-a)/e),u=Math.ceil((l-o)/e),p=e*Math.max(1,Math.ceil(d/c)),g=e*Math.max(1,Math.ceil(u/c)),h=Math.floor(a/p)*p,m=Math.floor(o/g)*g;this.gridLayer.clear(),this.gridLayer.visible=!0;for(let f=h;f<=s;f+=p)this.gridLayer.moveTo(f,o),this.gridLayer.lineTo(f,l);for(let f=m;f<=l;f+=g)this.gridLayer.moveTo(a,f),this.gridLayer.lineTo(s,f);this.gridLayer.stroke({width:1,color:16777215,alpha:this.gridAlpha})}updateGameFrame(e){var o;let t=this.playModeEnabled?(o=e!=null?e:this.getScreen())!=null?o:this.getRuntimeScreenSize():e!=null?e:this.getScreen();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;let i=t.width,n=t.height,a=0,s=0;this.lastGameFrameSize&&this.lastGameFrameSize.width===t.width&&this.lastGameFrameSize.height===t.height||(this.lastGameFrameSize={width:t.width,height:t.height},this.gameFrame.clear(),this.gameFrame.rect(a,s,i,n),this.gameFrame.stroke({width:2,color:6333946,alpha:.35}))}syncFromGameObjectsInternal(){var i,n,a,s,o,l,c,d;if(!this.app||!this.isVisible)return;let e=window.gameObjectManager;if(!(e!=null&&e.get))return;let t=this.dragMode?this.selectedId:null;for(let[u,p]of this.objectMap.entries()){if(t&&u===t)continue;let g=e.get(u),h=((i=g==null?void 0:g.getDisplayObject)==null?void 0:i.call(g))||(g==null?void 0:g.pixiObject)||g;if(!h)continue;let m=(a=(n=p.displayObject)==null?void 0:n.parent)!=null?a:this.mainContainer,f=new Q;if(typeof h.getGlobalPosition=="function"){h.getGlobalPosition(f);let L=m.toLocal(f,this.camera);p.displayObject.position.set(L.x,L.y)}else if(h.worldTransform){f.set(h.worldTransform.tx,h.worldTransform.ty);let L=m.toLocal(f,this.camera);p.displayObject.position.set(L.x,L.y)}let b=this.getWorldScale(h);if(b){let L=Number((o=(s=m.scale)==null?void 0:s.x)!=null?o:1)||1,j=Number((c=(l=m.scale)==null?void 0:l.y)!=null?c:1)||1,_=b.x/L,E=b.y/j;(d=p.displayObject.scale)!=null&&d.set?p.displayObject.scale.set(_,E):p.displayObject.scale&&(p.displayObject.scale.x=_,p.displayObject.scale.y=E)}let y=this.getWorldRotation(h);if(typeof y=="number"){let L=m?m.rotation:0;p.displayObject.rotation=y-L}let v=h.parent,S=typeof(v==null?void 0:v.getChildIndex)=="function"?v.getChildIndex(h):0;typeof h.zIndex=="number"?p.displayObject.zIndex=h.zIndex:Number.isFinite(S)&&(p.displayObject.zIndex=S)}this.updateGizmos()}getWorldScale(e){var a,s;let t=(s=e==null?void 0:e.worldTransform)!=null?s:(a=e==null?void 0:e.transform)==null?void 0:a.worldTransform;if(!t)return null;let i=Math.sqrt(t.a*t.a+t.b*t.b),n=Math.sqrt(t.c*t.c+t.d*t.d);return!Number.isFinite(i)||!Number.isFinite(n)?null:{x:i,y:n}}getWorldRotation(e){var i,n;let t=(n=e==null?void 0:e.worldTransform)!=null?n:(i=e==null?void 0:e.transform)==null?void 0:i.worldTransform;if(t){let a=Math.atan2(t.b,t.a);return Number.isFinite(a)?a:null}return typeof(e==null?void 0:e.rotation)=="number"?e.rotation:null}centerCamera(){var a;if(!this.app)return;let e=this.playModeEnabled?(a=this.getScreen())!=null?a:this.getRuntimeScreenSize():this.getScreen();if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=this.app.renderer.width,i=this.app.renderer.height,n=Math.max(.01,Math.min(t/e.width,i/e.height));this.cameraScale=n,this.camera.scale.set(n),this.camera.position.set((t-e.width*n)/2,(i-e.height*n)/2)}updateGizmos(){var m,f;if(!this.selectedId||!this.isVisible){this.clearGizmos();return}let e=this.objectMap.get(this.selectedId);if(!(e!=null&&e.displayObject)){this.clearGizmos();return}let t=(f=(m=e.displayObject).getBounds)==null?void 0:f.call(m);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let i=this.camera.toLocal(new Q(t.x,t.y)),n=this.camera.toLocal(new Q(t.x+t.width,t.y+t.height)),a=n.x-i.x,s=n.y-i.y,o=i.x+a/2,l=i.y+s/2;this.gizmoOutline.clear(),this.gizmoOutline.rect(i.x,i.y,a,s),this.gizmoOutline.stroke({width:2,color:16752394,alpha:.9});let c=7,d={width:2,color:988970,alpha:.6};this.moveHandle.clear(),this.moveHandle.circle(o,l,c).fill({color:2278750,alpha:.95}),this.moveHandle.stroke(d),this.moveHandle.cursor="move";let u=i.x+a,p=i.y+s;this.scaleHandle.clear(),this.scaleHandle.rect(u-c,p-c,c*2,c*2).fill({color:3718648,alpha:.95}),this.scaleHandle.stroke(d),this.scaleHandle.cursor="nwse-resize";let g=o,h=i.y-c*2;this.rotateHandle.clear(),this.rotateHandle.circle(g,h,c).fill({color:16347926,alpha:.95}),this.rotateHandle.stroke(d),this.rotateHandle.cursor="crosshair"}clearGizmos(){this.gizmoOutline.clear(),this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear()}updateSpawnPointHandles(){if(this.clearSpawnPointHandles(),!this.selectedId)return;let e=this.getEditableObjectConfig(this.selectedId);if(!e||!this.isSpawnerConfig(e))return;let t=this.getSpawnPoints(e);!t||t.length===0||t.forEach((i,n)=>{let a=new xe;a.circle(0,0,5).fill({color:16096779,alpha:.9}),a.circle(0,0,9).stroke({width:1,color:16096779,alpha:.45});let s=this.toCameraFromMain(i);a.position.set(s.x,s.y),a.cursor="move",a.eventMode="static",a.on("pointerdown",o=>this.startSpawnPointDrag(n,o)),this.spawnPointLayer.addChild(a)})}clearSpawnPointHandles(){this.spawnPointLayer.removeChildren().forEach(t=>{var i;(i=t.destroy)==null||i.call(t)})}isSpawnerConfig(e){var i,n;return((i=e==null?void 0:e.logic)==null?void 0:i.id)==="Spawner"?!0:String(((n=e==null?void 0:e.identity)==null?void 0:n.system_role)||"").toLowerCase().includes("spawner")}getSpawnPoints(e){var i,n;let t=(n=(i=e==null?void 0:e.logic)==null?void 0:i.props)==null?void 0:n.spawnPoints;return Array.isArray(t)?t.map(a=>{var s,o;return{x:Number((s=a==null?void 0:a.x)!=null?s:0),y:Number((o=a==null?void 0:a.y)!=null?o:0)}}):null}toCameraFromMain(e){let t=this.mainContainer.toGlobal(new Q(e.x,e.y)),i=new Q;return this.camera.toLocal(t,void 0,i),i}startSpawnPointDrag(e,t){var o,l;if(!this.selectedId)return;let i=this.getEditableObjectConfig(this.selectedId);if(!i)return;let n=this.getSpawnPoints(i);if(!n||!n[e])return;(o=t==null?void 0:t.stopPropagation)==null||o.call(t),(l=t==null?void 0:t.stopImmediatePropagation)==null||l.call(t);let a=this.getEventLocalPoint(t,this.mainContainer);if(!a)return;let s=n[e];this.spawnPointDrag={objectId:this.selectedId,index:e,offset:new Q(s.x-a.x,s.y-a.y),startPoints:n.map(c=>({x:c.x,y:c.y}))},window.addEventListener("pointermove",this.onSpawnPointDragMove),window.addEventListener("pointerup",this.onSpawnPointDragEnd)}updateLiveSpawnPoint(e,t,i,n){let a=this.getEditableObjectConfig(e);if(!a)return;let s=this.getSpawnPoints(a);if(!s||!s[t])return;let o=s.map((l,c)=>c===t?{x:i,y:n}:{x:l.x,y:l.y});this.setNestedValue(a,"logic.props.spawnPoints",o),this.queueLiveApply(e),this.updateSpawnPointHandles()}setSelected(e,t={}){if(this.selectedId!==e&&(this.selectedId=e,this.updateGizmos(),this.updateSpawnPointHandles(),!t.silent&&e)){let i=window.__previewSelectObject;typeof i=="function"&&i(e)}}startDrag(e,t){var l,c,d,u,p;if(!this.selectedId)return;let i=this.objectMap.get(this.selectedId);if(!(i!=null&&i.displayObject))return;let n=this.getEditableObjectConfig(this.selectedId);if(!n)return;let a=(l=n.transform)!=null?l:{},s=(c=i.displayObject.parent)!=null?c:this.mainContainer,o=this.getEventLocalPoint(t,s);o&&((d=t==null?void 0:t.stopPropagation)==null||d.call(t),(u=t==null?void 0:t.stopImmediatePropagation)==null||u.call(t),this.dragMode=e,this.dragContainer=s,this.dragStartPointer=new Q(o.x,o.y),this.dragStartPos=new Q(i.displayObject.position.x,i.displayObject.position.y),this.dragStartScale=typeof((p=i.displayObject.scale)==null?void 0:p.x)=="number"?i.displayObject.scale.x:1,this.dragStartRotation=typeof i.displayObject.rotation=="number"?i.displayObject.rotation:0,this.dragAnchorLocal=this.getAnchorLocalPoint(a,s),this.dragStartValue=this.getDragStartValue(e,a),this.dragAnchorLocal&&(this.dragStartAngle=Math.atan2(o.y-this.dragAnchorLocal.y,o.x-this.dragAnchorLocal.x),this.dragStartDistance=Math.max(1,this.distance(o,this.dragAnchorLocal))),window.addEventListener("pointermove",this.onDragMove),window.addEventListener("pointerup",this.onDragEnd))}getDragStartValue(e,t){var i,n,a;return e==="move"?(i=t==null?void 0:t.position)!=null?i:{x:0,y:0}:e==="scale"?(n=t==null?void 0:t.scale)!=null?n:1:e==="rotate"?(a=t==null?void 0:t.rotation)!=null?a:0:null}updateLiveConfigPosition(e,t){var u,p,g,h,m,f;if(!this.selectedId||!this.dragAnchorLocal)return;let i=e-this.dragAnchorLocal.x,n=t-this.dragAnchorLocal.y,a=this.getEditableObjectConfig(this.selectedId);if(!a)return;let s=(u=a.transform)!=null?u:{};a.transform||(a.transform=s);let o=(p=s.offset)!=null?p:{x:0,y:0},l=Array.isArray(o)?Number((g=o[0])!=null?g:0):Number((h=o==null?void 0:o.x)!=null?h:0),c=Array.isArray(o)?Number((m=o[1])!=null?m:0):Number((f=o==null?void 0:o.y)!=null?f:0),d=this.buildPositionValue(s,{x:i-l,y:n-c});this.setNestedValue(s,"position",d)}updateLiveConfigScale(e){var n;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(n=t.transform)!=null?n:{};t.transform||(t.transform=i),i.scale=Math.round(e*100)/100}updateLiveConfigRotation(e){var s;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(s=t.transform)!=null?s:{};t.transform||(t.transform=i);let n=this.toDegrees(e),a=typeof i.rotation=="number"?i.rotation:0;Math.abs(n-a)>.01&&(i.rotation=Math.round(n*100)/100)}applyFinalOverride(e,t,i,n){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),n),Ne({objectId:e,path:t,value:i},{persist:!0,emitEvent:!0,trackHistory:!0})}queueLiveApply(e){this.applyQueuedId=e,!this.applyQueued&&(this.applyQueued=!0,requestAnimationFrame(()=>{this.applyQueued=!1;let t=this.applyQueuedId;if(!t)return;let i=this.getEditableObjectConfig(t),n=window.applyEditableObjectConfig;typeof n=="function"&&i&&(n(t,i),window.dispatchEvent(new CustomEvent("inspector:refresh")))}))}setNestedValue(e,t,i){let n=t.split("."),a=e;for(let s=0;s<n.length-1;s+=1){let o=n[s];(!a[o]||typeof a[o]!="object")&&(a[o]={}),a=a[o]}a[n[n.length-1]]=i}buildPositionValue(e,t){let i=e==null?void 0:e.position,n=Math.round(t.x*100)/100,a=Math.round(t.y*100)/100;return Array.isArray(i)?[n,a]:{x:n,y:a}}toRadians(e){return e*Math.PI/180}toDegrees(e){return e*180/Math.PI}distance(e,t){let i=e.x-t.x,n=e.y-t.y;return Math.sqrt(i*i+n*n)}getPointerButton(e){var t,i,n;return typeof(e==null?void 0:e.button)=="number"?e.button:typeof((t=e==null?void 0:e.data)==null?void 0:t.button)=="number"?e.data.button:typeof((n=(i=e==null?void 0:e.data)==null?void 0:i.originalEvent)==null?void 0:n.button)=="number"?e.data.originalEvent.button:0}getEventGlobalPoint(e){var l,c;let t=(c=e==null?void 0:e.global)!=null?c:(l=e==null?void 0:e.data)==null?void 0:l.global;if(t)return new Q(t.x,t.y);if(!this.app)return null;let i=e==null?void 0:e.clientX,n=e==null?void 0:e.clientY;if(typeof i!="number"||typeof n!="number")return null;let a=this.app.canvas.getBoundingClientRect(),s=(i-a.left)*(this.app.renderer.width/a.width),o=(n-a.top)*(this.app.renderer.height/a.height);return new Q(s,o)}getEventLocalPoint(e,t=this.mainContainer){var a,s;if(!this.app)return null;if(typeof(e==null?void 0:e.getLocalPosition)=="function"){let o=e.getLocalPosition(t);return new Q(o.x,o.y)}let i=(s=e==null?void 0:e.global)!=null?s:(a=e==null?void 0:e.data)==null?void 0:a.global;if(!i)return null;let n=new Q;return t.toLocal(new Q(i.x,i.y),void 0,n),n}getPointerInContainer(e,t,i){if(!this.app)return null;let n=this.app.canvas.getBoundingClientRect(),a=(e-n.left)*(this.app.renderer.width/n.width),s=(t-n.top)*(this.app.renderer.height/n.height),o=new Q;return i.toLocal(new Q(a,s),void 0,o),o}parseColor(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=e.trim().replace("#",""),n=Number.parseInt(i,16);if(Number.isFinite(n))return n}return t}};var Vn=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[ct("playable-portrait"),ct("iphone-14"),ct("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.isSpaceKeyPressed=!1;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.originalConsole={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console)};this.sceneEditor=null;this.sceneVisiblePreference=!0;this.sceneVisible=!0;this.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.hasUnsavedChanges=!1;this.hasForceSynced=!1;this.onWindowResize=e=>{if(this.ignoreNextWindowResize){this.ignoreNextWindowResize=!1;return}this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()};this.onFrameDragMove=e=>{if(!this.frameDragActive)return;let t=e.clientX-this.frameDragStartX,i=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+i,this.applyFrameDrag(),this.updateDragCursor()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd),this.updateDragCursor())};this.options=e,this.currentPreset=ct(e.defaultDevice||un.id),this.debugPanel=new Bi,this.container=this.createShell(),this.previewContainer=this.mustQuery(".preview-container"),this.singleStage=this.mustQuery('[data-preview-stage="single"]'),this.compareStage=this.mustQuery('[data-preview-stage="compare"]'),this.frameDragger=this.mustQuery(".frame-dragger"),this.frameWrapper=this.mustQuery(".frame-wrapper"),this.deviceFrame=this.mustQuery(".device-frame"),this.gameContainer=this.mustQuery(".game-container"),this.scenePane=this.mustQuery("[data-scene-pane]"),this.sceneRoot=this.mustQuery("#scene-editor-root"),this.sceneSplitter=this.mustQuery("[data-scene-splitter]"),this.gameViewPane=this.mustQuery("[data-game-pane]"),this.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners();try{let i=window.localStorage.getItem(this.getSceneVisibilityStorageKey());this.sceneVisiblePreference=i===null?!0:i==="true"}catch{}let t="dark";try{let i=window.localStorage.getItem(this.getThemeStorageKey());(i==="light"||i==="dark")&&(t=i)}catch{}this.setTheme(t),this.sceneEditor=new Ui({root:this.sceneRoot,getScreen:()=>this.getScreen()}),this.sceneEditor.mount(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setupShortcutListeners(),this.setupUnsavedChangesIndicator(),this.setupScenePaneInteractions(),this.updateSceneVisibility(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.updateDockState(),this.isInitialized=!0,this.scheduleForceSync()}getShortcutKey(){return typeof navigator!="undefined"&&navigator.platform.toUpperCase().indexOf("MAC")>=0?"CMD":"CTRL"}mount(e=document.body){e.innerHTML="",e.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}scheduleForceSync(){this.hasForceSynced||(this.hasForceSynced=!0,window.setTimeout(()=>{let e=window.__HANDLER_ACTIVE_SCREEN;fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"})}).catch(i=>{console.warn("[PreviewShell] Force sync on refresh failed:",i)})},250))}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1,this.sceneEditor&&(this.sceneEditor.destroy(),this.sceneEditor=null)}getGameContainer(){return this.gameContainer}getScreen(){let e=this.getEffectivePreset();return{width:e.width,height:e.height}}getEffectivePreset(){var e;return this.isLandscape?{...this.currentPreset,width:this.currentPreset.height,height:this.currentPreset.width,ratio:((e=this.currentPreset.ratio)==null?void 0:e.split(":").reverse().join(":"))||this.currentPreset.ratio}:this.currentPreset}notifyGameLoaded(){var e;this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh(),(e=this.sceneEditor)==null||e.refresh(),requestAnimationFrame(()=>this.updatePanelPositions())}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(e,t={}){var n,a;let i=this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=ct(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:i}),t.suppressCallback||(a=(n=this.options).onDeviceChange)==null||a.call(n,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark");try{window.localStorage.setItem(this.getThemeStorageKey(),e)}catch{}let t=this.container.querySelector("#theme-select");t&&(t.value=e),requestAnimationFrame(()=>this.updatePanelPositions())}setLayoutMode(e){if(this.layoutMode===e)return;this.layoutMode=e,this.container.classList.toggle("layout-fixed",e==="fixed"),this.container.classList.toggle("layout-draggable",e==="draggable"),Array.from(this.container.querySelectorAll("[data-layout-toggle]")).forEach(n=>n.classList.toggle("active",n.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(n=>{n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),this.updateSceneVisibility(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}updateDockState(){let e=this.container.querySelector("#bottom-dock");e==null||e.classList.remove("hidden");let t=this.container.querySelector("#console-messages"),i=this.container.querySelector("#dock-console-content");t&&i&&t.parentElement!==i&&i.appendChild(t)}makeBottomDockResizable(e,t){let i,n,a=o=>{let l=o.clientY-i,c=Math.max(100,Math.min(800,n-l));e.style.height=`${c}px`;let d=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:d})},s=()=>{document.removeEventListener("pointermove",a),document.removeEventListener("pointerup",s),e.classList.remove("resizing")};t.addEventListener("pointerdown",o=>{o.preventDefault(),i=o.clientY,n=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",s),e.classList.add("resizing")})}makeSidebarResizable(e,t,i){let n,a,s=()=>{let c=this.container.querySelector(".preview-main");if(!c)return 600;let u=c.getBoundingClientRect().width,p=i==="left"?this.container.querySelector(".debug-workbench"):this.container.querySelector(".scene-panel.scene-objects"),g=p?p.offsetWidth:i==="left"?350:300,m=u-g-200;return Math.max(200,m)},o=c=>{let d=i==="left"?c.clientX-n:n-c.clientX,u=s(),p=Math.max(200,Math.min(u,a+d));e.style.width=`${p}px`;let g=this.container.querySelector(".preview-main");if(g){let m=i==="left"?`${p}px`:g.style.gridTemplateColumns.split(" ")[0]||"300px",f=i==="right"?`${p}px`:g.style.gridTemplateColumns.split(" ")[2]||"350px",b=400;g.style.gridTemplateColumns=`${m} minmax(${b}px, 1fr) ${f}`}let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},l=()=>{document.removeEventListener("pointermove",o),document.removeEventListener("pointerup",l),e.classList.remove("resizing")};t.addEventListener("pointerdown",c=>{c.preventDefault(),n=c.clientX,a=e.offsetWidth,document.addEventListener("pointermove",o),document.addEventListener("pointerup",l),e.classList.add("resizing")})}getSceneVisibilityStorageKey(){return`handler_preview_scene_visible::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getSceneWidthStorageKey(){return`handler_preview_scene_width::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getThemeStorageKey(){return`handler_preview_theme::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}setupScenePaneInteractions(){let e=this.scenePane.querySelector("[data-scene-drag-handle]"),t=this.scenePane.querySelector("[data-scene-resize]"),i=this.container.querySelector("[data-preview-split]");e&&et(this.scenePane,e,i!=null?i:this.previewContainer),t&&Hi(this.scenePane,t,void 0,260,200);let n=this.getStoredSceneWidth();n&&(this.scenePane.style.width=`${n}px`),this.sceneSplitter.addEventListener("pointerdown",a=>{if(this.layoutMode!=="fixed"||!this.sceneVisible)return;a.preventDefault();let s=a.clientX,o=this.scenePane.offsetWidth,l=Math.max(260,Math.min(720,this.previewContainer.clientWidth*.6)),c=u=>{let p=u.clientX-s,g=Math.max(240,Math.min(l,o+p));this.scenePane.style.width=`${g}px`;let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},d=()=>{document.removeEventListener("pointermove",c),document.removeEventListener("pointerup",d),this.storeSceneWidth(this.scenePane.offsetWidth)};document.addEventListener("pointermove",c),document.addEventListener("pointerup",d)})}storeSceneWidth(e){try{window.localStorage.setItem(this.getSceneWidthStorageKey(),String(e))}catch{}}getStoredSceneWidth(){try{let e=window.localStorage.getItem(this.getSceneWidthStorageKey()),t=e?Number(e):null;return Number.isFinite(t)&&t?t:null}catch{return null}}updateSceneVisibility(){let e=this.viewMode==="single"&&this.sceneVisiblePreference;this.setSceneVisible(e,{persist:!1});let t=this.container.querySelector("#scene-toggle");t&&(t.classList.toggle("active",this.sceneVisiblePreference),t.setAttribute("aria-pressed",String(this.sceneVisiblePreference)))}setSceneVisible(e,t={}){var i;if(this.sceneVisible=e,this.container.classList.toggle("scene-hidden",!e),(i=this.sceneEditor)==null||i.setVisible(e),t.persist!==!1){this.sceneVisiblePreference=e;try{window.localStorage.setItem(this.getSceneVisibilityStorageKey(),String(e))}catch{}}this.scheduleFit()}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell layout-fixed",e.innerHTML=`
|
|
2255
2255
|
<div class="preview-toolbar">
|
|
2256
2256
|
<div class="preview-toolbar-left">
|
|
2257
2257
|
<span class="preview-logo">PREVIEWER</span>
|
|
@@ -2443,7 +2443,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
2443
2443
|
</div>
|
|
2444
2444
|
|
|
2445
2445
|
</div>
|
|
2446
|
-
`,this.setupEventListeners(e),e}setupEventListeners(e){var j,_,E,M,I,k,T,A;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",C=>{if(this.viewMode==="compare")return;let w=C.target.value;this.setDevice(w)});let i=e.querySelector("#theme-select");i==null||i.addEventListener("change",C=>{let w=C.target.value;this.setTheme(w)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(C=>{C.addEventListener("click",()=>{let w=C.dataset.viewToggle;w&&this.setViewMode(w)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(C=>{C.addEventListener("click",()=>{let w=C.dataset.layoutToggle;w&&this.setLayoutMode(w)})});let s=e.querySelector("#scene-toggle");s==null||s.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!this.sceneVisiblePreference),this.updateSceneVisibility())});let o=e.querySelector("#scene-hide-btn");o==null||o.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!1),this.updateSceneVisibility())});let l=C=>{let w=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${C}::${w}`},c=e.querySelector("#scene-grid-btn"),d=e.querySelector("#scene-play-btn"),u=(C,w,x)=>{C&&(C.textContent=w?`${x} On`:`${x} Off`,C.setAttribute("aria-pressed",w?"true":"false"))},p=()=>{let C=window.localStorage.getItem(l("grid_gap")),w=Number(C!=null?C:50);return Number.isFinite(w)?w:50},g=C=>{try{window.localStorage.setItem(l("grid_enabled"),C?"true":"false")}catch{}u(c,C,"Grid");let w=p();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:C,gap:w}}))},h=C=>{try{window.localStorage.setItem(l("play_mode"),C?"true":"false")}catch{}u(d,C,"Play"),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:C}}))};try{let C=window.localStorage.getItem(l("grid_enabled"))==="true",w=!0;try{window.localStorage.setItem(l("play_mode"),"true")}catch{}if(u(c,C,"Grid"),u(d,w,"Play"),c){let x=p();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:C,gap:x}}))}d&&window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:w}}))}catch{}c==null||c.addEventListener("click",()=>{let C=c.getAttribute("aria-pressed")==="true";g(!C)}),d==null||d.addEventListener("click",()=>{let C=d.getAttribute("aria-pressed")==="true";h(!C)}),(j=e.querySelector("#rotate-btn"))==null||j.addEventListener("click",()=>this.toggleRotation()),(_=e.querySelector("#zoom-in-btn"))==null||_.addEventListener("click",()=>this.adjustUserZoom(.1)),(E=e.querySelector("#zoom-out-btn"))==null||E.addEventListener("click",()=>this.adjustUserZoom(-.1)),(M=e.querySelector("#refresh-btn"))==null||M.addEventListener("click",()=>this.refresh());let m=e.querySelector("#bottom-dock"),f=e.querySelector("#bottom-dock-resize");m&&f&&this.makeBottomDockResizable(m,f);let b=Array.from(e.querySelectorAll(".bottom-dock-tab"));b.forEach(C=>{C.addEventListener("click",()=>{let w=C.dataset.dockTab;if(!w)return;b.forEach(O=>O.classList.remove("active")),C.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(O=>{let P=O.dataset.dockPanel;O.classList.toggle("active",P===w)})})}),(I=e.querySelector("#console-clear"))==null||I.addEventListener("click",()=>this.clearConsole()),(k=e.querySelector("#corner-zoom-in-btn"))==null||k.addEventListener("click",()=>this.adjustUserZoom(.1)),(T=e.querySelector("#corner-zoom-out-btn"))==null||T.addEventListener("click",()=>this.adjustUserZoom(-.1)),(A=e.querySelector("#corner-grab-btn"))==null||A.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let y=e.querySelector(".scene-panel.scene-objects"),v=y==null?void 0:y.querySelector("[data-panel-resize-v]");y&&v&&this.makeSidebarResizable(y,v,"left");let S=e.querySelector(".debug-workbench"),L=S==null?void 0:S.querySelector("#workbench-resize-v");S&&L&&this.makeSidebarResizable(S,L,"right")}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"var(--ui-shadow-strong)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let e=this.getEffectivePreset(),t=`${e.width}px`,i=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=i,this.gameContainer.style.width=t,this.gameContainer.style.height=i,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=i,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=i,this.gameContainer.dataset.screenWidth=String(e.width),this.gameContainer.dataset.screenHeight=String(e.height),this.container.style.setProperty("--preview-screen-width",String(e.width)),this.container.style.setProperty("--preview-screen-height",String(e.height))}fitToScreen(e){if(!this.previewContainer)return;let t=this.getEffectivePreset(),i=this.getFitBounds(),n=Math.max(0,i.width),a=Math.max(0,i.height);if(n<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=n/t.width,o=a/t.height;if(this.autoScale=Math.max(.01,Math.min(s,o)),!this.hasInitialFit){this.hasInitialFit=!0;let l=.6;this.userScaleMultiplier=l/this.autoScale}(e==null?void 0:e.keepUserScaleMultiplier)!==void 0&&e.keepUserScaleMultiplier>0?this.userScaleMultiplier=e.keepUserScaleMultiplier:e!=null&&e.keepVisibleScale&&e.keepVisibleScale>0&&(this.userScaleMultiplier=e.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),requestAnimationFrame(()=>this.updatePanelPositions()),this.emitScreenChange()}applyTransform(){let e=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${e})`;let t=this.container.querySelector("#zoom-label");t&&(t.textContent=`${Math.round(e*100)}%`),requestAnimationFrame(()=>this.updatePanelPositions())}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`,requestAnimationFrame(()=>this.updatePanelPositions())}updatePanelPositions(){if(!this.gameReady||this.viewMode==="compare")return;let e=this.container.querySelector('[data-panel="scene-tools-corner"]'),t=this.container.querySelector('[data-panel="nudge-panel"]');if(this.layoutMode==="fixed"){let i=this.gameViewPane||this.container.querySelector(".preview-container");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}else{let i=this.container.querySelector(".preview-main");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}e&&(e.style.zIndex="100"),t&&(t.style.position="absolute",t.style.left="50%",t.style.top="16px",t.style.transform="translateX(calc(-50% + 200px))",t.style.zIndex="100")}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",e=>{let t=!this.gameContainer.contains(e.target);!this.isSpaceKeyPressed&&!t||e.button===0&&(e.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=e.clientX,this.frameDragStartY=e.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}setupSpaceKeyListener(){window.addEventListener("keydown",e=>{e.code==="Space"&&!this.isInputFocused()&&(this.isSpaceKeyPressed||(this.isSpaceKeyPressed=!0,this.updateDragCursor(),e.preventDefault()))}),window.addEventListener("keyup",e=>{e.code==="Space"&&(this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd())}),window.addEventListener("blur",()=>{this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd()})}isInputFocused(){let e=document.activeElement;if(!e)return!1;let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"||e.isContentEditable}setupShortcutListeners(){window.addEventListener("keydown",e=>{if(this.isInputFocused())return;let t=navigator.platform.toUpperCase().indexOf("MAC")>=0,i=e.ctrlKey||e.metaKey,n=e.shiftKey;if(i&&e.key==="s"&&!n){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(i&&e.key==="z"&&!n){e.preventDefault(),Ba();return}if(i&&(e.key==="z"&&n||e.key==="y"&&!n)){e.preventDefault(),Ua();return}})}setupUnsavedChangesIndicator(){let e=this.container.querySelector("#preview-save-shortcut-text");e&&(e.textContent=`(${this.getShortcutKey()} + S)`),window.addEventListener("config:changed",()=>{this.updateUnsavedChangesIndicator()}),this.updateUnsavedChangesIndicator();let t=this.container.querySelector("#preview-save-btn");t==null||t.addEventListener("click",()=>{let i=document.querySelector("#apply-current-btn");i&&i.getAttribute("disabled")===null&&i.click()})}updateUnsavedChangesIndicator(){let t=st().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let i=this.container.querySelector("#preview-unsaved-star"),n=this.container.querySelector("#preview-save-btn");i&&(i.style.display=t?"inline-block":"none"),n&&(n.style.display=t?"inline-flex":"none")}}updateDragCursor(){this.isSpaceKeyPressed?(this.frameDragger.style.cursor="grab",this.frameDragActive&&(this.frameDragger.style.cursor="grabbing")):this.frameDragger.style.cursor=""}adjustUserZoom(e){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+e)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var t,i;if(this.viewMode==="compare")return;let e=this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:e}),(i=(t=this.options).onDeviceChange)==null||i.call(t,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let e=this.getEffectivePreset(),t={width:e.width,height:e.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:e.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:t})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let i=window.gameApp;if(!(i!=null&&i.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var i;let t=new WeakSet;try{return JSON.stringify(e,(n,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((i=e.constructor)!=null&&i.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...i)=>{let n=i.map(s=>typeof s=="object"?this.safeStringify(s):String(s)).join(" ");this.consoleMessages.push({type:t,message:n,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let a=this.container.querySelector("#console-badge");if(a){let s=this.consoleMessages.filter(o=>o.type==="error").length;a.textContent=s>0?`${s}!`:"0",a.classList.toggle("has-errors",s>0)}};console.log=(...t)=>{this.originalConsole.log(...t),e("log",...t)},console.warn=(...t)=>{this.originalConsole.warn(...t),e("warn",...t)},console.error=(...t)=>{this.originalConsole.error(...t),e("error",...t)},console.info=(...t)=>{this.originalConsole.info(...t),e("info",...t)}}appendConsoleMessage(e){let t=this.container.querySelector("#console-messages");if(!t)return;let i=document.createElement("div");i.className=`console-msg type-${e.type}`;let n=e.timestamp.toLocaleTimeString();i.innerHTML=`<span class="time">${this.escapeHtml(n)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(i),t.scrollTop=t.scrollHeight}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}toggleConsole(e){var t;if(this.layoutMode==="fixed"){let i=this.container.querySelector('[data-dock-tab="console"]');if(i){i.click();let n=this.container.querySelector("#bottom-dock");n==null||n.classList.remove("hidden")}return}this.isConsoleOpen=e!=null?e:!this.isConsoleOpen,(t=this.consolePanel)==null||t.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let e=this.container.querySelector("#console-messages");e&&(e.innerHTML="");let t=this.container.querySelector("#console-badge");t&&(t.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(t=>{let i=t.dataset.viewport;if(!i)return;let n=this.comparePresets.find(u=>u.id===i);if(!n)return;let a=t.querySelector("[data-compare-slot]"),s=t.querySelector("[data-compare-ghost]"),o=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),d=t.querySelector("[data-compare-focus]");!a||!s||!o||!l||(t.addEventListener("click",u=>{let p=u.target;if(p!=null&&p.closest("[data-compare-focus]")){u.preventDefault(),this.activateCompareViewport(i);return}t.classList.contains("is-active")||this.activateCompareViewport(i)}),this.compareViewports.set(i,{preset:n,root:t,slot:a,ghost:s,wrapper:o,frame:l,canvas:c,focus:d}))})}setViewMode(e){if(this.viewMode===e)return;this.viewMode=e,this.container.classList.toggle("compare-mode",e==="compare"),this.singleStage.classList.toggle("hidden",e!=="single"),this.compareStage.classList.toggle("hidden",e!=="compare");let t=this.container.querySelector("#device-select");t&&(t.disabled=e==="compare");let i=this.container.querySelector("#rotate-btn");i&&(i.disabled=e==="compare");let n=this.container.querySelector("#scene-toggle");if(n&&(n.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots(),this.updateSceneVisibility();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen(),this.updateSceneVisibility()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(t=>{t.classList.toggle("active",t.dataset.viewToggle===this.viewMode)})}activateCompareViewport(e){var a,s;let t=this.compareViewports.get(e);if(!t)return;let i=this.autoScale*this.userScaleMultiplier,n=this.activeCompareId;n&&n!==e&&this.captureCompareSnapshot(n),this.activeCompareId=e,this.currentPreset=t.preset,this.isLandscape=!1,t.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,l)=>{o.root.classList.toggle("is-active",l===e),o.ghost.classList.toggle("hidden",l===e),o.focus&&(o.focus.textContent=l===e?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:i}),(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,i=`${t.width}px`,n=`${t.height}px`;e.frame.style.width=i,e.frame.style.height=n,e.canvas&&(e.canvas.width=t.width,e.canvas.height=t.height)})}fitCompareGhosts(){this.compareViewports.forEach(e=>{let t=e.root.querySelector(".compare-body");if(!t)return;let i=Math.max(0,t.clientWidth-24),n=Math.max(0,t.clientHeight-24);if(i<=0||n<=0)return;let a=i/e.preset.width,s=n/e.preset.height,o=Math.max(.01,Math.min(a,s));e.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let i=this.gameContainer.querySelector("canvas");if(!i)return;let n=t.canvas.getContext("2d");if(!n)return;let a=t.canvas.width,s=t.canvas.height,o=Math.min(a/i.width,s/i.height),l=i.width*o,c=i.height*o,d=(a-l)/2,u=(s-c)/2;n.clearRect(0,0,a,s),n.drawImage(i,d,u,l,c)}refreshCompareSnapshots(){this.compareViewports.forEach((e,t)=>{t!==this.activeCompareId&&this.captureCompareSnapshot(t)})}startCompareSnapshots(){this.compareSnapshotTimer||(this.compareSnapshotTimer=window.setInterval(()=>{this.viewMode==="compare"&&this.refreshCompareSnapshots()},500))}stopCompareSnapshots(){this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null)}getFitBounds(){if(this.viewMode!=="compare"){let i=this.gameViewPane||this.previewContainer;return{width:i.clientWidth-40,height:i.clientHeight-40}}let e=this.compareViewports.get(this.activeCompareId),t=e==null?void 0:e.root.querySelector(".compare-body");return t?{width:t.clientWidth-24,height:t.clientHeight-24}:{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40}}mustQuery(e){let t=this.container.querySelector(e);if(!t)throw new Error(`PreviewShell missing element: ${e}`);return t}};function mr(r={}){let e=new Vn(r);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}function Yn(r){try{if(r&&typeof r.keys=="function")return Array.from(r.keys())}catch{}return[]}function fr(r){var e;return r?((e=r.getDisplayObject)==null?void 0:e.call(r))||r.pixiObject||r:null}function Fo(r,e){if(!r||!(e!=null&&e.interaction))return;let t=e.interaction,i=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);r.eventMode=i?"static":"none",r.interactive=i,i&&(r.cursor=t.draggable?"move":"pointer")}function br(r,e){var d,u,p;if(!r||!e)return;let t=e.transform||{};Fo(r,e);let i=t.position||{},n=t.offset||{},a=(typeof i.x=="number"?i.x:0)+(typeof n.x=="number"?n.x:0),s=(typeof i.y=="number"?i.y:0)+(typeof n.y=="number"?n.y:0),o=333,l=111;a+=o,s+=l,console.log("[DEBUG FALLBACK] tryApplyTransform (live-edit) position.set",a,s,"(raw + 333, +111)"),(d=r.position)!=null&&d.set?r.position.set(a,s):(typeof r.x=="number"&&(r.x=a),typeof r.y=="number"&&(r.y=s)),typeof t.scale=="number"&&((u=r.scale)!=null&&u.set?r.scale.set(t.scale):r.scale&&(r.scale.x=t.scale,r.scale.y=t.scale));let c=t.anchor;if(c&&((p=r.anchor)!=null&&p.set)){let g=null;typeof window!="undefined"&&window.resolveAnchorVec2?g=window.resolveAnchorVec2(c):typeof c=="object"&&c.x!==void 0&&c.y!==void 0?g=c:Array.isArray(c)&&c.length===2&&(g={x:c[0],y:c[1]}),g&&typeof g.x=="number"&&typeof g.y=="number"&&r.anchor.set(g.x,g.y)}}function yr(r){if(typeof window=="undefined")return;let e=r==null?void 0:r.objects,t=Yn(e),i=a=>{var s;try{let o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return a;let l=window.__HANDLER_SCREEN_INDEX,c=(s=l==null?void 0:l.screenToInstances)==null?void 0:s[o];if(Array.isArray(c)&&c.length>0){let u=new Set(c);return a.filter(p=>u.has(p))}let d=l==null?void 0:l.instanceToScreen;return d?a.filter(u=>d[u]===o):a}catch{return a}};window.__editableObjectConfigs=e;let n=new Map;t.forEach(a=>n.set(a,[a])),window.__editableObjectInstances=n,window.refreshEditableConfigIndex=()=>yr(window.__editableConfig),window.getEditableObjectList=()=>{var a;return i(Yn((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return Yn((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var u,p,g,h,m,f;let s=(h=(g=(p=(u=window.__editableConfig)==null?void 0:u.objects)==null?void 0:p.get)==null?void 0:g.call(p,a))!=null?h:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return s;let l=window.__HANDLER_SCREEN_INDEX,c=(m=l==null?void 0:l.screenToInstances)==null?void 0:m[o];if(Array.isArray(c))return c.includes(a)?s:null;let d=(f=l==null?void 0:l.instanceToScreen)==null?void 0:f[a];return d&&d===o?s:null},window.getEditableEngineConfig=()=>{let a=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!a),!a)return null;if(a.engine&&a.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let s={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(s.assets||{})),s}return a}}function Bo(){if(typeof window=="undefined")return;let r=t=>{let i=String(t||"").trim();return i?/^(data:|blob:|https?:)/.test(i)||i.startsWith("/")?i:`/${i.replace(/^\.\//,"")}`:""},e=async(t,i)=>{var a,s,o;let n=r(i);if(n)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),import("./AssetTextures-67BIZDFD.js")]),d=Date.now(),u=/^(data:|blob:)/.test(n)?n:n+(n.includes("?")?`&t=${d}`:`?t=${d}`),p=await l.load(u);if(!p)return;c[t]=p;let g=window.CustomAssets;(a=g==null?void 0:g[t])!=null&&a.texture&&(g[t].texture=p);let h=window.gameObjectManager,m=(s=h==null?void 0:h.get)==null?void 0:s.call(h,t);if(m){let f=((o=m.getDisplayObject)==null?void 0:o.call(m))||m.pixiObject||m.pixi||m;if(f!=null&&f.texture)f.texture=p;else if(f!=null&&f.children){let b=f.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=p)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let i=nn();Array.isArray(i)&&i.length&&(window.__editableConfig=t,Wt(i,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let i=nn();Array.isArray(i)&&i.length&&(window.__editableConfig=t,Wt(i,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let i=window.__editableConfig;if(!(i!=null&&i.engine))return;let n=[];if(t.runtime)for(let[a,s]of Object.entries(t.runtime))n.push({path:`runtime.${a}`,value:s});if(t.assets)for(let[a,s]of Object.entries(t.assets))n.push({path:`assets.${a}`,value:s}),typeof s=="string"&&e(a,s);if(t.splash)for(let[a,s]of Object.entries(t.splash))n.push({path:`splash.${a}`,value:s});if(t.loading)for(let[a,s]of Object.entries(t.loading))n.push({path:`loading.${a}`,value:s});if(t.start)for(let[a,s]of Object.entries(t.start))n.push({path:`start.${a}`,value:s});n.length&&Wt(n,{silent:!0,persist:!0,emitEvent:!0})}}function Wn(r){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:i}=r;t&&(t.onObjectRebuildRequired=async(a,s)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${a} due to type change...`);let o=t.get(a),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,d=c==null?void 0:c.children.indexOf(l);o?t.remove(a):l&&l.destroy();let u=window.gameApp,p=await Te.create(a,s,u);c&&(d!==void 0&&d!==-1?c.addChildAt(p,d):c.addChild(p));let g=t.create(a,p);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),g}),typeof window!="undefined"&&(Bo(),window.applyEditableObjectConfig=(a,s)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let d=window.__editableConfig;(o=d==null?void 0:d.objects)!=null&&o.set&&(d.objects.set(a,s),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let u=(l=t==null?void 0:t.get)==null?void 0:l.call(t,a);if(console.log("[LIVE-EDIT] gameObject found?",!!u),u&&(console.log("[LIVE-EDIT] gameObject type:",(c=u.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof u.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof u.onConfigUpdate=="function")),u&&typeof u.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),u.updateConfig(s);else if(u&&typeof u.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),u.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let p=fr(u);br(p,s)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let n={async applyObjectConfig(a,s){var d,u;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=e();(d=o==null?void 0:o.objects)!=null&&d.set&&(o.objects.set(a,s),console.log("[BRIDGE] \u2705 Updated config"));let l=(u=t==null?void 0:t.get)==null?void 0:u.call(t,a);if(console.log("[BRIDGE] gameObject found?",!!l),l&&(console.log("[BRIDGE] has updateConfig?",typeof l.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof l.onConfigUpdate=="function")),l&&typeof l.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),l.updateConfig(s);else if(l&&typeof l.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),l.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let p=fr(l);br(p,s)}let c=[a];i==null||i(a,s,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,yr(a))}};return n.rebuildIndexes(),n}import Uo from"lottie-web";Jn(Ss);typeof window!="undefined"&&!window.lottie&&(window.lottie=Uo);var ht=null,Go=async()=>{if(!ht){let r=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(r==null?void 0:r["handler.config"])||(r==null?void 0:r["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let i=atob(e.split(",")[1]);ht=JSON.parse(i)}else ht=JSON.parse(e);return ht}catch(i){console.warn("[CONFIG] Failed to parse inline handler.config.json:",i)}ht=await(await fetch("./handler.config.json")).json()}return ht},Zn,Dt,xr,mt,Kn,Xn;function qp(r){Zn=r.initGame,Dt=r.CustomAssets,xr=r.updateScreenState,mt=r.globalResponsiveMultipliers,Kn=r.layout,Xn=r.clearResponsiveElements}var Gi="web_embed",zt="https://example.com",vr={profile_id:Gi},We=null,ke=null,Rt={width:0,height:0},qo=!0,Vp=async()=>{var c,d,u,p;document.title="Handler Pixi Game";let r=await Go();vr={...r.ids||{},profile_id:Gi},zt=r.destination_url||((d=(c=r.export_profiles)==null?void 0:c[Gi])==null?void 0:d.destination_url)||zt,Re.init({ids:vr,profile:Gi,destinationUrl:zt});let e=Re.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),ke=mr({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),wr()},onRefresh:wr});let g=ke.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var v,S,L,j,_,E,M,I,k,T,A,C,w;let m=window.gameApp,f=window.gameObjectManager,{width:b,height:y}=h.detail;if(Rt.width=b,Rt.height=y,xr(b,y),!(!m||!m.renderer)){f&&o(m,f);try{m.renderer.resize(b,y);let x=m.view;x&&(x.style.width="100%",x.style.height="100%",x.style.display="block")}catch(x){console.warn("[SCREEN] Error resizing renderer:",x);return}if(t&&f&&Kn)try{let x=(v=window.__mainContainer)!=null?v:m.stage,O=(M=(E=(j=window.__tutorialLabel)!=null?j:(L=(S=f.get("label_1"))==null?void 0:S.getDisplayObject)==null?void 0:L.call(S))!=null?E:(_=f.get("label_1"))==null?void 0:_.pixiObject)!=null?M:f.get("label_1"),P=f.get("background_1"),R=(A=(T=(k=window.__background)!=null?k:(I=P==null?void 0:P.getDisplayObject)==null?void 0:I.call(P))!=null?T:P==null?void 0:P.pixiObject)!=null?A:P;if(x){let z=x===m.stage;Kn({mainContainer:x,label:O,background:R,backgroundTexture:(R==null?void 0:R.texture)||null,app:m},t,0,Rt,f,{skipMainContainerTransform:z}),window.dispatchEvent(new CustomEvent("handler:layout-applied",{detail:{width:Rt.width,height:Rt.height,presetId:(w=(C=h.detail)==null?void 0:C.presetId)!=null?w:null}}))}}catch(x){console.warn("[SCREEN] Error in layout:",x)}}})}let t=await Xt("scene.main");window.__editableConfig=t,s(),window.__editableConfigBaseline||(window.__editableConfigBaseline=an(t),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(p=(u=t.engine.runtime)==null?void 0:u.layout)!=null&&p.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(g=>setTimeout(g,100)),t=await Xt("scene.main"));let i=await Zn(e,t,zt,ke);We=i.app;let n=i.gameObjectManager;window.gameApp=We,window.gameObjectManager=n;try{window.__liveEditBridge=Wn({getConfig:()=>window.__editableConfig,gameObjectManager:n,assets:Dt})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}ke&&ke.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(mt.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(We,n);async function s(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,S=await fetch(v,{cache:"no-cache"});if(!S.ok)return null;let L=await S.text();try{return JSON.parse(L)}catch{return null}},h=await g("configs/flow/app.flow.json");if(!h||typeof h!="object")return;let m=h.screens;if(!m||typeof m!="object")return;let f={},b={};for(let[y,v]of Object.entries(m)){let S=v==null?void 0:v.source;if(typeof S!="string")continue;let L=await g(S),j=L==null?void 0:L.elements;if(!Array.isArray(j))continue;let _=j.map(E=>E==null?void 0:E.instance_id).filter(E=>typeof E=="string");f[y]=_;for(let E of _)b[E]||(b[E]=y)}window.__HANDLER_APP_FLOW=h,window.__HANDLER_SCREEN_INDEX={screenToInstances:f,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,h){if(qo){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${mt.scale.toFixed(3)}`),g.stage){let f=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((S,L)=>{if(S&&S.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(S&&S.scale){let j=S.scale.x||1,_=S.scale.y||1;S.__originalScale||(S.__originalScale={x:j,y:_},console.log(`${v}[RESPONSIVE] Stored original scale for child[${L}]: ${j.toFixed(3)}, ${_.toFixed(3)}`));let E=S.__originalScale.x*mt.scale,M=S.__originalScale.y*mt.scale;typeof S.scale.set=="function"?S.scale.set(E,M):(S.scale.x=E,S.scale.y=M),console.log(`${v}[RESPONSIVE] Child[${L}] scale: ${j.toFixed(3)}\u2192${S.scale.x.toFixed(3)} (type: ${S.constructor.name})`),f(S,y+1)}else S&&console.log(`${v}[RESPONSIVE] Child[${L}] has no scale (type: ${S.constructor.name})`)})};var m=f;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),f(g.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function l(g){if(g!==void 0){mt.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let h=window.gameApp,m=window.gameObjectManager;h&&m?(o(h,m),h.renderer&&(h.renderer.render(h.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!h}) or gameObjectManager (${!!m}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,Re.start()},wr=async()=>{var e,t,i,n;console.log("[PREVIEW] Restarting game in 1 seconds...");let r=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(r){let a=((t=r.getDisplayObject)==null?void 0:t.call(r))||r;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((i=a.scale.x)!=null?i:1).toFixed(3)}, y: ${((n=a.scale.y)!=null?n:1).toFixed(3)}`)}if(ke){ke.notifyGameDestroyed();try{Xn&&Xn()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=ke.getGameContainer(),s=window.gameObjectManager;if(s&&typeof s.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),s.clear()),We){try{We.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}We=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof Dt.resetScene=="function"&&Dt.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{Xt("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=an(o)),Zn(a,o,zt).then(l=>{We=l.app,window.gameApp=We,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=Wn({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Dt})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}ke&&ke.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{Re.start()}catch{}})})},100)},1e3)}};var ze={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},Vo=1.25,Yo={fontFamily:"Inter, system-ui, sans-serif"};var Qn=class{constructor(e={}){this.currentProgress=0;var t;this.currentProgress=(t=e.progress)!=null?t:0,this.container=this.createContainer()}createContainer(){let e=document.createElement("div");e.className="handler-loading-screen",e.style.cssText=`
|
|
2446
|
+
`,this.setupEventListeners(e),e}setupEventListeners(e){var j,_,E,M,I,k,T,A;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",C=>{if(this.viewMode==="compare")return;let w=C.target.value;this.setDevice(w)});let i=e.querySelector("#theme-select");i==null||i.addEventListener("change",C=>{let w=C.target.value;this.setTheme(w)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(C=>{C.addEventListener("click",()=>{let w=C.dataset.viewToggle;w&&this.setViewMode(w)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(C=>{C.addEventListener("click",()=>{let w=C.dataset.layoutToggle;w&&this.setLayoutMode(w)})});let s=e.querySelector("#scene-toggle");s==null||s.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!this.sceneVisiblePreference),this.updateSceneVisibility())});let o=e.querySelector("#scene-hide-btn");o==null||o.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!1),this.updateSceneVisibility())});let l=C=>{let w=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${C}::${w}`},c=e.querySelector("#scene-grid-btn"),d=e.querySelector("#scene-play-btn"),u=(C,w,x)=>{C&&(C.textContent=w?`${x} On`:`${x} Off`,C.setAttribute("aria-pressed",w?"true":"false"))},p=()=>{let C=window.localStorage.getItem(l("grid_gap")),w=Number(C!=null?C:50);return Number.isFinite(w)?w:50},g=C=>{try{window.localStorage.setItem(l("grid_enabled"),C?"true":"false")}catch{}u(c,C,"Grid");let w=p();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:C,gap:w}}))},h=C=>{try{window.localStorage.setItem(l("play_mode"),C?"true":"false")}catch{}u(d,C,"Play"),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:C}}))};try{let C=window.localStorage.getItem(l("grid_enabled"))==="true",w=!0;try{window.localStorage.setItem(l("play_mode"),"true")}catch{}if(u(c,C,"Grid"),u(d,w,"Play"),d&&(d.disabled=!0),c){let x=p();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:C,gap:x}}))}d&&window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:w}}))}catch{}c==null||c.addEventListener("click",()=>{let C=c.getAttribute("aria-pressed")==="true";g(!C)}),d==null||d.addEventListener("click",()=>{let C=d.getAttribute("aria-pressed")==="true";h(!C)}),(j=e.querySelector("#rotate-btn"))==null||j.addEventListener("click",()=>this.toggleRotation()),(_=e.querySelector("#zoom-in-btn"))==null||_.addEventListener("click",()=>this.adjustUserZoom(.1)),(E=e.querySelector("#zoom-out-btn"))==null||E.addEventListener("click",()=>this.adjustUserZoom(-.1)),(M=e.querySelector("#refresh-btn"))==null||M.addEventListener("click",()=>this.refresh());let m=e.querySelector("#bottom-dock"),f=e.querySelector("#bottom-dock-resize");m&&f&&this.makeBottomDockResizable(m,f);let b=Array.from(e.querySelectorAll(".bottom-dock-tab"));b.forEach(C=>{C.addEventListener("click",()=>{let w=C.dataset.dockTab;if(!w)return;b.forEach(O=>O.classList.remove("active")),C.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(O=>{let P=O.dataset.dockPanel;O.classList.toggle("active",P===w)})})}),(I=e.querySelector("#console-clear"))==null||I.addEventListener("click",()=>this.clearConsole()),(k=e.querySelector("#corner-zoom-in-btn"))==null||k.addEventListener("click",()=>this.adjustUserZoom(.1)),(T=e.querySelector("#corner-zoom-out-btn"))==null||T.addEventListener("click",()=>this.adjustUserZoom(-.1)),(A=e.querySelector("#corner-grab-btn"))==null||A.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let y=e.querySelector(".scene-panel.scene-objects"),v=y==null?void 0:y.querySelector("[data-panel-resize-v]");y&&v&&this.makeSidebarResizable(y,v,"left");let S=e.querySelector(".debug-workbench"),L=S==null?void 0:S.querySelector("#workbench-resize-v");S&&L&&this.makeSidebarResizable(S,L,"right")}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"var(--ui-shadow-strong)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let e=this.getEffectivePreset(),t=`${e.width}px`,i=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=i,this.gameContainer.style.width=t,this.gameContainer.style.height=i,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=i,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=i,this.gameContainer.dataset.screenWidth=String(e.width),this.gameContainer.dataset.screenHeight=String(e.height),this.container.style.setProperty("--preview-screen-width",String(e.width)),this.container.style.setProperty("--preview-screen-height",String(e.height))}fitToScreen(e){if(!this.previewContainer)return;let t=this.getEffectivePreset(),i=this.getFitBounds(),n=Math.max(0,i.width),a=Math.max(0,i.height);if(n<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=n/t.width,o=a/t.height;if(this.autoScale=Math.max(.01,Math.min(s,o)),!this.hasInitialFit){this.hasInitialFit=!0;let l=.6;this.userScaleMultiplier=l/this.autoScale}(e==null?void 0:e.keepUserScaleMultiplier)!==void 0&&e.keepUserScaleMultiplier>0?this.userScaleMultiplier=e.keepUserScaleMultiplier:e!=null&&e.keepVisibleScale&&e.keepVisibleScale>0&&(this.userScaleMultiplier=e.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),requestAnimationFrame(()=>this.updatePanelPositions()),this.emitScreenChange()}applyTransform(){let e=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${e})`;let t=this.container.querySelector("#zoom-label");t&&(t.textContent=`${Math.round(e*100)}%`),requestAnimationFrame(()=>this.updatePanelPositions())}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`,requestAnimationFrame(()=>this.updatePanelPositions())}updatePanelPositions(){if(!this.gameReady||this.viewMode==="compare")return;let e=this.container.querySelector('[data-panel="scene-tools-corner"]'),t=this.container.querySelector('[data-panel="nudge-panel"]');if(this.layoutMode==="fixed"){let i=this.gameViewPane||this.container.querySelector(".preview-container");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}else{let i=this.container.querySelector(".preview-main");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}e&&(e.style.zIndex="100"),t&&(t.style.position="absolute",t.style.left="50%",t.style.top="16px",t.style.transform="translateX(calc(-50% + 200px))",t.style.zIndex="100")}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",e=>{let t=!this.gameContainer.contains(e.target);!this.isSpaceKeyPressed&&!t||e.button===0&&(e.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=e.clientX,this.frameDragStartY=e.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}setupSpaceKeyListener(){window.addEventListener("keydown",e=>{e.code==="Space"&&!this.isInputFocused()&&(this.isSpaceKeyPressed||(this.isSpaceKeyPressed=!0,this.updateDragCursor(),e.preventDefault()))}),window.addEventListener("keyup",e=>{e.code==="Space"&&(this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd())}),window.addEventListener("blur",()=>{this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd()})}isInputFocused(){let e=document.activeElement;if(!e)return!1;let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"||e.isContentEditable}setupShortcutListeners(){window.addEventListener("keydown",e=>{if(this.isInputFocused())return;let t=navigator.platform.toUpperCase().indexOf("MAC")>=0,i=e.ctrlKey||e.metaKey,n=e.shiftKey;if(i&&e.key==="s"&&!n){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(i&&e.key==="z"&&!n){e.preventDefault(),Ba();return}if(i&&(e.key==="z"&&n||e.key==="y"&&!n)){e.preventDefault(),Ua();return}})}setupUnsavedChangesIndicator(){let e=this.container.querySelector("#preview-save-shortcut-text");e&&(e.textContent=`(${this.getShortcutKey()} + S)`),window.addEventListener("config:changed",()=>{this.updateUnsavedChangesIndicator()}),this.updateUnsavedChangesIndicator();let t=this.container.querySelector("#preview-save-btn");t==null||t.addEventListener("click",()=>{let i=document.querySelector("#apply-current-btn");i&&i.getAttribute("disabled")===null&&i.click()})}updateUnsavedChangesIndicator(){let t=st().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let i=this.container.querySelector("#preview-unsaved-star"),n=this.container.querySelector("#preview-save-btn");i&&(i.style.display=t?"inline-block":"none"),n&&(n.style.display=t?"inline-flex":"none")}}updateDragCursor(){this.isSpaceKeyPressed?(this.frameDragger.style.cursor="grab",this.frameDragActive&&(this.frameDragger.style.cursor="grabbing")):this.frameDragger.style.cursor=""}adjustUserZoom(e){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+e)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var t,i;if(this.viewMode==="compare")return;let e=this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:e}),(i=(t=this.options).onDeviceChange)==null||i.call(t,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let e=this.getEffectivePreset(),t={width:e.width,height:e.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:e.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:t})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let i=window.gameApp;if(!(i!=null&&i.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var i;let t=new WeakSet;try{return JSON.stringify(e,(n,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((i=e.constructor)!=null&&i.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...i)=>{let n=i.map(s=>typeof s=="object"?this.safeStringify(s):String(s)).join(" ");this.consoleMessages.push({type:t,message:n,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let a=this.container.querySelector("#console-badge");if(a){let s=this.consoleMessages.filter(o=>o.type==="error").length;a.textContent=s>0?`${s}!`:"0",a.classList.toggle("has-errors",s>0)}};console.log=(...t)=>{this.originalConsole.log(...t),e("log",...t)},console.warn=(...t)=>{this.originalConsole.warn(...t),e("warn",...t)},console.error=(...t)=>{this.originalConsole.error(...t),e("error",...t)},console.info=(...t)=>{this.originalConsole.info(...t),e("info",...t)}}appendConsoleMessage(e){let t=this.container.querySelector("#console-messages");if(!t)return;let i=document.createElement("div");i.className=`console-msg type-${e.type}`;let n=e.timestamp.toLocaleTimeString();i.innerHTML=`<span class="time">${this.escapeHtml(n)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(i),t.scrollTop=t.scrollHeight}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}toggleConsole(e){var t;if(this.layoutMode==="fixed"){let i=this.container.querySelector('[data-dock-tab="console"]');if(i){i.click();let n=this.container.querySelector("#bottom-dock");n==null||n.classList.remove("hidden")}return}this.isConsoleOpen=e!=null?e:!this.isConsoleOpen,(t=this.consolePanel)==null||t.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let e=this.container.querySelector("#console-messages");e&&(e.innerHTML="");let t=this.container.querySelector("#console-badge");t&&(t.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(t=>{let i=t.dataset.viewport;if(!i)return;let n=this.comparePresets.find(u=>u.id===i);if(!n)return;let a=t.querySelector("[data-compare-slot]"),s=t.querySelector("[data-compare-ghost]"),o=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),d=t.querySelector("[data-compare-focus]");!a||!s||!o||!l||(t.addEventListener("click",u=>{let p=u.target;if(p!=null&&p.closest("[data-compare-focus]")){u.preventDefault(),this.activateCompareViewport(i);return}t.classList.contains("is-active")||this.activateCompareViewport(i)}),this.compareViewports.set(i,{preset:n,root:t,slot:a,ghost:s,wrapper:o,frame:l,canvas:c,focus:d}))})}setViewMode(e){if(this.viewMode===e)return;this.viewMode=e,this.container.classList.toggle("compare-mode",e==="compare"),this.singleStage.classList.toggle("hidden",e!=="single"),this.compareStage.classList.toggle("hidden",e!=="compare");let t=this.container.querySelector("#device-select");t&&(t.disabled=e==="compare");let i=this.container.querySelector("#rotate-btn");i&&(i.disabled=e==="compare");let n=this.container.querySelector("#scene-toggle");if(n&&(n.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots(),this.updateSceneVisibility();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen(),this.updateSceneVisibility()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(t=>{t.classList.toggle("active",t.dataset.viewToggle===this.viewMode)})}activateCompareViewport(e){var a,s;let t=this.compareViewports.get(e);if(!t)return;let i=this.autoScale*this.userScaleMultiplier,n=this.activeCompareId;n&&n!==e&&this.captureCompareSnapshot(n),this.activeCompareId=e,this.currentPreset=t.preset,this.isLandscape=!1,t.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,l)=>{o.root.classList.toggle("is-active",l===e),o.ghost.classList.toggle("hidden",l===e),o.focus&&(o.focus.textContent=l===e?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:i}),(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,i=`${t.width}px`,n=`${t.height}px`;e.frame.style.width=i,e.frame.style.height=n,e.canvas&&(e.canvas.width=t.width,e.canvas.height=t.height)})}fitCompareGhosts(){this.compareViewports.forEach(e=>{let t=e.root.querySelector(".compare-body");if(!t)return;let i=Math.max(0,t.clientWidth-24),n=Math.max(0,t.clientHeight-24);if(i<=0||n<=0)return;let a=i/e.preset.width,s=n/e.preset.height,o=Math.max(.01,Math.min(a,s));e.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let i=this.gameContainer.querySelector("canvas");if(!i)return;let n=t.canvas.getContext("2d");if(!n)return;let a=t.canvas.width,s=t.canvas.height,o=Math.min(a/i.width,s/i.height),l=i.width*o,c=i.height*o,d=(a-l)/2,u=(s-c)/2;n.clearRect(0,0,a,s),n.drawImage(i,d,u,l,c)}refreshCompareSnapshots(){this.compareViewports.forEach((e,t)=>{t!==this.activeCompareId&&this.captureCompareSnapshot(t)})}startCompareSnapshots(){this.compareSnapshotTimer||(this.compareSnapshotTimer=window.setInterval(()=>{this.viewMode==="compare"&&this.refreshCompareSnapshots()},500))}stopCompareSnapshots(){this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null)}getFitBounds(){if(this.viewMode!=="compare"){let i=this.gameViewPane||this.previewContainer;return{width:i.clientWidth-40,height:i.clientHeight-40}}let e=this.compareViewports.get(this.activeCompareId),t=e==null?void 0:e.root.querySelector(".compare-body");return t?{width:t.clientWidth-24,height:t.clientHeight-24}:{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40}}mustQuery(e){let t=this.container.querySelector(e);if(!t)throw new Error(`PreviewShell missing element: ${e}`);return t}};function mr(r={}){let e=new Vn(r);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}function Yn(r){try{if(r&&typeof r.keys=="function")return Array.from(r.keys())}catch{}return[]}function fr(r){var e;return r?((e=r.getDisplayObject)==null?void 0:e.call(r))||r.pixiObject||r:null}function Fo(r,e){if(!r||!(e!=null&&e.interaction))return;let t=e.interaction,i=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);r.eventMode=i?"static":"none",r.interactive=i,i&&(r.cursor=t.draggable?"move":"pointer")}function br(r,e){var d,u,p;if(!r||!e)return;let t=e.transform||{};Fo(r,e);let i=t.position||{},n=t.offset||{},a=(typeof i.x=="number"?i.x:0)+(typeof n.x=="number"?n.x:0),s=(typeof i.y=="number"?i.y:0)+(typeof n.y=="number"?n.y:0),o=333,l=111;a+=o,s+=l,console.log("[DEBUG FALLBACK] tryApplyTransform (live-edit) position.set",a,s,"(raw + 333, +111)"),(d=r.position)!=null&&d.set?r.position.set(a,s):(typeof r.x=="number"&&(r.x=a),typeof r.y=="number"&&(r.y=s)),typeof t.scale=="number"&&((u=r.scale)!=null&&u.set?r.scale.set(t.scale):r.scale&&(r.scale.x=t.scale,r.scale.y=t.scale));let c=t.anchor;if(c&&((p=r.anchor)!=null&&p.set)){let g=null;typeof window!="undefined"&&window.resolveAnchorVec2?g=window.resolveAnchorVec2(c):typeof c=="object"&&c.x!==void 0&&c.y!==void 0?g=c:Array.isArray(c)&&c.length===2&&(g={x:c[0],y:c[1]}),g&&typeof g.x=="number"&&typeof g.y=="number"&&r.anchor.set(g.x,g.y)}}function yr(r){if(typeof window=="undefined")return;let e=r==null?void 0:r.objects,t=Yn(e),i=a=>{var s;try{let o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return a;let l=window.__HANDLER_SCREEN_INDEX,c=(s=l==null?void 0:l.screenToInstances)==null?void 0:s[o];if(Array.isArray(c)&&c.length>0){let u=new Set(c);return a.filter(p=>u.has(p))}let d=l==null?void 0:l.instanceToScreen;return d?a.filter(u=>d[u]===o):a}catch{return a}};window.__editableObjectConfigs=e;let n=new Map;t.forEach(a=>n.set(a,[a])),window.__editableObjectInstances=n,window.refreshEditableConfigIndex=()=>yr(window.__editableConfig),window.getEditableObjectList=()=>{var a;return i(Yn((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return Yn((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var u,p,g,h,m,f;let s=(h=(g=(p=(u=window.__editableConfig)==null?void 0:u.objects)==null?void 0:p.get)==null?void 0:g.call(p,a))!=null?h:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return s;let l=window.__HANDLER_SCREEN_INDEX,c=(m=l==null?void 0:l.screenToInstances)==null?void 0:m[o];if(Array.isArray(c))return c.includes(a)?s:null;let d=(f=l==null?void 0:l.instanceToScreen)==null?void 0:f[a];return d&&d===o?s:null},window.getEditableEngineConfig=()=>{let a=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!a),!a)return null;if(a.engine&&a.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let s={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(s.assets||{})),s}return a}}function Bo(){if(typeof window=="undefined")return;let r=t=>{let i=String(t||"").trim();return i?/^(data:|blob:|https?:)/.test(i)||i.startsWith("/")?i:`/${i.replace(/^\.\//,"")}`:""},e=async(t,i)=>{var a,s,o;let n=r(i);if(n)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),import("./AssetTextures-67BIZDFD.js")]),d=Date.now(),u=/^(data:|blob:)/.test(n)?n:n+(n.includes("?")?`&t=${d}`:`?t=${d}`),p=await l.load(u);if(!p)return;c[t]=p;let g=window.CustomAssets;(a=g==null?void 0:g[t])!=null&&a.texture&&(g[t].texture=p);let h=window.gameObjectManager,m=(s=h==null?void 0:h.get)==null?void 0:s.call(h,t);if(m){let f=((o=m.getDisplayObject)==null?void 0:o.call(m))||m.pixiObject||m.pixi||m;if(f!=null&&f.texture)f.texture=p;else if(f!=null&&f.children){let b=f.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=p)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let i=nn();Array.isArray(i)&&i.length&&(window.__editableConfig=t,Wt(i,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let i=nn();Array.isArray(i)&&i.length&&(window.__editableConfig=t,Wt(i,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let i=window.__editableConfig;if(!(i!=null&&i.engine))return;let n=[];if(t.runtime)for(let[a,s]of Object.entries(t.runtime))n.push({path:`runtime.${a}`,value:s});if(t.assets)for(let[a,s]of Object.entries(t.assets))n.push({path:`assets.${a}`,value:s}),typeof s=="string"&&e(a,s);if(t.splash)for(let[a,s]of Object.entries(t.splash))n.push({path:`splash.${a}`,value:s});if(t.loading)for(let[a,s]of Object.entries(t.loading))n.push({path:`loading.${a}`,value:s});if(t.start)for(let[a,s]of Object.entries(t.start))n.push({path:`start.${a}`,value:s});n.length&&Wt(n,{silent:!0,persist:!0,emitEvent:!0})}}function Wn(r){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:i}=r;t&&(t.onObjectRebuildRequired=async(a,s)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${a} due to type change...`);let o=t.get(a),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,d=c==null?void 0:c.children.indexOf(l);o?t.remove(a):l&&l.destroy();let u=window.gameApp,p=await Te.create(a,s,u);c&&(d!==void 0&&d!==-1?c.addChildAt(p,d):c.addChild(p));let g=t.create(a,p);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),g}),typeof window!="undefined"&&(Bo(),window.applyEditableObjectConfig=(a,s)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let d=window.__editableConfig;(o=d==null?void 0:d.objects)!=null&&o.set&&(d.objects.set(a,s),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let u=(l=t==null?void 0:t.get)==null?void 0:l.call(t,a);if(console.log("[LIVE-EDIT] gameObject found?",!!u),u&&(console.log("[LIVE-EDIT] gameObject type:",(c=u.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof u.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof u.onConfigUpdate=="function")),u&&typeof u.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),u.updateConfig(s);else if(u&&typeof u.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),u.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let p=fr(u);br(p,s)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let n={async applyObjectConfig(a,s){var d,u;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=e();(d=o==null?void 0:o.objects)!=null&&d.set&&(o.objects.set(a,s),console.log("[BRIDGE] \u2705 Updated config"));let l=(u=t==null?void 0:t.get)==null?void 0:u.call(t,a);if(console.log("[BRIDGE] gameObject found?",!!l),l&&(console.log("[BRIDGE] has updateConfig?",typeof l.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof l.onConfigUpdate=="function")),l&&typeof l.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),l.updateConfig(s);else if(l&&typeof l.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),l.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let p=fr(l);br(p,s)}let c=[a];i==null||i(a,s,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,yr(a))}};return n.rebuildIndexes(),n}import Uo from"lottie-web";Jn(Ss);typeof window!="undefined"&&!window.lottie&&(window.lottie=Uo);var ht=null,Go=async()=>{if(!ht){let r=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(r==null?void 0:r["handler.config"])||(r==null?void 0:r["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let i=atob(e.split(",")[1]);ht=JSON.parse(i)}else ht=JSON.parse(e);return ht}catch(i){console.warn("[CONFIG] Failed to parse inline handler.config.json:",i)}ht=await(await fetch("./handler.config.json")).json()}return ht},Zn,Dt,xr,mt,Kn,Xn;function qp(r){Zn=r.initGame,Dt=r.CustomAssets,xr=r.updateScreenState,mt=r.globalResponsiveMultipliers,Kn=r.layout,Xn=r.clearResponsiveElements}var Gi="web_embed",zt="https://example.com",vr={profile_id:Gi},We=null,ke=null,Rt={width:0,height:0},qo=!0,Vp=async()=>{var c,d,u,p;document.title="Handler Pixi Game";let r=await Go();vr={...r.ids||{},profile_id:Gi},zt=r.destination_url||((d=(c=r.export_profiles)==null?void 0:c[Gi])==null?void 0:d.destination_url)||zt,Re.init({ids:vr,profile:Gi,destinationUrl:zt});let e=Re.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),ke=mr({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),wr()},onRefresh:wr});let g=ke.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var v,S,L,j,_,E,M,I,k,T,A,C,w;let m=window.gameApp,f=window.gameObjectManager,{width:b,height:y}=h.detail;if(Rt.width=b,Rt.height=y,xr(b,y),!(!m||!m.renderer)){f&&o(m,f);try{m.renderer.resize(b,y);let x=m.view;x&&(x.style.width="100%",x.style.height="100%",x.style.display="block")}catch(x){console.warn("[SCREEN] Error resizing renderer:",x);return}if(t&&f&&Kn)try{let x=(v=window.__mainContainer)!=null?v:m.stage,O=(M=(E=(j=window.__tutorialLabel)!=null?j:(L=(S=f.get("label_1"))==null?void 0:S.getDisplayObject)==null?void 0:L.call(S))!=null?E:(_=f.get("label_1"))==null?void 0:_.pixiObject)!=null?M:f.get("label_1"),P=f.get("background_1"),R=(A=(T=(k=window.__background)!=null?k:(I=P==null?void 0:P.getDisplayObject)==null?void 0:I.call(P))!=null?T:P==null?void 0:P.pixiObject)!=null?A:P;if(x){let z=x===m.stage;Kn({mainContainer:x,label:O,background:R,backgroundTexture:(R==null?void 0:R.texture)||null,app:m},t,0,Rt,f,{skipMainContainerTransform:z}),window.dispatchEvent(new CustomEvent("handler:layout-applied",{detail:{width:Rt.width,height:Rt.height,presetId:(w=(C=h.detail)==null?void 0:C.presetId)!=null?w:null}}))}}catch(x){console.warn("[SCREEN] Error in layout:",x)}}})}let t=await Xt("scene.main");window.__editableConfig=t,s(),window.__editableConfigBaseline||(window.__editableConfigBaseline=an(t),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(p=(u=t.engine.runtime)==null?void 0:u.layout)!=null&&p.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(g=>setTimeout(g,100)),t=await Xt("scene.main"));let i=await Zn(e,t,zt,ke);We=i.app;let n=i.gameObjectManager;window.gameApp=We,window.gameObjectManager=n;try{window.__liveEditBridge=Wn({getConfig:()=>window.__editableConfig,gameObjectManager:n,assets:Dt})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}ke&&ke.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(mt.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(We,n);async function s(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,S=await fetch(v,{cache:"no-cache"});if(!S.ok)return null;let L=await S.text();try{return JSON.parse(L)}catch{return null}},h=await g("configs/flow/app.flow.json");if(!h||typeof h!="object")return;let m=h.screens;if(!m||typeof m!="object")return;let f={},b={};for(let[y,v]of Object.entries(m)){let S=v==null?void 0:v.source;if(typeof S!="string")continue;let L=await g(S),j=L==null?void 0:L.elements;if(!Array.isArray(j))continue;let _=j.map(E=>E==null?void 0:E.instance_id).filter(E=>typeof E=="string");f[y]=_;for(let E of _)b[E]||(b[E]=y)}window.__HANDLER_APP_FLOW=h,window.__HANDLER_SCREEN_INDEX={screenToInstances:f,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,h){if(qo){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${mt.scale.toFixed(3)}`),g.stage){let f=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((S,L)=>{if(S&&S.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(S&&S.scale){let j=S.scale.x||1,_=S.scale.y||1;S.__originalScale||(S.__originalScale={x:j,y:_},console.log(`${v}[RESPONSIVE] Stored original scale for child[${L}]: ${j.toFixed(3)}, ${_.toFixed(3)}`));let E=S.__originalScale.x*mt.scale,M=S.__originalScale.y*mt.scale;typeof S.scale.set=="function"?S.scale.set(E,M):(S.scale.x=E,S.scale.y=M),console.log(`${v}[RESPONSIVE] Child[${L}] scale: ${j.toFixed(3)}\u2192${S.scale.x.toFixed(3)} (type: ${S.constructor.name})`),f(S,y+1)}else S&&console.log(`${v}[RESPONSIVE] Child[${L}] has no scale (type: ${S.constructor.name})`)})};var m=f;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),f(g.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function l(g){if(g!==void 0){mt.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let h=window.gameApp,m=window.gameObjectManager;h&&m?(o(h,m),h.renderer&&(h.renderer.render(h.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!h}) or gameObjectManager (${!!m}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,Re.start()},wr=async()=>{var e,t,i,n;console.log("[PREVIEW] Restarting game in 1 seconds...");let r=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(r){let a=((t=r.getDisplayObject)==null?void 0:t.call(r))||r;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((i=a.scale.x)!=null?i:1).toFixed(3)}, y: ${((n=a.scale.y)!=null?n:1).toFixed(3)}`)}if(ke){ke.notifyGameDestroyed();try{Xn&&Xn()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=ke.getGameContainer(),s=window.gameObjectManager;if(s&&typeof s.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),s.clear()),We){try{We.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}We=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof Dt.resetScene=="function"&&Dt.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{Xt("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=an(o)),Zn(a,o,zt).then(l=>{We=l.app,window.gameApp=We,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=Wn({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Dt})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}ke&&ke.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{Re.start()}catch{}})})},100)},1e3)}};var ze={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},Vo=1.25,Yo={fontFamily:"Inter, system-ui, sans-serif"};var Qn=class{constructor(e={}){this.currentProgress=0;var t;this.currentProgress=(t=e.progress)!=null?t:0,this.container=this.createContainer()}createContainer(){let e=document.createElement("div");e.className="handler-loading-screen",e.style.cssText=`
|
|
2447
2447
|
position: fixed;
|
|
2448
2448
|
inset: 0;
|
|
2449
2449
|
display: flex;
|