handler-playable-sdk 0.5.47 → 0.5.54
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-RLJOGLPW.js → chunk-UXMZHMPZ.js} +147 -96
- 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.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 +138 -87
- package/dist/index.css +86 -0
- package/dist/index.d.cts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1 -1
- package/dist/pixi/index.cjs +5 -5
- package/dist/pixi/index.css +86 -0
- package/dist/pixi/index.js +1 -1
- package/dist/three/index.cjs +12 -12
- package/dist/three/index.css +86 -0
- package/dist/three/index.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Ys=Object.create;var Wt=Object.defineProperty;var Ks=Object.getOwnPropertyDescriptor;var Xs=Object.getOwnPropertyNames;var Js=Object.getPrototypeOf,Zs=Object.prototype.hasOwnProperty;var pe=(r,e)=>()=>(r&&(e=r(r=0)),e);var bt=(r,e)=>{for(var t in e)Wt(r,t,{get:e[t],enumerable:!0})},Fa=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Xs(e))!Zs.call(r,i)&&i!==t&&Wt(r,i,{get:()=>e[i],enumerable:!(n=Ks(e,i))||n.enumerable});return r};var Xe=(r,e,t)=>(t=r!=null?Ys(Js(r)):{},Fa(e||!r||!r.__esModule?Wt(t,"default",{value:r,enumerable:!0}):t,r)),Qs=r=>Fa(Wt({},"__esModule",{value:!0}),r);var ue,vi=pe(()=>{"use strict";ue=class{static get(e){var t;return(t=this.store.get(e))==null?void 0:t.data}static set(e,t){this.store.set(e,{data:t})}static has(e){return this.store.has(e)}static clear(){this.store.clear()}};ue.store=new Map});function oo(){var r,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(r=document.querySelector("script"))==null?void 0:r.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),n=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!n)}catch{return!1}}async function lo(){try{if(typeof window!="undefined"){let r=await fetch("./build-settings.json");if(r.ok){let e=await r.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function co(){try{if(typeof window!="undefined"){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);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function po(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${B}`),Object.keys(ge).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(ge)),ge;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),ge={...window.INLINE_ASSETS},ge;if(!(B==="publish"&&se!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),ge;if(!wi){let e=typeof window!="undefined"?new URL("inline-assets.js",window.location.href).href:"./inline-assets.js";console.log("[AssetLoader] Loading inline assets from:",e),wi=(async()=>{try{try{let a=await import(e+"?t="+Date.now());if(a.INLINE_ASSETS)return console.log("[AssetLoader] Loaded INLINE_ASSETS via ES module:",Object.keys(a.INLINE_ASSETS)),a.INLINE_ASSETS}catch(a){console.warn("[AssetLoader] ES module import failed, trying text parse:",a)}let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let n=await t.text();console.log("[AssetLoader] Received JS code, length:",n.length);let i=n.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(i)try{let a=i[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let s=new Function("return "+a)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(s)),s}catch(a){return console.warn("[AssetLoader] Failed to parse inline assets:",a),{}}else return console.warn("[AssetLoader] INLINE_ASSETS export not found in response"),console.log("[AssetLoader] JS code preview:",n.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return ge=await wi,console.log("[AssetLoader] Final inline assets cache:",Object.keys(ge)),ge}function xi(r){return r===null||typeof r!="object"||(Object.freeze(r),Object.values(r).forEach(e=>xi(e))),r}function uo(r=64,e=64,t=16711680){let n=document.createElement("canvas");n.width=r,n.height=e;let i=n.getContext("2d");return i.fillStyle=`#${t.toString(16).padStart(6,"0")}`,i.fillRect(0,0,r,e),i.strokeStyle="#000",i.strokeRect(0,0,r,e),i.fillStyle="#fff",i.font="10px sans-serif",i.textAlign="center",i.fillText("MISSING",r/2,e/2),he.Texture.from(n)}function Ei(r,e){wr.set(r,e)}var he,yr,vr,Re,B,se,Se,ge,wi,wr,ze,Jt=pe(()=>{"use strict";he=require("pixi.js");vi();yr=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",vr=oo(),Re=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,B=vr?"publish":yr,se=Re==null?void 0:Re.assetsInlined;Re!=null&&Re.buildMode&&(B=Re.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${B}`));Se=co();Se!=null&&Se.buildMode&&(B=Se.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${B}`));(Se==null?void 0:Se.assetsInlined)!==void 0&&(se=Se.assetsInlined);lo().then(r=>{r!=null&&r.buildMode&&r.buildMode!==B&&(B=r.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${B}`)),(r==null?void 0:r.assetsInlined)!==void 0&&(se=r.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${yr}, Runtime: ${vr?"publish":"dev"}, Effective: ${B}`);ge={},wi=null;wr=new Map;ze=class{static async load(e,t,n,i){let a=`${e}:${t.path}`,s=ue.get(a);if(s!==void 0)return s;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${B}`),console.log(`[AssetLoader] Window defined: ${typeof window!="undefined"}, INLINE_ASSETS exists: ${!!(typeof window!="undefined"&&window.INLINE_ASSETS)}, keys: ${typeof window!="undefined"&&window.INLINE_ASSETS?Object.keys(window.INLINE_ASSETS).length:"N/A"}`);let o=await po(),l=o[e];if(!l&&i&&(l=o[i],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${i}`)),!l&&t.path){let d=t.path.split("/");if(d.length>=2){let u=d[d.length-1].split(".")[0];o[u]&&(l=o[u],console.log(`[AssetLoader] Found inline data for ${e} using assetName: ${u}`))}}if(console.log("[AssetLoader] Inline data for",e,":",l?"FOUND":"NOT FOUND"),B==="publish"&&se!==!1&&(console.log("[AssetLoader] \u26A0\uFE0F PUBLISH MODE DETECTED - inline assets are MANDATORY"),!l))throw new Error(`[AssetLoader] PUBLISH MODE: Inline asset required but NOT FOUND for object: ${e}, path: ${t.path}`);let p=wr.get(t.type);if(p)try{let d=await p(t.path,l,e,n);return ue.set(a,d),d}catch(d){return this.handleFailure(e,t.type,d)}try{let d;switch(t.type){case"image":d=await this.loadImage(t.path,l);break;case"json":d=await this.loadJSON(t.path,l),d=xi(d);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return ue.set(a,d),d}catch(d){return this.handleFailure(e,t.type,d)}}static async loadImage(e,t){let n=B==="publish",i=n&&se!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${B}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for object. Path: ${e}`);if(typeof t!="string"||!t.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof t}`);try{return await he.Assets.load(t)}catch(a){throw console.error("[AssetLoader] Failed to load texture from data URI:",a),a}}if(t&&typeof t=="string"&&t.startsWith("data:"))try{return await he.Assets.load(t)}catch(a){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",a),await he.Assets.load(e)}return await he.Assets.load(e)}static async loadJSON(e,t){let n=B==="publish",i=n&&se!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${B}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let s=atob(t.split(",")[1]);return JSON.parse(s)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let s=atob(t.split(",")[1]);return JSON.parse(s)}return JSON.parse(t)}let a=await fetch(e);if(!a.ok)throw new Error(`JSON fetch failed: ${e}`);return a.json()}static handleFailure(e,t,n){if(B==="dev"){let a=t==="image"?uo():xi({__placeholder:!0,type:t});return ue.set(e+":"+((n==null?void 0:n.path)||"missing"),a),a}throw n}};Ei("image",async(r,e)=>{let t=B==="publish",n=t&&se!==!1,i=B==="brand",a=t&&se===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${B}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${r}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return he.Assets.load(e)}let s=r;return(i||a)&&r&&!r.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=r,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${r}" as-is`)):(s=`assets/${r}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${r}" -> "${s}"`))),he.Assets.load(e||s)});Ei("json",async(r,e)=>{let t=B==="publish",n=t&&se!==!1,i=B==="brand",a=t&&se===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${B}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${r}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let s=r;if((i||a)&&r&&!r.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=r,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${r}" as-is`)):(s=`assets/${r}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${r}" -> "${s}"`))),e)return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e);let o=await fetch(s);if(!o.ok)throw new Error(`JSON fetch failed: ${r}`);return o.json()})});var Er={};bt(Er,{AssetTextures:()=>oe,initAssetTextures:()=>Ci});function Ci(r,e){xr.init(r,e),typeof window!="undefined"&&(window.__AssetTextures=oe)}var Ai,xr,oe,et=pe(()=>{"use strict";Jt();Ai=class{constructor(){this.textures=new Map;this.readyPromise=null;this.priorityReadyPromise=null;this.priorityReadyResolve=null;this.config=null;this.app=null;this.attempted=new Set;this.waiters=new Set}init(e,t){if(this.config===e&&this.app===t&&this.priorityReadyPromise){console.log("[AssetTextures] init called with same config/app; keeping existing state");return}this.textures.clear(),this.readyPromise=null,this.priorityReadyPromise=null,this.priorityReadyResolve=null,this.attempted.clear(),this.waiters.clear(),this.priorityReadyPromise=new Promise(n=>{this.priorityReadyResolve=n}),this.config=e,this.app=t,console.log("[AssetTextures] Initialized with config, cleared previous textures")}async ready(){if(this.readyPromise){await this.readyPromise;return}if(!this.config)throw new Error("[AssetTextures] Must call init() before ready() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before ready() - app is null");let e=this.config,t=this.app;return this.readyPromise=(async()=>{var s;console.log("[AssetTextures] Loading all assets...");let n=new Set(["background_loading_1"]),i=[],a=[];for(let[o,l]of e.objects.entries()){let c=(s=l.render)==null?void 0:s.asset;if(!c)continue;let p=async()=>{var d;try{let u=(d=l.identity)==null?void 0:d.id;console.log(`[AssetTextures] Loading ${c.type}: ${o} (${u})`);let g=await ze.load(o,c,t,u);this.textures.set(o,g),console.log(`[AssetTextures] \u2713 Loaded: ${o}`)}catch(u){console.error(`[AssetTextures] \u2717 Failed to load: ${o}`,u)}finally{this.attempted.add(o);try{for(let u of Array.from(this.waiters))u()}catch{}}};n.has(o)?i.push(p()):a.push(p())}i.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(i),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(a),console.log("[AssetTextures] All textures loaded:",Array.from(this.textures.keys()))})(),this.readyPromise}async priorityReady(){return this.priorityReadyPromise?this.priorityReadyPromise:Promise.resolve()}async waitFor(e,t={}){if(!this.config)throw new Error("[AssetTextures] Must call init() before waitFor() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before waitFor() - app is null");let i=Array.from(new Set((e||[]).filter(o=>typeof o=="string"&&o))).filter(o=>{var l,c,p,d;try{let u=(p=(c=(l=this.config)==null?void 0:l.objects)==null?void 0:c.get)==null?void 0:p.call(c,o);return!!((d=u==null?void 0:u.render)!=null&&d.asset)}catch{return!1}});if(i.length===0)return;this.ready().catch(()=>{});let a=()=>i.every(o=>this.textures.has(o)||this.attempted.has(o));if(a())return;let s=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(o=>{let l=!1,c=()=>{l||a()&&(l=!0,this.waiters.delete(c),o())};this.waiters.add(c),c(),s>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:i}),o())},s)})}get(e){return this.textures.get(e)}set(e,t){this.textures.set(e,t),console.log(`[AssetTextures] Updated texture: ${e}`)}clear(){this.textures.clear(),this.readyPromise=null,console.log("[AssetTextures] Cleared all textures")}getAllIds(){return Array.from(this.textures.keys())}},xr=new Ai,oe=new Proxy(xr,{get(r,e){return e in r&&typeof r[e]=="function"?r[e].bind(r):r.get(e)},set(r,e,t){return r.set(e,t),!0}})});var He={};bt(He,{applyConfigOverride:()=>le,applyConfigOverrides:()=>Ce,applyConfigsToDisk:()=>un,clearConfigOverrides:()=>te,clearConfigOverridesForObject:()=>Pr,configOverrideManager:()=>_r,deepClone:()=>V,exportConfigsAsJSON:()=>De,getConfigOverrides:()=>K,getConfigStateSummary:()=>Te,getOverrideMode:()=>At,redoLastConfigChange:()=>pn,removeConfigOverride:()=>Ct,resetToApplied:()=>Tt,resetToOriginal:()=>gn,setOverrideMode:()=>ji,trackObjectCreation:()=>jr,trackObjectDeletion:()=>Or,undoLastConfigChange:()=>dn});function on(){return typeof window=="undefined"?null:window.__editableConfig||null}function Mi(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function Ii(r,e){var t,n;if(!r)return null;try{if(r instanceof Map)return(t=r.get(e))!=null?t:null;if(typeof r=="object")return(n=r[e])!=null?n:null}catch{}return null}function Do(r,e,t){if(r){if(r instanceof Map){r.set(e,t);return}typeof r=="object"&&(r[e]=t)}}function kr(r,e){for(let t of e)St(r,t.path,t.value)}function ln(r){var o;if(typeof window=="undefined")return;let e=on();if(!e)return;let t=Mi(),n=(o=t?Ii(t.objects,r):null)!=null?o:Ii(e.objects,r);if(!n)return;let i=V(n),a=K().filter(l=>l.objectId===r);try{kr(i,a)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",r,l);return}Do(e.objects,r,i);let s=window.applyEditableObjectConfig;if(typeof s=="function")try{s(r,i)}catch{}}function Pi(){var i;if(typeof window=="undefined")return;let r=on();if(!(r!=null&&r.engine))return;let e=Mi(),t=V(((i=e==null?void 0:e.engine)!=null?i:r.engine)||{}),n=K().filter(a=>!a.objectId&&!a.sceneId);try{kr(t,n)}catch(a){console.error("[CONFIG] Failed to reapply engine overrides",a);return}try{let a=r.engine;for(let s of Object.keys(a))s in t||delete a[s];for(let[s,o]of Object.entries(t))a[s]=o}catch{r.engine=t}}function Ho(){if(typeof window=="undefined")return"unknown";let r=window;return typeof r.__HANDLER_PROJECT_ID=="string"?r.__HANDLER_PROJECT_ID:"handler-default"}function Ir(){return`handler_preview_config_overrides::${Ho()}`}function No(){if(typeof window=="undefined")return[];try{let r=window.localStorage.getItem(Ir());if(!r)return[];let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch{return[]}}function cn(r){if(typeof window!="undefined")try{window.localStorage.setItem(Ir(),JSON.stringify(r))}catch{}}function At(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function ji(r){if(typeof window!="undefined"){window.__enableConfigOverrides=r;try{window.localStorage.setItem(Mr,r?"true":"false")}catch{}}}function le(r,e={}){var u,g;let{objectId:t,path:n,value:i}=r,{silent:a=!1,persist:s=!0,emitEvent:o=!0}=e,l=on();if(!l){console.warn("[CONFIG] applyConfigOverride: No editable config found in window.__editableConfig");return}let c=t?(g=(u=l.objects)==null?void 0:u.get)==null?void 0:g.call(u,t):l.engine;if(!c){console.warn("[CONFIG] applyConfigOverride: Override target not found:",{objectId:t,path:n,hasObjects:!!l.objects});return}a||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:n,value:i});let p;try{p=Rr(c,n),St(c,n,i)}catch(m){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:n,value:i},m);return}if(e.trackHistory!==!1){window.__configChanges=window.__configChanges||[];let m=window.__configChanges;m.push({objectId:t,path:n,oldValue:p,newValue:i,ts:Date.now()}),m.length>_i&&m.shift(),window.__configChangeRedo=[]}if(s){let m=K(),h=m.findIndex(f=>f.objectId===t&&f.sceneId===r.sceneId&&f.path===n);h>=0?m[h].value=i:m.push(r),window.__configOverrides=m,cn(m),At()||ji(!0)}a||console.log("[CONFIG] Applied override:",r),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:r}))}function Ce(r,e={}){let t=e.emitEvent!==!1,n=[];for(let i of r)i!=null&&i.objectId&&typeof i.objectId=="string"&&n.push(i.objectId),le(i,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let i=Array.from(new Set(n));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:i,count:r.length}}))}}function te(){window.__configOverrides=[],window.__configChanges=[],window.__configChangeRedo=[],cn([]),console.log("[CONFIG] Cleared all overrides")}function Pr(r){let e=K().filter(n=>n.objectId!==r);window.__configOverrides=e,cn(e);let t=window.__configChanges||[];window.__configChanges=t.filter(n=>n.objectId!==r),ln(r),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:r}}))}function Ct(r,e){let t=K().filter(i=>i.objectId!==r||i.path!==e);window.__configOverrides=t,cn(t);let n=window.__configChanges||[];window.__configChanges=n.filter(i=>i.objectId!==r||i.path!==e),r?ln(r):Pi(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:r,path:e}}))}function K(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=No()),window.__configOverrides||[])}function dn(){var a;if(typeof window=="undefined")return!1;let r=window.__configChanges||[];if(r.length===0)return!1;let e=r.pop();window.__configChangeRedo=window.__configChangeRedo||[];let t=window.__configChangeRedo;if(e.changeType==="object_create"){let{screenId:s}=e.metadata||{};return e.objectId&&s&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:s})}).catch(o=>console.error("[CONFIG] Failed to delete object on undo:",o)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Deleted object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:s,objectConfigId:o}=e.metadata||{},l=e.oldValue;return e.objectId&&s&&l&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:s,instanceId:e.objectId,objectConfigId:o||((a=l==null?void 0:l.identity)==null?void 0:a.id),config:l})}).catch(c=>console.error("[CONFIG] Failed to recreate object on undo:",c)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Recreated object",e.objectId),!0}t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType});let n=Mi(),i=!1;if(n){let s=e.objectId?Ii(n.objects,e.objectId):n.engine;if(s){let o=Rr(s,e.path);JSON.stringify(o)===JSON.stringify(e.oldValue)&&(i=!0)}}return i?Ct(e.objectId,e.path):(le({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?ln(e.objectId):Pi()),console.log("[CONFIG] Undo:",e.path),!0}function pn(){var n;if(typeof window=="undefined")return!1;let r=window.__configChangeRedo||[];if(r.length===0)return!1;let e=r.pop();if(e.changeType==="object_create"){let{screenId:i,objectConfigId:a}=e.metadata||{},s=e.newValue;return e.objectId&&i&&s&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:e.objectId,objectConfigId:a||((n=s==null?void 0:s.identity)==null?void 0:n.id),config:s})}).catch(l=>console.error("[CONFIG] Failed to recreate object on redo:",l)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Recreated object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:i}=e.metadata||{};return e.objectId&&i&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:i})}).catch(s=>console.error("[CONFIG] Failed to delete object on redo:",s)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Deleted object",e.objectId),!0}return window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType}),le({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?ln(e.objectId):Pi(),console.log("[CONFIG] Redo:",e.path),!0}function jr(r,e,t){var i;if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:r,path:"__object_create__",oldValue:null,newValue:t,ts:Date.now(),changeType:"object_create",metadata:{screenId:e,objectConfigId:(i=t==null?void 0:t.identity)==null?void 0:i.id}}),window.__configChangeRedo=[],n.length>_i&&n.shift(),console.log("[CONFIG] Tracked object creation:",r)}function Or(r,e,t){if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:r,path:"__object_delete__",oldValue:t,newValue:null,ts:Date.now(),changeType:"object_delete",metadata:{screenId:e}}),window.__configChangeRedo=[],n.length>_i&&n.shift(),console.log("[CONFIG] Tracked object deletion:",r)}function St(r,e,t){var s;let n=e.split("."),i=n.pop(),a=r;for(let o of n){if(a[o]!==void 0&&typeof a[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);a[o]=(s=a[o])!=null?s:{},a=a[o]}a[i]=t}function Rr(r,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,r)}function V(r){if(r===null||typeof r!="object")return r;if(r instanceof Date)return new Date(r.getTime());if(r instanceof Set)return new Set([...r].map(t=>V(t)));if(ArrayBuffer.isView(r))return r.slice();if(r instanceof Array)return r.map(t=>V(t));if(r instanceof Map){let t=new Map;return r.forEach((n,i)=>t.set(i,V(n))),t}let e={};for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=V(r[t]));return e}function De(){let r=window.__editableConfigBaseline;if(!r){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return Lr(e)}return Lr(r)}function Lr(r){let e={objects:{},scenes:{},engine:V(r.engine||{})},t=r.objects;if(t instanceof Map)t.forEach((a,s)=>{e.objects[s]=V(a)});else if(t&&typeof t=="object")for(let a in t)e.objects[a]=V(t[a]);let n=r.scenes;if(n instanceof Map)n.forEach((a,s)=>{e.scenes[s]=V(a)});else if(n&&typeof n=="object")for(let a in n)e.scenes[a]=V(n[a]);let i=K();for(let a of i)a.objectId?(e.objects[a.objectId]||(e.objects[a.objectId]={}),St(e.objects[a.objectId],a.path,a.value)):a.sceneId?(e.scenes[a.sceneId]||(e.scenes[a.sceneId]={}),St(e.scenes[a.sceneId],a.path,a.value)):St(e.engine,a.path,a.value);return e}function Te(){let r=K(),e=new Set;for(let t of r)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:r.length,hasChanges:r.length>0,overrides:r}}async function un(r){let e=De(),t={};for(let[i,a]of Object.entries(e.objects)){let s=a,o=i;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${i}`),s&&typeof s=="object"&&(s.identity||(s.identity={}),s.identity.id=o),t[`objects/${o}.json`]=s}e.engine&&(e.engine.runtime&&(t["engine/engine.runtime.json"]=e.engine.runtime),e.engine.assets&&(t["engine/engine.assets.json"]=e.engine.assets),e.engine.splash&&(t["engine/engine.splash.json"]=e.engine.splash),e.engine.loading&&(t["engine/engine.loading.json"]=e.engine.loading),e.engine.start&&(t["engine/engine.start.json"]=e.engine.start),e.engine.tutorial&&(t["engine/engine.tutorial.json"]=e.engine.tutorial),e.engine.endgame&&(t["engine/engine.endgame.json"]=e.engine.endgame),!e.engine.runtime&&!e.engine.assets&&(t["engine/engine.json"]=e.engine));for(let[i,a]of Object.entries(e.scenes)){let s=i.startsWith("scene.")?i:`scene.${i}`;t[`scenes/${s}.json`]=a}let n=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:K().length>0,versionName:r})});if(!n.ok){let i=await n.json();throw new Error(`Apply failed: ${i.error||"Unknown error"}`)}te();try{let i=on();i&&(window.__editableConfigBaseline=V(i))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Tt(){te(),window.location.reload()}async function gn(){if(!confirm("This will restore all configs to their original state. All uncommitted changes in cache AND applied changes will be lost. Continue?"))return;let e=await fetch("/api/reset-to-original",{method:"POST"});if(!e.ok){let t=await e.json();throw new Error(`Reset failed: ${t.error||"Unknown error"}`)}te(),window.location.reload()}var Mr,_i,_r,X=pe(()=>{"use strict";Mr="handler_preview_override_mode";if(typeof window!="undefined"){let r=window.localStorage.getItem(Mr);window.__enableConfigOverrides=r===null?!0:r==="true"}_i=500;_r={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[],window.__configChangeRedo=[]}}});function Fo(r,e){try{if(typeof r=="object"&&r!==null)return r;if(typeof r!="string")return null;if(r.startsWith("data:")){let n=r.indexOf(",");if(n===-1)return null;let i=r.slice(0,n);if(!i.includes("application/json")&&!i.includes("text/plain"))return null;let a=r.slice(n+1),s=i.includes("base64")?typeof atob=="function"?atob(a):a:decodeURIComponent(a);return JSON.parse(s)}let t=r.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(r):null}catch{return null}}function Bo(r){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=r.replace(/^\.\/+/,""),n=t.split("/").pop()||t,i=[t,n,t.replace(/\.json$/,""),n.replace(/\.json$/,"")];for(let a of i){let s=e[a];if(s){let o=Fo(s,a);if(o!==null)return o}}return null}async function Lt(r){if(Oi.has(r)&&!Ri)return console.log(`[CONFIG] Using cached config for: "${r}"`),Oi.get(r);if(console.log(`[CONFIG] loadConfigFile called with: "${r}", MODE: ${N.toUpperCase()}, CACHE: ${Ri?"DISABLED":"ENABLED"}`),N==="publish"){let n=Bo(r);return n?(console.log(`[CONFIG] \u2713 Loaded ${r} via INLINE_ASSETS`),n):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${r} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}N==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${r}"`);let e;N==="brand"?e=[`./${r.split("/").pop()||r}`,`./${r}`,`./${r.replace(/^configs\//,"")}`,`./${r.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${r}`,`./${r.replace(/^configs\//,"")}`,`./${r.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(n=>n.startsWith("./")?[n,`/${n.slice(2)}`]:n.startsWith("/")?[n]:[n,`/${n}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let n=Ri?"no-store":"force-cache";for(let i of e)try{let a=await fetch(i,{cache:n});if(!a.ok)continue;let s=await a.json();return console.log(`[CONFIG] \u2713 Loaded ${r} via ${i}`,s),s}catch(a){console.warn(`[CONFIG] \u2717 Failed to load ${i} (mode: ${N}):`,a)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${r}; using defaults`),{}})();return Oi.set(r,t),t}async function hn(){console.log("[CONFIG] Loading component schemas...");let r=["components/identity.schema.json","components/transform.schema.json","components/render.schema.json","components/motion.schema.json","components/effects.schema.json","components/interaction.schema.json","components/gameplay.rules.schema.json","components/gameplay.tuning.schema.json","components/visibility.schema.json","components/audio.schema.json","components/physics.schema.json","components/ui.schema.json"],e=new Map;for(let t of r)try{let n=N==="publish"||N==="brand"?t.split("/").pop()||t:`configs/${t}`,i=await Lt(n);i.component&&(e.set(i.component,i),console.log(`[CONFIG] \u2713 Schema loaded: ${i.component} ${N==="publish"||N==="brand"?"(flattened)":"(nested)"}`))}catch(n){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,n)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function Le(r){console.log(`[CONFIG] Loading object config: ${r}`);let e=N==="publish"||N==="brand"?`${r}.json`:`configs/objects/${r}.json`;return await Lt(e)}async function fn(r){let e=new Map;if(r.objects&&Array.isArray(r.objects)){for(let t of r.objects)if(t.enabled&&t.object_config)try{let n=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(n)||(n=`json.${n}`);let i=await Le(n);(!i||Object.keys(i).length===0)&&n!==t.instance_id&&(i=await Le(t.instance_id)),!i||Object.keys(i).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),i=await Le(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...i,instance_id:t.instance_id,object_config:t.object_config})}catch(n){console.warn(`Failed to load object ${t.object_config}:`,n)}}return e}async function mn(){console.log("[CONFIG] Loading engine configs...");let r=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(r.map(n=>{let i=`engine.${n}.json`,a=N==="publish"||N==="brand"?i:`configs/engine/${i}`;return Lt(a)})),t=Object.fromEntries(r.map((n,i)=>[n,e[i]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(r.map(n=>{var s;let i=(s=t[n])!=null?s:{},a=Object.keys(i);return[n,a.length>0?a:"empty"]}))),t}async function zi(){return await Lt(N==="publish"||N==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function bn(r="scene.main"){console.log(`[CONFIG] Loading scene config: ${r}`);let e=N==="publish"||N==="brand"?`${r}.json`:`configs/scenes/${r}.json`;return await Lt(e)}function tt(r,e){let t=[];if(!r.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let n=e.get("identity");if(n)for(let i of n.required||[])r.identity[i]||t.push(`Missing required identity field: ${i}`);for(let[i,a]of Object.entries(r)){if(i==="identity")continue;let s=e.get(i);if(s&&a&&typeof a=="object"){let o=a;for(let l of s.required||[])o[l]===void 0&&t.push(`Missing required field in ${i}: ${l}`);if(s.constraints&&typeof s.constraints=="object")for(let[l,c]of Object.entries(s.constraints)){let p=o[l];if(p!==void 0&&c&&typeof c=="object"){let d=c;typeof p=="number"&&(d.min!==void 0&&p<d.min&&t.push(`${i}.${l} value ${p} is below minimum ${d.min}`),d.max!==void 0&&p>d.max&&t.push(`${i}.${l} value ${p} is above maximum ${d.max}`))}}}}return{valid:t.length===0,errors:t}}function Ne(r,e){let t={...r},n=["identity","transform","render"];for(let[i,a]of e.entries())a.defaults&&Object.keys(a.defaults).length>0&&(n.includes(i)||t[i])&&(t[i]||(t[i]={}),t[i]={...a.defaults,...t[i]});return t}function ne(r,e,t,n){return typeof r!="number"||!Number.isFinite(r)?e:Math.min(Math.max(r,t),n)}function $r(r,e){if(Array.isArray(r))return{x:ne(r[0],e.x,-2e3,2e3),y:ne(r[1],e.y,-2e3,2e3)};if(!r||typeof r!="object")return e;let{x:t,y:n}=r;return{x:ne(t,e.x,-2e3,2e3),y:ne(n,e.y,-2e3,2e3)}}function Uo(r,e){if(Array.isArray(r))return{x:ne(r[0],e.x,0,1),y:ne(r[1],e.y,0,1)};if(!r||typeof r!="object")return e;let{x:t,y:n}=r;return{x:ne(t,e.x,0,1),y:ne(n,e.y,0,1)}}function Go(r){if(Array.isArray(r))return{x:ne(r[0],.5,-10,10),y:ne(r[1],.5,-10,10)};if(r&&typeof r=="object"){let{x:e,y:t}=r;return{x:ne(e,.5,-10,10),y:ne(t,.5,-10,10)}}return typeof r=="string"?r:null}async function ye(r="scene.main",e){var l,c,p,d,u,g,m,h,f,b,y,v,S,C;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await hn(),n=K();n.length>0&&console.log(`[CONFIG] Applying ${n.length} active overrides`);let i=await bn(r);console.log(`[CONFIG] Scene config loaded: ${((l=i.objects)==null?void 0:l.length)||0} objects`);let a=await mn();console.log("[CONFIG] Loading object configs...");let s=await fn(i);console.log(`[CONFIG] Loaded ${s.size} object configs:`,Array.from(s.keys()));for(let[k,z]of s.entries()){let w=Ne(z,t),x=tt(w,t);x.valid||console.warn(`Object ${k} validation errors:`,x.errors),(c=w.transform)!=null&&c.position&&(w.transform.position=$r(w.transform.position,{x:0,y:0})),(p=w.transform)!=null&&p.offset&&(w.transform.offset=$r(w.transform.offset,{x:0,y:0})),((d=w.transform)==null?void 0:d.anchor)!==void 0&&(w.transform.anchor=Go(w.transform.anchor)),((u=w.transform)==null?void 0:u.position_ratio)!==void 0&&w.transform.position_ratio!==null&&(w.transform.position_ratio=Uo(w.transform.position_ratio,{x:.5,y:.5})),s.set(k,w)}if(e){if(e.objects)for(let[k,z]of e.objects.entries())s.set(k,z);e.engine&&(a.runtime={...a.runtime,...e.engine.runtime},a.assets={...a.assets,...e.engine.assets},a.splash={...(g=a.splash)!=null?g:{},...(m=e.engine.splash)!=null?m:{}})}let o={objects:s,engine:a,scene:i,schemas:t,theme:{background_color:"#ffffff",text_color:"#000000",square_color:"#cccccc",cta_background:"#007bff",cta_text:"#ffffff"},gameplay:{}};return typeof window!="undefined"&&(window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=Ne(o,t))),n.length>0&&At()&&Ce(n,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(s.keys()),engine:{runtime:Object.keys((h=a.runtime)!=null?h:{}),assets:Object.keys((f=a.assets)!=null?f:{}),splash:Object.keys((b=a.splash)!=null?b:{}),loading:Object.keys((y=a.loading)!=null?y:{}),start:Object.keys((v=a.start)!=null?v:{}),tutorial:Object.keys((S=a.tutorial)!=null?S:{}),endgame:Object.keys((C=a.endgame)!=null?C:{})},scene:i.scene_id||"unknown"}),o}function $i(r){var t,n,i,a,s,o,l,c,p,d,u,g,m,h,f,b,y,v,S,C,k,z,w,x,M,A,E,I,L,_,P,R,T;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[j,O]of r.objects.entries()){let H=((t=O.identity)==null?void 0:t.id)||j;H.includes("character")&&(e.gameplay.character_pos=((n=O.transform)==null?void 0:n.position)||{x:0,y:0},e.gameplay.character_scale=((i=O.transform)==null?void 0:i.scale)||1,e.gameplay.character_anim_speed=((s=(a=O.gameplay)==null?void 0:a.tuning)==null?void 0:s.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(o=O.gameplay)==null?void 0:o.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((p=(c=O.gameplay)==null?void 0:c.tuning)==null?void 0:p.relief_speed)||.22),(H.includes("gun")||H.includes("flame"))&&(e.gameplay.gun=O.gun||{},e.gameplay.gunmuzzle=((d=O.effects)==null?void 0:d.gunmuzzle)||{},e.gameplay.muzzle_levels=((u=O.effects)==null?void 0:u.muzzle_levels)||{},e.gameplay.flame=((g=O.effects)==null?void 0:g.flame)||{}),H.includes("diamond")&&(e.gameplay.diamond=O),H.includes("ice")&&(e.gameplay.melt=O.melt||{},e.gameplay.melt_anchor=((m=O.transform)==null?void 0:m.melt_anchor)||{x:0,y:0},e.gameplay.melt_pos=((h=O.transform)==null?void 0:h.position)||{x:0,y:0},e.gameplay.hybrid_melting=((f=O.effects)==null?void 0:f.hybrid_melting)||{},e.gameplay.physics_chunks=((b=O.effects)==null?void 0:b.physics_chunks)||{},e.gameplay.melting_particles=((y=O.effects)==null?void 0:y.melting_particles)||{},e.gameplay.hard_ice=O.hard_ice||{}),H.includes("water")&&(e.gameplay.water_drops=O),H.includes("crack")&&(e.gameplay.crack=O),H.includes("hand")&&(e.gameplay.hand=((v=O.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((S=O.transform)==null?void 0:S.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((C=O.transform)==null?void 0:C.scale)||1.5),H.includes("hazard")&&(e.gameplay.hazard=((k=O.gameplay)==null?void 0:k.tuning)||{},e.gameplay.danger_pos=((z=O.transform)==null?void 0:z.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((x=(w=O.gameplay)==null?void 0:w.tuning)==null?void 0:x.danger_pulse)||{},e.gameplay.hazard_height=((A=(M=O.gameplay)==null?void 0:M.tuning)==null?void 0:A.hazard_height)||140)}return e.gameplay.timeline=((E=r.engine.runtime)==null?void 0:E.timeline)||{},e.gameplay.drag_surface=((I=r.engine.runtime)==null?void 0:I.drag_surface)||{},e.gameplay.background=((L=r.engine.runtime)==null?void 0:L.background)||{},e.gameplay.ui_styles=((_=r.engine.runtime)==null?void 0:_.ui_styles)||{},e.gameplay.label_pulse=((P=r.engine.runtime)==null?void 0:P.label_pulse)||{},e.ui=((R=r.engine.runtime)==null?void 0:R.ui)||{},e.theme=((T=r.engine.runtime)==null?void 0:T.theme)||{},e.assets=r.engine.assets||{},e}var zr,N,Oi,Ri,Di=pe(()=>{"use strict";X();zr=null,N="dev";if(typeof window!="undefined"){let r=window.__BUILD_SETTINGS__;if(r!=null&&r.buildMode)zr=r,N=r.buildMode,console.log("[CONFIG] Loaded inline build settings:",r,"buildMode:",N);else try{let e=new XMLHttpRequest;if(e.open("GET","./build-settings.json",!1),e.send(),e.status===200&&e.responseText){let t=JSON.parse(e.responseText);zr=t,N=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",N)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",N)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",N);Oi=new Map,Ri=N==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Hi(r,e){let t=[];function n(i,a,s=""){if(i!==a){if(typeof i!=typeof a){t.push(`${s}: type changed`);return}if(typeof i=="object"&&i!==null&&a!==null){let o=new Set([...Object.keys(i),...Object.keys(a)]);for(let l of o){let c=s?`${s}.${l}`:l;l in i?l in a?n(i[l],a[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${s}: changed`)}}return n(r,e),t}function Ni(r,e,t,n){let i={...t};for(let[a,s]of n.entries())i[a]&&s.defaults&&(i[a]={...s.defaults,...i[a]});return i}var kt,Fe,Fi=pe(()=>{"use strict";kt=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},Fe=class{constructor(e=1e3){this.pollingInterval=null;this.fileHashes=new Map;this.callbacks=new Map;this.intervalMs=e}watch(e,t){this.callbacks.set(e,t),this.pollingInterval===null&&(this.pollingInterval=window.setInterval(()=>{this.checkAllFiles()},this.intervalMs))}async checkAllFiles(){for(let[e,t]of this.callbacks.entries())try{let n=`${e}?t=${Date.now()}&r=${Math.random()}`,i=await fetch(n,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(i.ok){let a=await i.text(),s=this.hashString(a),o=this.fileHashes.get(e);if(o&&o!==s&&console.log(`[HOT-RELOAD] File changed: ${e}`),o&&o!==s){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,s)}else o||this.fileHashes.set(e,s)}}catch(n){console.warn(`Failed to check ${e}:`,n)}}determineEventType(e){var t,n;return e.includes("/components/")?{type:"component",path:e,componentName:(t=e.split("/").pop())==null?void 0:t.replace(".schema.json","")}:e.includes("/engine/")?{type:"engine",path:e}:e.includes("/scenes/")?{type:"scene",path:e}:e.includes("/objects/")?{type:"object",path:e,objectId:(n=e.split("/").pop())==null?void 0:n.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);t=(t<<5)-t+i,t=t&t}return t.toString()}unwatch(e){this.callbacks.delete(e),this.fileHashes.delete(e)}stop(){this.pollingInterval!==null&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.callbacks.clear(),this.fileHashes.clear()}}});function Ui(r){if(typeof window=="undefined")return;let e=typeof Bi!="undefined"&&!!Bi.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let i=null,a=!1,s=null;if(t){s=new Fe;let m=window.__configWatcher;m!=null&&m.stop&&m.stop(),window.__configWatcher=s}let o=new Set,l=m=>{var b,y;if(!s)return;let h=new Set;h.add("configs/engine/engine.runtime.json"),h.add("configs/engine/engine.assets.json"),h.add("configs/engine/engine.splash.json"),h.add("configs/scenes/scene.main.json");let f=(y=(b=m.scene)==null?void 0:b.objects)!=null?y:[];for(let v of f)v!=null&&v.object_config&&h.add(`configs/objects/${v.object_config}.json`);for(let v of o)h.has(v)||s.unwatch(v);for(let v of h)o.has(v)||s.watch(v,S=>g(S));o=h},c=new Set,p=!1,d=async m=>{let h=await Le(m),f=Ne(h,r.activeConfig.schemas),b=tt(f,r.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${m} validation errors:`,b.errors),await r.liveEditBridge.applyObjectConfig(m,f)};async function u(m){if(!a){a=!0;try{if(p||c.size===0){r.audioSystem.destroy();let h=await ye("scene.main");r.setActiveConfig(h),r.gameObjectManager.updateConfig(h),r.CustomAssets.updateConfig(h),await r.CustomAssets.ready();let f=r.createAudioSystem(h);r.setAudioSystem(f),window.__audioSystem=f,await f.start(),r.liveEditBridge.rebuildIndexes(),l(h),console.log(`[GAME] Hot-reload complete (${m})`)}else{let h=Array.from(c);c.clear();for(let f of h)await d(f);console.log(`[GAME] Hot-reload updated objects: ${h.join(", ")}`)}}catch(h){console.warn("[GAME] Hot-reload failed:",h)}finally{a=!1,p=!1,c.clear()}}}function g(m){m.type==="object"&&m.objectId?c.add(m.objectId):p=!0,i&&window.clearTimeout(i),i=window.setTimeout(()=>{u(m.type)},120)}e&&Bi.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(r.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var Bi,Dr=pe(()=>{"use strict";Fi();Di();Bi={}});var Hr={};bt(Hr,{ConfigWatcher:()=>Fe,DefaultReloadStrategy:()=>kt,applyDefaults:()=>Ne,diffConfigs:()=>Hi,loadAllObjectConfigs:()=>fn,loadComponentSchemas:()=>hn,loadEngineConfig:()=>mn,loadGamePromptConfig:()=>zi,loadObjectCentricConfig:()=>ye,loadObjectConfig:()=>Le,loadSceneConfig:()=>bn,rehydrateObject:()=>Ni,setupHotReload:()=>Ui,toLegacyFormat:()=>$i,validateObjectConfig:()=>tt});var yn=pe(()=>{"use strict";Di();Fi();Dr()});var As={};bt(As,{AssetEditorModal:()=>Ea});var Ea,Sa=pe(()=>{"use strict";Ea=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,n,i){this.currentObjectId=e,this.currentPath=t,this.currentAsset=n,this.onApplyCallback=i,this.createModal(e,n),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let n=document.createElement("div");n.className="asset-editor-modal",n.innerHTML=`
|
|
1
|
+
"use strict";var Ys=Object.create;var Kt=Object.defineProperty;var Ks=Object.getOwnPropertyDescriptor;var Xs=Object.getOwnPropertyNames;var Js=Object.getPrototypeOf,Zs=Object.prototype.hasOwnProperty;var he=(r,e)=>()=>(r&&(e=r(r=0)),e);var vt=(r,e)=>{for(var t in e)Kt(r,t,{get:e[t],enumerable:!0})},Ba=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Xs(e))!Zs.call(r,i)&&i!==t&&Kt(r,i,{get:()=>e[i],enumerable:!(n=Ks(e,i))||n.enumerable});return r};var Ze=(r,e,t)=>(t=r!=null?Ys(Js(r)):{},Ba(e||!r||!r.__esModule?Kt(t,"default",{value:r,enumerable:!0}):t,r)),Qs=r=>Ba(Kt({},"__esModule",{value:!0}),r);var fe,wi=he(()=>{"use strict";fe=class{static get(e){var t;return(t=this.store.get(e))==null?void 0:t.data}static set(e,t){this.store.set(e,{data:t})}static has(e){return this.store.has(e)}static clear(){this.store.clear()}};fe.store=new Map});function oo(){var r,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(r=document.querySelector("script"))==null?void 0:r.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),n=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!n)}catch{return!1}}async function lo(){try{if(typeof window!="undefined"){let r=await fetch("./build-settings.json");if(r.ok){let e=await r.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function co(){try{if(typeof window!="undefined"){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);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function po(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${B}`),Object.keys(me).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(me)),me;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),me={...window.INLINE_ASSETS},me;if(!(B==="publish"&&oe!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),me;if(!xi){let e=typeof window!="undefined"?new URL("inline-assets.js",window.location.href).href:"./inline-assets.js";console.log("[AssetLoader] Loading inline assets from:",e),xi=(async()=>{try{try{let a=await import(e+"?t="+Date.now());if(a.INLINE_ASSETS)return console.log("[AssetLoader] Loaded INLINE_ASSETS via ES module:",Object.keys(a.INLINE_ASSETS)),a.INLINE_ASSETS}catch(a){console.warn("[AssetLoader] ES module import failed, trying text parse:",a)}let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let n=await t.text();console.log("[AssetLoader] Received JS code, length:",n.length);let i=n.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(i)try{let a=i[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let s=new Function("return "+a)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(s)),s}catch(a){return console.warn("[AssetLoader] Failed to parse inline assets:",a),{}}else return console.warn("[AssetLoader] INLINE_ASSETS export not found in response"),console.log("[AssetLoader] JS code preview:",n.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return me=await xi,console.log("[AssetLoader] Final inline assets cache:",Object.keys(me)),me}function Ei(r){return r===null||typeof r!="object"||(Object.freeze(r),Object.values(r).forEach(e=>Ei(e))),r}function uo(r=64,e=64,t=16711680){let n=document.createElement("canvas");n.width=r,n.height=e;let i=n.getContext("2d");return i.fillStyle=`#${t.toString(16).padStart(6,"0")}`,i.fillRect(0,0,r,e),i.strokeStyle="#000",i.strokeRect(0,0,r,e),i.fillStyle="#fff",i.font="10px sans-serif",i.textAlign="center",i.fillText("MISSING",r/2,e/2),be.Texture.from(n)}function Si(r,e){xr.set(r,e)}var be,vr,wr,De,B,oe,Te,me,xi,xr,He,Qt=he(()=>{"use strict";be=require("pixi.js");wi();vr=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",wr=oo(),De=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,B=wr?"publish":vr,oe=De==null?void 0:De.assetsInlined;De!=null&&De.buildMode&&(B=De.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${B}`));Te=co();Te!=null&&Te.buildMode&&(B=Te.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${B}`));(Te==null?void 0:Te.assetsInlined)!==void 0&&(oe=Te.assetsInlined);lo().then(r=>{r!=null&&r.buildMode&&r.buildMode!==B&&(B=r.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${B}`)),(r==null?void 0:r.assetsInlined)!==void 0&&(oe=r.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${vr}, Runtime: ${wr?"publish":"dev"}, Effective: ${B}`);me={},xi=null;xr=new Map;He=class{static async load(e,t,n,i){let a=`${e}:${t.path}`,s=fe.get(a);if(s!==void 0)return s;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${B}`),console.log(`[AssetLoader] Window defined: ${typeof window!="undefined"}, INLINE_ASSETS exists: ${!!(typeof window!="undefined"&&window.INLINE_ASSETS)}, keys: ${typeof window!="undefined"&&window.INLINE_ASSETS?Object.keys(window.INLINE_ASSETS).length:"N/A"}`);let o=await po(),l=o[e];if(!l&&i&&(l=o[i],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${i}`)),!l&&t.path){let d=t.path.split("/");if(d.length>=2){let u=d[d.length-1].split(".")[0];o[u]&&(l=o[u],console.log(`[AssetLoader] Found inline data for ${e} using assetName: ${u}`))}}if(console.log("[AssetLoader] Inline data for",e,":",l?"FOUND":"NOT FOUND"),B==="publish"&&oe!==!1&&(console.log("[AssetLoader] \u26A0\uFE0F PUBLISH MODE DETECTED - inline assets are MANDATORY"),!l))throw new Error(`[AssetLoader] PUBLISH MODE: Inline asset required but NOT FOUND for object: ${e}, path: ${t.path}`);let p=xr.get(t.type);if(p)try{let d=await p(t.path,l,e,n);return fe.set(a,d),d}catch(d){return this.handleFailure(e,t.type,d)}try{let d;switch(t.type){case"image":d=await this.loadImage(t.path,l);break;case"json":d=await this.loadJSON(t.path,l),d=Ei(d);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return fe.set(a,d),d}catch(d){return this.handleFailure(e,t.type,d)}}static async loadImage(e,t){let n=B==="publish",i=n&&oe!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${B}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for object. Path: ${e}`);if(typeof t!="string"||!t.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof t}`);try{return await be.Assets.load(t)}catch(a){throw console.error("[AssetLoader] Failed to load texture from data URI:",a),a}}if(t&&typeof t=="string"&&t.startsWith("data:"))try{return await be.Assets.load(t)}catch(a){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",a),await be.Assets.load(e)}return await be.Assets.load(e)}static async loadJSON(e,t){let n=B==="publish",i=n&&oe!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${B}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let s=atob(t.split(",")[1]);return JSON.parse(s)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let s=atob(t.split(",")[1]);return JSON.parse(s)}return JSON.parse(t)}let a=await fetch(e);if(!a.ok)throw new Error(`JSON fetch failed: ${e}`);return a.json()}static handleFailure(e,t,n){if(B==="dev"){let a=t==="image"?uo():Ei({__placeholder:!0,type:t});return fe.set(e+":"+((n==null?void 0:n.path)||"missing"),a),a}throw n}};Si("image",async(r,e)=>{let t=B==="publish",n=t&&oe!==!1,i=B==="brand",a=t&&oe===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${B}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${r}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return be.Assets.load(e)}let s=r;return(i||a)&&r&&!r.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=r,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${r}" as-is`)):(s=`assets/${r}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${r}" -> "${s}"`))),be.Assets.load(e||s)});Si("json",async(r,e)=>{let t=B==="publish",n=t&&oe!==!1,i=B==="brand",a=t&&oe===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${B}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${r}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let s=r;if((i||a)&&r&&!r.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=r,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${r}" as-is`)):(s=`assets/${r}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${r}" -> "${s}"`))),e)return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e);let o=await fetch(s);if(!o.ok)throw new Error(`JSON fetch failed: ${r}`);return o.json()})});var Sr={};vt(Sr,{AssetTextures:()=>le,initAssetTextures:()=>Ti});function Ti(r,e){Er.init(r,e),typeof window!="undefined"&&(window.__AssetTextures=le)}var Ci,Er,le,nt=he(()=>{"use strict";Qt();Ci=class{constructor(){this.textures=new Map;this.readyPromise=null;this.priorityReadyPromise=null;this.priorityReadyResolve=null;this.config=null;this.app=null;this.attempted=new Set;this.waiters=new Set}init(e,t){if(this.config===e&&this.app===t&&this.priorityReadyPromise){console.log("[AssetTextures] init called with same config/app; keeping existing state");return}this.textures.clear(),this.readyPromise=null,this.priorityReadyPromise=null,this.priorityReadyResolve=null,this.attempted.clear(),this.waiters.clear(),this.priorityReadyPromise=new Promise(n=>{this.priorityReadyResolve=n}),this.config=e,this.app=t,console.log("[AssetTextures] Initialized with config, cleared previous textures")}async ready(){if(this.readyPromise){await this.readyPromise;return}if(!this.config)throw new Error("[AssetTextures] Must call init() before ready() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before ready() - app is null");let e=this.config,t=this.app;return this.readyPromise=(async()=>{var s;console.log("[AssetTextures] Loading all assets...");let n=new Set(["background_loading_1"]),i=[],a=[];for(let[o,l]of e.objects.entries()){let c=(s=l.render)==null?void 0:s.asset;if(!c)continue;let p=async()=>{var d;try{let u=(d=l.identity)==null?void 0:d.id;console.log(`[AssetTextures] Loading ${c.type}: ${o} (${u})`);let g=await He.load(o,c,t,u);this.textures.set(o,g),console.log(`[AssetTextures] \u2713 Loaded: ${o}`)}catch(u){console.error(`[AssetTextures] \u2717 Failed to load: ${o}`,u)}finally{this.attempted.add(o);try{for(let u of Array.from(this.waiters))u()}catch{}}};n.has(o)?i.push(p()):a.push(p())}i.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(i),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(a),console.log("[AssetTextures] All textures loaded:",Array.from(this.textures.keys()))})(),this.readyPromise}async priorityReady(){return this.priorityReadyPromise?this.priorityReadyPromise:Promise.resolve()}async waitFor(e,t={}){if(!this.config)throw new Error("[AssetTextures] Must call init() before waitFor() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before waitFor() - app is null");let i=Array.from(new Set((e||[]).filter(o=>typeof o=="string"&&o))).filter(o=>{var l,c,p,d;try{let u=(p=(c=(l=this.config)==null?void 0:l.objects)==null?void 0:c.get)==null?void 0:p.call(c,o);return!!((d=u==null?void 0:u.render)!=null&&d.asset)}catch{return!1}});if(i.length===0)return;this.ready().catch(()=>{});let a=()=>i.every(o=>this.textures.has(o)||this.attempted.has(o));if(a())return;let s=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(o=>{let l=!1,c=()=>{l||a()&&(l=!0,this.waiters.delete(c),o())};this.waiters.add(c),c(),s>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:i}),o())},s)})}get(e){return this.textures.get(e)}set(e,t){this.textures.set(e,t),console.log(`[AssetTextures] Updated texture: ${e}`)}clear(){this.textures.clear(),this.readyPromise=null,console.log("[AssetTextures] Cleared all textures")}getAllIds(){return Array.from(this.textures.keys())}},Er=new Ci,le=new Proxy(Er,{get(r,e){return e in r&&typeof r[e]=="function"?r[e].bind(r):r.get(e)},set(r,e,t){return r.set(e,t),!0}})});var Be={};vt(Be,{applyConfigOverride:()=>ce,applyConfigOverrides:()=>ke,applyConfigsToDisk:()=>hn,clearConfigOverrides:()=>ne,clearConfigOverridesForObject:()=>_r,configOverrideManager:()=>Pr,deepClone:()=>W,exportConfigsAsJSON:()=>Fe,getConfigOverrides:()=>X,getConfigStateSummary:()=>Ie,getOverrideMode:()=>Tt,redoLastConfigChange:()=>gn,removeConfigOverride:()=>Lt,resetToApplied:()=>kt,resetToOriginal:()=>fn,setOverrideMode:()=>Oi,trackObjectCreation:()=>Or,trackObjectDeletion:()=>Rr,undoLastConfigChange:()=>un});function cn(){return typeof window=="undefined"?null:window.__editableConfig||null}function Mi(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function ji(r,e){var t,n;if(!r)return null;try{if(r instanceof Map)return(t=r.get(e))!=null?t:null;if(typeof r=="object")return(n=r[e])!=null?n:null}catch{}return null}function Do(r,e,t){if(r){if(r instanceof Map){r.set(e,t);return}typeof r=="object"&&(r[e]=t)}}function Ir(r,e){for(let t of e)Ct(r,t.path,t.value)}function dn(r){var o;if(typeof window=="undefined")return;let e=cn();if(!e)return;let t=Mi(),n=(o=t?ji(t.objects,r):null)!=null?o:ji(e.objects,r);if(!n)return;let i=W(n),a=X().filter(l=>l.objectId===r);try{Ir(i,a)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",r,l);return}Do(e.objects,r,i);let s=window.applyEditableObjectConfig;if(typeof s=="function")try{s(r,i)}catch{}}function _i(){var i;if(typeof window=="undefined")return;let r=cn();if(!(r!=null&&r.engine))return;let e=Mi(),t=W(((i=e==null?void 0:e.engine)!=null?i:r.engine)||{}),n=X().filter(a=>!a.objectId&&!a.sceneId);try{Ir(t,n)}catch(a){console.error("[CONFIG] Failed to reapply engine overrides",a);return}try{let a=r.engine;for(let s of Object.keys(a))s in t||delete a[s];for(let[s,o]of Object.entries(t))a[s]=o}catch{r.engine=t}}function Ho(){if(typeof window=="undefined")return"unknown";let r=window;return typeof r.__HANDLER_PROJECT_ID=="string"?r.__HANDLER_PROJECT_ID:"handler-default"}function jr(){return`handler_preview_config_overrides::${Ho()}`}function No(){if(typeof window=="undefined")return[];try{let r=window.localStorage.getItem(jr());if(!r)return[];let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch{return[]}}function pn(r){if(typeof window!="undefined")try{window.localStorage.setItem(jr(),JSON.stringify(r))}catch{}}function Tt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function Oi(r){if(typeof window!="undefined"){window.__enableConfigOverrides=r;try{window.localStorage.setItem(Mr,r?"true":"false")}catch{}}}function ce(r,e={}){var u,g;let{objectId:t,path:n,value:i}=r,{silent:a=!1,persist:s=!0,emitEvent:o=!0}=e,l=cn();if(!l){console.warn("[CONFIG] applyConfigOverride: No editable config found in window.__editableConfig");return}let c=t?(g=(u=l.objects)==null?void 0:u.get)==null?void 0:g.call(u,t):l.engine;if(!c){console.warn("[CONFIG] applyConfigOverride: Override target not found:",{objectId:t,path:n,hasObjects:!!l.objects});return}a||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:n,value:i});let p;try{p=zr(c,n),Ct(c,n,i)}catch(m){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:n,value:i},m);return}if(e.trackHistory!==!1){window.__configChanges=window.__configChanges||[];let m=window.__configChanges;m.push({objectId:t,path:n,oldValue:p,newValue:i,ts:Date.now()}),m.length>Pi&&m.shift(),window.__configChangeRedo=[]}if(s){let m=X(),h=m.findIndex(f=>f.objectId===t&&f.sceneId===r.sceneId&&f.path===n);h>=0?m[h].value=i:m.push(r),window.__configOverrides=m,pn(m),Tt()||Oi(!0)}a||console.log("[CONFIG] Applied override:",r),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:r}))}function ke(r,e={}){let t=e.emitEvent!==!1,n=[];for(let i of r)i!=null&&i.objectId&&typeof i.objectId=="string"&&n.push(i.objectId),ce(i,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let i=Array.from(new Set(n));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:i,count:r.length}}))}}function ne(){window.__configOverrides=[],window.__configChanges=[],window.__configChangeRedo=[],pn([]),console.log("[CONFIG] Cleared all overrides")}function _r(r){let e=X().filter(n=>n.objectId!==r);window.__configOverrides=e,pn(e);let t=window.__configChanges||[];window.__configChanges=t.filter(n=>n.objectId!==r),dn(r),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:r}}))}function Lt(r,e){let t=X().filter(i=>i.objectId!==r||i.path!==e);window.__configOverrides=t,pn(t);let n=window.__configChanges||[];window.__configChanges=n.filter(i=>i.objectId!==r||i.path!==e),r?dn(r):_i(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:r,path:e}}))}function X(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=No()),window.__configOverrides||[])}function un(){var a;if(typeof window=="undefined")return!1;let r=window.__configChanges||[];if(r.length===0)return!1;let e=r.pop();window.__configChangeRedo=window.__configChangeRedo||[];let t=window.__configChangeRedo;if(e.changeType==="object_create"){let{screenId:s}=e.metadata||{};return e.objectId&&s&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:s})}).catch(o=>console.error("[CONFIG] Failed to delete object on undo:",o)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Deleted object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:s,objectConfigId:o}=e.metadata||{},l=e.oldValue;return e.objectId&&s&&l&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:s,instanceId:e.objectId,objectConfigId:o||((a=l==null?void 0:l.identity)==null?void 0:a.id),config:l})}).catch(c=>console.error("[CONFIG] Failed to recreate object on undo:",c)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Recreated object",e.objectId),!0}t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType});let n=Mi(),i=!1;if(n){let s=e.objectId?ji(n.objects,e.objectId):n.engine;if(s){let o=zr(s,e.path);JSON.stringify(o)===JSON.stringify(e.oldValue)&&(i=!0)}}return i?Lt(e.objectId,e.path):(ce({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?dn(e.objectId):_i()),console.log("[CONFIG] Undo:",e.path),!0}function gn(){var n;if(typeof window=="undefined")return!1;let r=window.__configChangeRedo||[];if(r.length===0)return!1;let e=r.pop();if(e.changeType==="object_create"){let{screenId:i,objectConfigId:a}=e.metadata||{},s=e.newValue;return e.objectId&&i&&s&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:e.objectId,objectConfigId:a||((n=s==null?void 0:s.identity)==null?void 0:n.id),config:s})}).catch(l=>console.error("[CONFIG] Failed to recreate object on redo:",l)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Recreated object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:i}=e.metadata||{};return e.objectId&&i&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:i})}).catch(s=>console.error("[CONFIG] Failed to delete object on redo:",s)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Deleted object",e.objectId),!0}return window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType}),ce({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?dn(e.objectId):_i(),console.log("[CONFIG] Redo:",e.path),!0}function Or(r,e,t){var i;if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:r,path:"__object_create__",oldValue:null,newValue:t,ts:Date.now(),changeType:"object_create",metadata:{screenId:e,objectConfigId:(i=t==null?void 0:t.identity)==null?void 0:i.id}}),window.__configChangeRedo=[],n.length>Pi&&n.shift(),console.log("[CONFIG] Tracked object creation:",r)}function Rr(r,e,t){if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:r,path:"__object_delete__",oldValue:t,newValue:null,ts:Date.now(),changeType:"object_delete",metadata:{screenId:e}}),window.__configChangeRedo=[],n.length>Pi&&n.shift(),console.log("[CONFIG] Tracked object deletion:",r)}function Ct(r,e,t){var s;let n=e.split("."),i=n.pop(),a=r;for(let o of n){if(a[o]!==void 0&&typeof a[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);a[o]=(s=a[o])!=null?s:{},a=a[o]}a[i]=t}function zr(r,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,r)}function W(r){if(r===null||typeof r!="object")return r;if(r instanceof Date)return new Date(r.getTime());if(r instanceof Set)return new Set([...r].map(t=>W(t)));if(ArrayBuffer.isView(r))return r.slice();if(r instanceof Array)return r.map(t=>W(t));if(r instanceof Map){let t=new Map;return r.forEach((n,i)=>t.set(i,W(n))),t}let e={};for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=W(r[t]));return e}function Fe(){let r=window.__editableConfigBaseline;if(!r){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return kr(e)}return kr(r)}function kr(r){let e={objects:{},scenes:{},engine:W(r.engine||{})},t=r.objects;if(t instanceof Map)t.forEach((a,s)=>{e.objects[s]=W(a)});else if(t&&typeof t=="object")for(let a in t)e.objects[a]=W(t[a]);let n=r.scenes;if(n instanceof Map)n.forEach((a,s)=>{e.scenes[s]=W(a)});else if(n&&typeof n=="object")for(let a in n)e.scenes[a]=W(n[a]);let i=X();for(let a of i)a.objectId?(e.objects[a.objectId]||(e.objects[a.objectId]={}),Ct(e.objects[a.objectId],a.path,a.value)):a.sceneId?(e.scenes[a.sceneId]||(e.scenes[a.sceneId]={}),Ct(e.scenes[a.sceneId],a.path,a.value)):Ct(e.engine,a.path,a.value);return e}function Ie(){let r=X(),e=new Set;for(let t of r)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:r.length,hasChanges:r.length>0,overrides:r}}async function hn(r){let e=Fe(),t={};for(let[i,a]of Object.entries(e.objects)){let s=a,o=i;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${i}`),s&&typeof s=="object"&&(s.identity||(s.identity={}),s.identity.id=o),t[`objects/${o}.json`]=s}e.engine&&(e.engine.runtime&&(t["engine/engine.runtime.json"]=e.engine.runtime),e.engine.assets&&(t["engine/engine.assets.json"]=e.engine.assets),e.engine.splash&&(t["engine/engine.splash.json"]=e.engine.splash),e.engine.loading&&(t["engine/engine.loading.json"]=e.engine.loading),e.engine.start&&(t["engine/engine.start.json"]=e.engine.start),e.engine.tutorial&&(t["engine/engine.tutorial.json"]=e.engine.tutorial),e.engine.endgame&&(t["engine/engine.endgame.json"]=e.engine.endgame),!e.engine.runtime&&!e.engine.assets&&(t["engine/engine.json"]=e.engine));for(let[i,a]of Object.entries(e.scenes)){let s=i.startsWith("scene.")?i:`scene.${i}`;t[`scenes/${s}.json`]=a}let n=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:X().length>0,versionName:r})});if(!n.ok){let i=await n.json();throw new Error(`Apply failed: ${i.error||"Unknown error"}`)}ne();try{let i=cn();i&&(window.__editableConfigBaseline=W(i))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function kt(){ne(),window.location.reload()}async function fn(){if(!confirm("This will restore all configs to their original state. All uncommitted changes in cache AND applied changes will be lost. Continue?"))return;let e=await fetch("/api/reset-to-original",{method:"POST"});if(!e.ok){let t=await e.json();throw new Error(`Reset failed: ${t.error||"Unknown error"}`)}ne(),window.location.reload()}var Mr,Pi,Pr,J=he(()=>{"use strict";Mr="handler_preview_override_mode";if(typeof window!="undefined"){let r=window.localStorage.getItem(Mr);window.__enableConfigOverrides=r===null?!0:r==="true"}Pi=500;Pr={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[],window.__configChangeRedo=[]}}});function Fo(r,e){try{if(typeof r=="object"&&r!==null)return r;if(typeof r!="string")return null;if(r.startsWith("data:")){let n=r.indexOf(",");if(n===-1)return null;let i=r.slice(0,n);if(!i.includes("application/json")&&!i.includes("text/plain"))return null;let a=r.slice(n+1),s=i.includes("base64")?typeof atob=="function"?atob(a):a:decodeURIComponent(a);return JSON.parse(s)}let t=r.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(r):null}catch{return null}}function Bo(r){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=r.replace(/^\.\/+/,""),n=t.split("/").pop()||t,i=[t,n,t.replace(/\.json$/,""),n.replace(/\.json$/,"")];for(let a of i){let s=e[a];if(s){let o=Fo(s,a);if(o!==null)return o}}return null}async function It(r){if(Ri.has(r)&&!zi)return console.log(`[CONFIG] Using cached config for: "${r}"`),Ri.get(r);if(console.log(`[CONFIG] loadConfigFile called with: "${r}", MODE: ${F.toUpperCase()}, CACHE: ${zi?"DISABLED":"ENABLED"}`),F==="publish"){let n=Bo(r);return n?(console.log(`[CONFIG] \u2713 Loaded ${r} via INLINE_ASSETS`),n):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${r} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}F==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${r}"`);let e;F==="brand"?e=[`./${r.split("/").pop()||r}`,`./${r}`,`./${r.replace(/^configs\//,"")}`,`./${r.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${r}`,`./${r.replace(/^configs\//,"")}`,`./${r.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(n=>n.startsWith("./")?[n,`/${n.slice(2)}`]:n.startsWith("/")?[n]:[n,`/${n}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let n=zi?"no-store":"force-cache";for(let i of e)try{let a=await fetch(i,{cache:n});if(!a.ok)continue;let s=await a.json();return console.log(`[CONFIG] \u2713 Loaded ${r} via ${i}`,s),s}catch(a){console.warn(`[CONFIG] \u2717 Failed to load ${i} (mode: ${F}):`,a)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${r}; using defaults`),{}})();return Ri.set(r,t),t}async function mn(){console.log("[CONFIG] Loading component schemas...");let r=["components/identity.schema.json","components/transform.schema.json","components/render.schema.json","components/motion.schema.json","components/effects.schema.json","components/interaction.schema.json","components/gameplay.rules.schema.json","components/gameplay.tuning.schema.json","components/visibility.schema.json","components/audio.schema.json","components/physics.schema.json","components/ui.schema.json"],e=new Map;for(let t of r)try{let n=F==="publish"||F==="brand"?t.split("/").pop()||t:`configs/${t}`,i=await It(n);i.component&&(e.set(i.component,i),console.log(`[CONFIG] \u2713 Schema loaded: ${i.component} ${F==="publish"||F==="brand"?"(flattened)":"(nested)"}`))}catch(n){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,n)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function je(r){console.log(`[CONFIG] Loading object config: ${r}`);let e=F==="publish"||F==="brand"?`${r}.json`:`configs/objects/${r}.json`;return await It(e)}async function bn(r){let e=new Map;if(r.objects&&Array.isArray(r.objects)){for(let t of r.objects)if(t.enabled&&t.object_config)try{let n=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(n)||(n=`json.${n}`);let i=await je(n);(!i||Object.keys(i).length===0)&&n!==t.instance_id&&(i=await je(t.instance_id)),!i||Object.keys(i).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),i=await je(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...i,instance_id:t.instance_id,object_config:t.object_config})}catch(n){console.warn(`Failed to load object ${t.object_config}:`,n)}}return e}async function yn(){console.log("[CONFIG] Loading engine configs...");let r=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(r.map(n=>{let i=`engine.${n}.json`,a=F==="publish"||F==="brand"?i:`configs/engine/${i}`;return It(a)})),t=Object.fromEntries(r.map((n,i)=>[n,e[i]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(r.map(n=>{var s;let i=(s=t[n])!=null?s:{},a=Object.keys(i);return[n,a.length>0?a:"empty"]}))),t}async function $i(){return await It(F==="publish"||F==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function vn(r="scene.main"){console.log(`[CONFIG] Loading scene config: ${r}`);let e=F==="publish"||F==="brand"?`${r}.json`:`configs/scenes/${r}.json`;return await It(e)}function it(r,e){let t=[];if(!r.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let n=e.get("identity");if(n)for(let i of n.required||[])r.identity[i]||t.push(`Missing required identity field: ${i}`);for(let[i,a]of Object.entries(r)){if(i==="identity")continue;let s=e.get(i);if(s&&a&&typeof a=="object"){let o=a;for(let l of s.required||[])o[l]===void 0&&t.push(`Missing required field in ${i}: ${l}`);if(s.constraints&&typeof s.constraints=="object")for(let[l,c]of Object.entries(s.constraints)){let p=o[l];if(p!==void 0&&c&&typeof c=="object"){let d=c;typeof p=="number"&&(d.min!==void 0&&p<d.min&&t.push(`${i}.${l} value ${p} is below minimum ${d.min}`),d.max!==void 0&&p>d.max&&t.push(`${i}.${l} value ${p} is above maximum ${d.max}`))}}}}return{valid:t.length===0,errors:t}}function Ue(r,e){let t={...r},n=["identity","transform","render"];for(let[i,a]of e.entries())a.defaults&&Object.keys(a.defaults).length>0&&(n.includes(i)||t[i])&&(t[i]||(t[i]={}),t[i]={...a.defaults,...t[i]});return t}function ie(r,e,t,n){return typeof r!="number"||!Number.isFinite(r)?e:Math.min(Math.max(r,t),n)}function Dr(r,e){if(Array.isArray(r))return{x:ie(r[0],e.x,-2e3,2e3),y:ie(r[1],e.y,-2e3,2e3)};if(!r||typeof r!="object")return e;let{x:t,y:n}=r;return{x:ie(t,e.x,-2e3,2e3),y:ie(n,e.y,-2e3,2e3)}}function Uo(r,e){if(Array.isArray(r))return{x:ie(r[0],e.x,0,1),y:ie(r[1],e.y,0,1)};if(!r||typeof r!="object")return e;let{x:t,y:n}=r;return{x:ie(t,e.x,0,1),y:ie(n,e.y,0,1)}}function Go(r){if(Array.isArray(r))return{x:ie(r[0],.5,-10,10),y:ie(r[1],.5,-10,10)};if(r&&typeof r=="object"){let{x:e,y:t}=r;return{x:ie(e,.5,-10,10),y:ie(t,.5,-10,10)}}return typeof r=="string"?r:null}async function xe(r="scene.main",e){var l,c,p,d,u,g,m,h,f,b,y,v,w,E;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await mn(),n=X();n.length>0&&console.log(`[CONFIG] Applying ${n.length} active overrides`);let i=await vn(r);console.log(`[CONFIG] Scene config loaded: ${((l=i.objects)==null?void 0:l.length)||0} objects`);let a=await yn();console.log("[CONFIG] Loading object configs...");let s=await bn(i);console.log(`[CONFIG] Loaded ${s.size} object configs:`,Array.from(s.keys()));for(let[j,z]of s.entries()){let S=Ue(z,t),_=it(S,t);_.valid||console.warn(`Object ${j} validation errors:`,_.errors),(c=S.transform)!=null&&c.position&&(S.transform.position=Dr(S.transform.position,{x:0,y:0})),(p=S.transform)!=null&&p.offset&&(S.transform.offset=Dr(S.transform.offset,{x:0,y:0})),((d=S.transform)==null?void 0:d.anchor)!==void 0&&(S.transform.anchor=Go(S.transform.anchor)),((u=S.transform)==null?void 0:u.position_ratio)!==void 0&&S.transform.position_ratio!==null&&(S.transform.position_ratio=Uo(S.transform.position_ratio,{x:.5,y:.5})),s.set(j,S)}if(e){if(e.objects)for(let[j,z]of e.objects.entries())s.set(j,z);e.engine&&(a.runtime={...a.runtime,...e.engine.runtime},a.assets={...a.assets,...e.engine.assets},a.splash={...(g=a.splash)!=null?g:{},...(m=e.engine.splash)!=null?m:{}})}let o={objects:s,engine:a,scene:i,schemas:t,theme:{background_color:"#ffffff",text_color:"#000000",square_color:"#cccccc",cta_background:"#007bff",cta_text:"#ffffff"},gameplay:{}};return typeof window!="undefined"&&(window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=Ue(o,t))),n.length>0&&Tt()&&ke(n,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(s.keys()),engine:{runtime:Object.keys((h=a.runtime)!=null?h:{}),assets:Object.keys((f=a.assets)!=null?f:{}),splash:Object.keys((b=a.splash)!=null?b:{}),loading:Object.keys((y=a.loading)!=null?y:{}),start:Object.keys((v=a.start)!=null?v:{}),tutorial:Object.keys((w=a.tutorial)!=null?w:{}),endgame:Object.keys((E=a.endgame)!=null?E:{})},scene:i.scene_id||"unknown"}),o}function Di(r){var t,n,i,a,s,o,l,c,p,d,u,g,m,h,f,b,y,v,w,E,j,z,S,_,R,T,C,M,k,A,x,I,L;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[P,O]of r.objects.entries()){let H=((t=O.identity)==null?void 0:t.id)||P;H.includes("character")&&(e.gameplay.character_pos=((n=O.transform)==null?void 0:n.position)||{x:0,y:0},e.gameplay.character_scale=((i=O.transform)==null?void 0:i.scale)||1,e.gameplay.character_anim_speed=((s=(a=O.gameplay)==null?void 0:a.tuning)==null?void 0:s.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(o=O.gameplay)==null?void 0:o.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((p=(c=O.gameplay)==null?void 0:c.tuning)==null?void 0:p.relief_speed)||.22),(H.includes("gun")||H.includes("flame"))&&(e.gameplay.gun=O.gun||{},e.gameplay.gunmuzzle=((d=O.effects)==null?void 0:d.gunmuzzle)||{},e.gameplay.muzzle_levels=((u=O.effects)==null?void 0:u.muzzle_levels)||{},e.gameplay.flame=((g=O.effects)==null?void 0:g.flame)||{}),H.includes("diamond")&&(e.gameplay.diamond=O),H.includes("ice")&&(e.gameplay.melt=O.melt||{},e.gameplay.melt_anchor=((m=O.transform)==null?void 0:m.melt_anchor)||{x:0,y:0},e.gameplay.melt_pos=((h=O.transform)==null?void 0:h.position)||{x:0,y:0},e.gameplay.hybrid_melting=((f=O.effects)==null?void 0:f.hybrid_melting)||{},e.gameplay.physics_chunks=((b=O.effects)==null?void 0:b.physics_chunks)||{},e.gameplay.melting_particles=((y=O.effects)==null?void 0:y.melting_particles)||{},e.gameplay.hard_ice=O.hard_ice||{}),H.includes("water")&&(e.gameplay.water_drops=O),H.includes("crack")&&(e.gameplay.crack=O),H.includes("hand")&&(e.gameplay.hand=((v=O.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((w=O.transform)==null?void 0:w.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((E=O.transform)==null?void 0:E.scale)||1.5),H.includes("hazard")&&(e.gameplay.hazard=((j=O.gameplay)==null?void 0:j.tuning)||{},e.gameplay.danger_pos=((z=O.transform)==null?void 0:z.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((_=(S=O.gameplay)==null?void 0:S.tuning)==null?void 0:_.danger_pulse)||{},e.gameplay.hazard_height=((T=(R=O.gameplay)==null?void 0:R.tuning)==null?void 0:T.hazard_height)||140)}return e.gameplay.timeline=((C=r.engine.runtime)==null?void 0:C.timeline)||{},e.gameplay.drag_surface=((M=r.engine.runtime)==null?void 0:M.drag_surface)||{},e.gameplay.background=((k=r.engine.runtime)==null?void 0:k.background)||{},e.gameplay.ui_styles=((A=r.engine.runtime)==null?void 0:A.ui_styles)||{},e.gameplay.label_pulse=((x=r.engine.runtime)==null?void 0:x.label_pulse)||{},e.ui=((I=r.engine.runtime)==null?void 0:I.ui)||{},e.theme=((L=r.engine.runtime)==null?void 0:L.theme)||{},e.assets=r.engine.assets||{},e}var $r,F,Ri,zi,Hi=he(()=>{"use strict";J();$r=null,F="dev";if(typeof window!="undefined"){let r=window.__BUILD_SETTINGS__;if(r!=null&&r.buildMode)$r=r,F=r.buildMode,console.log("[CONFIG] Loaded inline build settings:",r,"buildMode:",F);else try{let e=new XMLHttpRequest;if(e.open("GET","./build-settings.json",!1),e.send(),e.status===200&&e.responseText){let t=JSON.parse(e.responseText);$r=t,F=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",F)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",F)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",F);Ri=new Map,zi=F==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Ni(r,e){let t=[];function n(i,a,s=""){if(i!==a){if(typeof i!=typeof a){t.push(`${s}: type changed`);return}if(typeof i=="object"&&i!==null&&a!==null){let o=new Set([...Object.keys(i),...Object.keys(a)]);for(let l of o){let c=s?`${s}.${l}`:l;l in i?l in a?n(i[l],a[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${s}: changed`)}}return n(r,e),t}function Fi(r,e,t,n){let i={...t};for(let[a,s]of n.entries())i[a]&&s.defaults&&(i[a]={...s.defaults,...i[a]});return i}var jt,Ge,Bi=he(()=>{"use strict";jt=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},Ge=class{constructor(e=1e3){this.pollingInterval=null;this.fileHashes=new Map;this.callbacks=new Map;this.intervalMs=e}watch(e,t){this.callbacks.set(e,t),this.pollingInterval===null&&(this.pollingInterval=window.setInterval(()=>{this.checkAllFiles()},this.intervalMs))}async checkAllFiles(){for(let[e,t]of this.callbacks.entries())try{let n=`${e}?t=${Date.now()}&r=${Math.random()}`,i=await fetch(n,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(i.ok){let a=await i.text(),s=this.hashString(a),o=this.fileHashes.get(e);if(o&&o!==s&&console.log(`[HOT-RELOAD] File changed: ${e}`),o&&o!==s){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,s)}else o||this.fileHashes.set(e,s)}}catch(n){console.warn(`Failed to check ${e}:`,n)}}determineEventType(e){var t,n;return e.includes("/components/")?{type:"component",path:e,componentName:(t=e.split("/").pop())==null?void 0:t.replace(".schema.json","")}:e.includes("/engine/")?{type:"engine",path:e}:e.includes("/scenes/")?{type:"scene",path:e}:e.includes("/objects/")?{type:"object",path:e,objectId:(n=e.split("/").pop())==null?void 0:n.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);t=(t<<5)-t+i,t=t&t}return t.toString()}unwatch(e){this.callbacks.delete(e),this.fileHashes.delete(e)}stop(){this.pollingInterval!==null&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.callbacks.clear(),this.fileHashes.clear()}}});function Gi(r){if(typeof window=="undefined")return;let e=typeof Ui!="undefined"&&!!Ui.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let i=null,a=!1,s=null;if(t){s=new Ge;let m=window.__configWatcher;m!=null&&m.stop&&m.stop(),window.__configWatcher=s}let o=new Set,l=m=>{var b,y;if(!s)return;let h=new Set;h.add("configs/engine/engine.runtime.json"),h.add("configs/engine/engine.assets.json"),h.add("configs/engine/engine.splash.json"),h.add("configs/scenes/scene.main.json");let f=(y=(b=m.scene)==null?void 0:b.objects)!=null?y:[];for(let v of f)v!=null&&v.object_config&&h.add(`configs/objects/${v.object_config}.json`);for(let v of o)h.has(v)||s.unwatch(v);for(let v of h)o.has(v)||s.watch(v,w=>g(w));o=h},c=new Set,p=!1,d=async m=>{let h=await je(m),f=Ue(h,r.activeConfig.schemas),b=it(f,r.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${m} validation errors:`,b.errors),await r.liveEditBridge.applyObjectConfig(m,f)};async function u(m){if(!a){a=!0;try{if(p||c.size===0){r.audioSystem.destroy();let h=await xe("scene.main");r.setActiveConfig(h),r.gameObjectManager.updateConfig(h),r.CustomAssets.updateConfig(h),await r.CustomAssets.ready();let f=r.createAudioSystem(h);r.setAudioSystem(f),window.__audioSystem=f,await f.start(),r.liveEditBridge.rebuildIndexes(),l(h),console.log(`[GAME] Hot-reload complete (${m})`)}else{let h=Array.from(c);c.clear();for(let f of h)await d(f);console.log(`[GAME] Hot-reload updated objects: ${h.join(", ")}`)}}catch(h){console.warn("[GAME] Hot-reload failed:",h)}finally{a=!1,p=!1,c.clear()}}}function g(m){m.type==="object"&&m.objectId?c.add(m.objectId):p=!0,i&&window.clearTimeout(i),i=window.setTimeout(()=>{u(m.type)},120)}e&&Ui.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(r.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var Ui,Hr=he(()=>{"use strict";Bi();Hi();Ui={}});var Nr={};vt(Nr,{ConfigWatcher:()=>Ge,DefaultReloadStrategy:()=>jt,applyDefaults:()=>Ue,diffConfigs:()=>Ni,loadAllObjectConfigs:()=>bn,loadComponentSchemas:()=>mn,loadEngineConfig:()=>yn,loadGamePromptConfig:()=>$i,loadObjectCentricConfig:()=>xe,loadObjectConfig:()=>je,loadSceneConfig:()=>vn,rehydrateObject:()=>Fi,setupHotReload:()=>Gi,toLegacyFormat:()=>Di,validateObjectConfig:()=>it});var wn=he(()=>{"use strict";Hi();Bi();Hr()});var As={};vt(As,{AssetEditorModal:()=>Sa});var Sa,Aa=he(()=>{"use strict";Sa=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,n,i){this.currentObjectId=e,this.currentPath=t,this.currentAsset=n,this.onApplyCallback=i,this.createModal(e,n),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let n=document.createElement("div");n.className="asset-editor-modal",n.innerHTML=`
|
|
2
2
|
<div class="asset-editor-card">
|
|
3
3
|
<div class="asset-editor-header">
|
|
4
4
|
<div>
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
<button class="debug-btn primary" data-modal-apply>Apply</button>
|
|
44
44
|
</div>
|
|
45
45
|
</div>
|
|
46
|
-
`,this.modal=n}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(s=>{s.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(s=>{s.addEventListener("click",o=>{let c=o.target.dataset.tab;c&&this.switchTab(c)})});let n=this.modal.querySelector("[data-ai-generate]");n==null||n.addEventListener("click",()=>{this.openAiEditor("generate")});let i=this.modal.querySelector("[data-ai-edit]");i==null||i.addEventListener("click",()=>{this.openAiEditor("edit")});let a=this.modal.querySelector("[data-modal-apply]");a==null||a.addEventListener("click",()=>{this.apply()}),this.modal.addEventListener("click",s=>{s.target===this.modal&&this.close()})}switchTab(e){if(!this.modal)return;this.modal.querySelectorAll("[data-tab]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab-panel")===e)})}openAiEditor(e){let t=window.__openAiEditor;if(typeof t!="function"){alert("AI Editor not available. Please check your setup.");return}let n="";e==="edit"&&this.currentAsset?n=`Edit this image: ${this.currentObjectId}`:n=`Create an image for: ${this.currentObjectId}`,t(this.currentObjectId||"unknown",n,this.currentAsset,{path:this.currentPath,onApply:i=>{this.onApplyCallback&&this.onApplyCallback(i),this.close()}})}apply(){this.onApplyCallback&&this.onApplyCallback("library/placeholder.png"),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.currentObjectId=null,this.currentPath=null,this.onApplyCallback=null}}});var Ll={};bt(Ll,{COLORS:()=>de,ConfigWatcher:()=>Fe,DebugPanel:()=>zt,DefaultReloadStrategy:()=>kt,Handler:()=>re,PlayableLoadingScreen:()=>ni,PreviewShell:()=>Qn,STROKE_WIDTH:()=>_s,THEME:()=>js,applyConfigOverride:()=>le,applyConfigOverrides:()=>Ce,applyConfigsToDisk:()=>un,applyDefaults:()=>Ne,baseLottie:()=>mi,bootstrap:()=>ml,clearConfigOverrides:()=>te,clearConfigOverridesForObject:()=>Pr,configOverrideManager:()=>_r,createPreviewShell:()=>Ta,deepClone:()=>V,default:()=>Oe,defaultPreset:()=>vn,deviceGroups:()=>Vi,devicePresets:()=>qi,diffConfigs:()=>Hi,exportConfigsAsJSON:()=>De,getConfigOverrides:()=>K,getConfigStateSummary:()=>Te,getOverrideMode:()=>At,getPresetById:()=>Be,getPresetsByCategory:()=>qo,loadAllObjectConfigs:()=>fn,loadComponentSchemas:()=>hn,loadEngineConfig:()=>mn,loadGamePromptConfig:()=>zi,loadObjectCentricConfig:()=>ye,loadObjectConfig:()=>Le,loadSceneConfig:()=>bn,redoLastConfigChange:()=>pn,rehydrateObject:()=>Ni,removeConfigOverride:()=>Ct,resetToApplied:()=>Tt,resetToOriginal:()=>gn,setBootstrapDependencies:()=>hl,setOverrideMode:()=>ji,setupHotReload:()=>Ui,setupLiveEditBridge:()=>ei,toLegacyFormat:()=>$i,trackObjectCreation:()=>jr,trackObjectDeletion:()=>Or,undoLastConfigChange:()=>dn,validateObjectConfig:()=>tt});module.exports=Qs(Ll);var Ee={};function Yt(r,e,t=!1){Ee[r]||(Ee[r]=[]),Ee[r].push({fn:e,once:t})}function ui(r,e){if(Ee[r]){if(!e){delete Ee[r];return}Ee[r]=Ee[r].filter(t=>t.fn!==e)}}function Kt(r,...e){let t=Ee[r];if(t)for(let n of[...t])n.fn(...e),n.once&&ui(r,n.fn)}function Z(r,e){Yt(r,e,!0)}var G=null,ie=[],Je=null;function Ga(r){G=r,ie=[],Je!==null&&(clearTimeout(Je),Je=null)}function qa(){var r,e,t;return{endpoint:(G==null?void 0:G.endpoint)||"",transport:(G==null?void 0:G.transport)||"beacon",batchSize:(r=G==null?void 0:G.batchSize)!=null?r:10,flushIntervalMs:(e=G==null?void 0:G.flushIntervalMs)!=null?e:300,maxQueue:(t=G==null?void 0:G.maxQueue)!=null?t:200,debug:!!(G!=null&&G.debug)}}async function Ba(r,e,t,n){let i=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(r,new Blob([i],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:i,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",e)}catch(a){n&&console.warn("[handler.telemetry] fetch failed",a)}}function gi(r,e){let t=qa();if(e&&t.endpoint){if(ie.push(r),ie.length>t.maxQueue&&(ie=ie.slice(ie.length-t.maxQueue)),ie.length>=t.batchSize){Ua();return}Je===null&&(Je=window.setTimeout(()=>{Je=null,Ua()},t.flushIntervalMs))}}async function Ua(){let r=qa();if(!r.endpoint||ie.length===0)return;let e=ie.splice(0,r.batchSize);await Ba(r.endpoint,{events:e},r.transport,r.debug),ie.length>0&&await Ba(r.endpoint,{events:ie.splice(0,r.batchSize)},r.transport,r.debug)}function Va(r){return Math.max(0,Math.min(1,r))}function eo(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.]+)\)/),n=t?Number(t[1]):1.8;return i=>1+(n+1)*Math.pow(i-1,3)+n*Math.pow(i-1,2)}return t=>1-(1-t)*(1-t)}function yt(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function to(r,e){let t=r==null?void 0:r[e];return typeof t=="number"?t:0}function Wa(r,e,t){try{r[e]=t}catch{}}function no(r){let e=r==null?void 0:r.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,n=typeof e.y=="number"?e.y:1;return{x:t,y:n}}function Ya(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 Ka(r,e){let t=no(r);if(!t)return{from:null,to:null};let n=null,i=null;return typeof e.scale=="number"?(n=e.scale,i=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(n=e.scale.x),typeof e.scale.y=="number"&&(i=e.scale.y)),typeof e.scaleX=="number"&&(n=e.scaleX),typeof e.scaleY=="number"&&(i=e.scaleY),n===null&&i===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:n!=null?n:t.x,y:i!=null?i:t.y}}}function Xa(){let r=new Set,e=new WeakMap,t=null,n=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),r.size>0&&n()})},i=p=>{var u;r.add(p);let d=(u=e.get(p.target))!=null?u:new Set;d.add(p),e.set(p.target,d),n()},a=p=>{r.delete(p);let d=e.get(p.target);d&&(d.delete(p),d.size===0&&e.delete(p.target))},s=p=>{p.killed||(p.killed=!0,a(p))},o=()=>{var d,u;let p=yt();for(let g of Array.from(r)){if(g.killed||g.paused)continue;let m=p-g.startMs-g.delayMs;if(m<0)continue;let h=g.durationMs>0?m/g.durationMs:1,f=Va(h),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(h),b-1):0;if(g.repeat>0&&h>=1){let C=h-y;f=Va(C)}let v=g.ease(f);g.yoyo&&y%2===1&&(v=1-v);for(let C of g.props)Wa(g.target,C.key,C.from+(C.to-C.from)*v);g.scaleFrom&&g.scaleTo&&Ya(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{(d=g.onUpdate)==null||d.call(g)}catch{}if(h>=b){s(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(p,d,u)=>{var C;let g=Math.max(0,(typeof d.duration=="number"?d.duration:.5)*1e3),m=Math.max(0,(typeof d.delay=="number"?d.delay:0)*1e3+((C=u==null?void 0:u.delayMsOverride)!=null?C:0)),h=eo(d.ease),f=typeof d.repeat=="number"?Math.max(0,d.repeat|0):0,b=d.yoyo===!0,y=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let k of Object.keys(d)){if(y.has(k))continue;let z=d[k];typeof z=="number"&&v.push({key:k,from:to(p,k),to:z})}let S=Ka(p,d);return{target:p,startMs:yt(),delayMs:m,durationMs:g,ease:h,props:v,scaleFrom:S.from,scaleTo:S.to,repeat:f,yoyo:b,onUpdate:typeof d.onUpdate=="function"?d.onUpdate:void 0,onComplete:typeof d.onComplete=="function"?d.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(p,d){let u=l(p,d);return i(u),{kill:()=>s(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=yt())},resume:()=>{var h;if(!u.paused)return;let g=(h=u.pauseAtMs)!=null?h:yt(),m=yt()-g;u.startMs+=m,u.paused=!1,u.pauseAtMs=null},isActive:()=>!u.killed&&!u.paused}},fromTo(p,d,u){return c.set(p,d),c.to(p,u)},set(p,d){if(!p||!d)return;for(let g of Object.keys(d)){let m=d[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof m=="number"&&Wa(p,g,m)}let u=Ka(p,d);u.to&&Ya(p,u.to)},killTweensOf(p){let d=e.get(p);if(d)for(let u of Array.from(d))s(u)},timeline(p={}){let d=[],u=0,g=!1,m=[],h=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},f=y=>{d.push(y);let v=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);u=Math.max(u,y.atMs+v)},b={to(y,v,S){return f({kind:"to",target:y,vars:v,atMs:h(S)}),b},fromTo(y,v,S,C){return f({kind:"fromTo",target:y,vars:S,from:v,atMs:h(C)}),b},play(){var y,v;if(g)return b;g=!0,m=[];for(let S of d)S.kind==="fromTo"&&c.set(S.target,(y=S.from)!=null?y:{}),m.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 m)y.pause();return b},kill(){for(let y of m)y.kill();m=[],g=!1}};return p.paused||b.play(),b}};return c}function Ja(){if(typeof window=="undefined")return;let r=window;if(!r.gsap)try{r.gsap=Xa()}catch{}}var Za={name:"handler-playable-sdk",version:"0.5.47",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 && 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/ && chmod +x dist/cli/*.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 && 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; 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 Q=0,ao=Q++,Qa=Q++,er=Q++,tr=Q++,nr=Q++,ir=Q++,ar=Q++,rr=Q++,sr=Q++,or=Q++,lr=Q++,cr=Q++,U=ao;function dr(){return U===Qa}function pr(){return U===er}function ur(){return U===tr}function gr(){return U===nr}function Ze(){return U===ir}function Qe(){return U===ar}function hr(){return U===rr}function fr(){return U===sr}function mr(){return U===or}function hi(){return U===lr}function fi(){return U===cr}function br(){let r=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(r==="mraid")try{mraid.getState(),U=Qa;return}catch{}else if(r==="dapi")try{dapi.isReady(),U=er;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(U=tr)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(U=nr)}catch{}else if(e==="mintegral")window.gameReady&&(U=ir);else if(e==="tapjoy")window.TJ_API&&(U=ar);else if(e==="tiktok")window.openAppStore&&(U=rr);else if(e==="smadex")try{window.smxTracking&&(U=sr)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(U=or)}catch{}else e==="vungle"?U=lr:(r==="nucleo"||e==="nucleo")&&(U=cr)}var Xt=Xe(require("lottie-web"),1),mi=Xt.default;typeof window!="undefined"&&(window.lottie=Xt.default,window.__baseLottie=Xt.default);var ro=require("pixi.js");var bi=require("pixi.js");var so=null;function yi(r){so=r}Jt();vi();var vt=require("pixi.js");Jt();var go=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",Si=go;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&&(Si=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${Si}`))}}catch{}function ho(r){var t,n,i,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:(n=r[1])!=null?n:.5};if(r&&typeof r=="object"&&"x"in r&&"y"in r)return{x:(i=r.x)!=null?i:.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 Ae=class{static async create(e,t,n){var l,c,p,d,u,g,m;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${Si}`);let i=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!i){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let h=new vt.Container;return this.applyTransform(h,t==null?void 0:t.transform,t),h}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: ${i.type}, path: ${i.path}`);let s=await ze.load(e,i,n,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(p=s==null?void 0:s.constructor)==null?void 0:p.name}`);let o;if(i.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",e),o=new vt.Sprite(s),console.log("[ObjectFactory] Created object:",o,"type:",(d=o==null?void 0:o.constructor)==null?void 0:d.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(i.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=s==null?void 0:s.constructor)==null?void 0:u.name,s),s&&(((g=s.constructor)==null?void 0:g.name)==="Container"||s instanceof vt.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let h=[i.path,`/assets/${i.path}`,`assets/${i.path}`,`../assets/${i.path}`],f=!1;for(let b of h)try{let y=await fetch(b);if(y.ok){o=await y.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(m=o==null?void 0:o.constructor)==null?void 0:m.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,n){var i,a,s,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(i=t.position.x)!=null?i: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=ho(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 wt=class{constructor(){this.config=null}init(e){this.config=e}get(e){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return this.config.objects.get(e)}getAllIds(){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return Array.from(this.config.objects.keys())}has(e){return this.config?this.config.objects.has(e):!1}};var bo=Xe(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=bo);et();var Zt=require("pixi.js");et();var Ti=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new wt}init(e,t){this.registry.init(e),this.app=t}updateConfig(e){this.registry.init(e),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let t=this.registry.getAllIds().filter(i=>!this.instanceCache.has(i));if(t.length===0)return;let n=async i=>{i.length&&(console.log("[Assets] Loading objects:",i),await Promise.all(i.map(async a=>{var o;let s=this.registry.get(a);if(!s){console.warn("[Assets] No config found for object:",a);return}try{let l=await Ae.create(a,s,this.app);this.instanceCache.set(a,l),console.log("[Assets] Loaded object:",a,(o=l==null?void 0:l.constructor)==null?void 0:o.name)}catch(l){console.error("[Assets] Failed to load object:",a,l)}})))};return this.readyPromise=(async()=>{await n(t);let i=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));i.length>0&&(console.warn("[Assets] Retrying missing assets:",i),await n(i)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(e){let t=this.registry.get(e);if(t){let n=await Ae.create(e,t,this.app);this.instanceCache.set(e,n)}}get(e){return this.instanceCache.get(e)}},yo=new Ti,vo=new Proxy(yo,{get(r,e){if(e in r&&typeof r[e]=="function")return r[e].bind(r);if(r.get(e))return r.get(e)}});et();var Sr=require("pixi.js"),fe={width:400,height:600,designWidth:400,scaleFactor:1},en={scale:1,position:1},ki=[];function xo(r,e,t,n,i,a,s){ki.push({element:r,originalScale:a,positionHelper:e,heightPercent:i}),e(r,t,n,i,a,s,!1)}function Eo(){ki.forEach(({element:r,originalScale:e,positionHelper:t,heightPercent:n})=>{let i=e*fe.scaleFactor;t(r,fe.width,fe.height,n,i,!0,!1)})}function Li(r,e){console.log(`[SCREEN] updateScreenState called: ${r}x${e}`),fe.width=r,fe.height=e,fe.scaleFactor=Math.min(r/fe.designWidth,1.15),en.scale=fe.scaleFactor,en.position=1,console.log(`[SCREEN] Global multipliers - scale: ${en.scale.toFixed(3)}`),Eo()}var Et={layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}};function So(r,e,t){let n=Et[r];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${r}.${e} = ${t}`))}function Ao(){return Et}var Co={center:{x:.5,y:.5},"center-center":{x:.5,y:.5},middle:{x:.5,y:.5},"middle-center":{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},"left-center":{x:0,y:.5},"right-center":{x:1,y:.5},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};function Qt(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function tn(r,e={x:.5,y:.5}){var t;if(Array.isArray(r))return{x:Qt(r[0],e.x),y:Qt(r[1],e.y)};if(r&&typeof r=="object"){let n=r;return{x:Qt(n.x,e.x),y:Qt(n.y,e.y)}}if(typeof r=="string"){let n=r.trim().toLowerCase();return(t=Co[n])!=null?t:e}return e}function Ar(r,e,t,n={}){var g,m,h,f,b,y;let i=tn(t),a=(g=n.inset)!=null?g:{},s=(m=n.padding)!=null?m:{x:0,y:0},o=((h=a.left)!=null?h:0)+s.x,l=((f=a.right)!=null?f:0)+s.x,c=((b=a.top)!=null?b:0)+s.y,p=((y=a.bottom)!=null?y:0)+s.y,d=Math.max(0,r-o-l),u=Math.max(0,e-c-p);return{x:o+d*i.x,y:c+u*i.y}}function Cr(r,e,t,n={}){var h,f,b,y,v,S;let i=(h=n.inset)!=null?h:{},a=(f=n.padding)!=null?f:{x:0,y:0},s=((b=i.left)!=null?b:0)+a.x,o=((y=i.right)!=null?y:0)+a.x,l=((v=i.top)!=null?v:0)+a.y,c=((S=i.bottom)!=null?S:0)+a.y,p=Math.max(0,r-s-o),d=Math.max(0,e-l-c),u=tn(t,{x:.5,y:.5}),g=Math.min(Math.max(u.x,0),1),m=Math.min(Math.max(u.y,0),1);return{x:s+p*g,y:l+d*m}}if(typeof window!="undefined"){let r=window.innerWidth,e=window.innerHeight,t=()=>{let n=window.innerWidth,i=window.innerHeight;(n!==r||i!==e)&&(r=n,e=i,Li(n,i))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),Li(window.innerWidth,window.innerHeight),window.updateDebugConfig=So,window.getDebugConfig=Ao,window.copyConfig=zo,window.applyConfig=xt,window.applyConfigForRatio=$o,window.positionAtBottom=Tr,window.positionAtTop=ko,window.positionAtCenter=Io,window.positionAtLeft=Mo,window.positionAtRight=Po,window.positionAtBottomLeft=_o,window.positionAtBottomRight=jo,window.positionAtTopLeft=Oo,window.positionAtTopRight=Ro,window.applyPositionContract=Lo,console.log("\u{1F3AE} Debug Config Functions Available:"),console.log("\u2022 updateDebugConfig(category, key, value)"),console.log("\u2022 getDebugConfig()"),console.log("\u2022 copyConfig(presetName)"),console.log("\u2022 applyConfig(config)"),console.log("\u2022 applyConfigForRatio(width, height)"),console.log("\u{1F4CD} Positioning Helpers Available (with scale):"),console.log("\u2022 positionAtBottom(element, w, h, percent, scale)"),console.log("\u2022 positionAtTop(element, w, h, percent, scale)"),console.log("\u2022 positionAtCenter(element, w, h, offsetX, offsetY, scale)"),console.log("\u2022 positionAtLeft/Right(element, w, h, percent, scale)"),console.log("\u2022 Corner positions: BottomLeft/Right, TopLeft/Right (all with scale)"),console.log("\u2022 applyPositionContract(element, w, h, contract)"),console.log("Example: positionAtCenter(mySprite, 400, 600, 0, -50, 1.2)")}function nn(r,e,t=0){return r*e+t}function an(r,e,t=0){return r*(1-e)+t}function rn(r,e,t=0){return r*e+t}function sn(r,e,t=0){return r*(1-e)+t}function ee(r,e=0){return r/2+e}function To(r,e){return r*e}function Lo(r,e,t,n){var s,o,l,c,p,d,u,g,m,h,f,b,y,v,S,C,k,z,w,x;let i=0,a=0;switch(n.type){case"top":i=ee(e,(o=(s=n.offset)==null?void 0:s.x)!=null?o:0),a=nn(t,n.percent,(c=(l=n.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":i=ee(e,(d=(p=n.offset)==null?void 0:p.x)!=null?d:0),a=an(t,n.percent,(g=(u=n.offset)==null?void 0:u.y)!=null?g:0);break;case"left":i=rn(e,n.percent,(h=(m=n.offset)==null?void 0:m.x)!=null?h:0),a=ee(t,(b=(f=n.offset)==null?void 0:f.y)!=null?b:0);break;case"right":i=sn(e,n.percent,(v=(y=n.offset)==null?void 0:y.x)!=null?v:0),a=ee(t,(C=(S=n.offset)==null?void 0:S.y)!=null?C:0);break;case"center":i=ee(e,(z=(k=n.offset)==null?void 0:k.x)!=null?z:0),a=ee(t,(x=(w=n.offset)==null?void 0:w.y)!=null?x:0);break}r.position?r.position.set(i,a):(r.x=i,r.y=a),n.scale!==void 0&&n.scale!==1&&r.scale&&(typeof r.scale.set=="function"?r.scale.set(n.scale,n.scale):(r.scale.x=n.scale,r.scale.y=n.scale))}function Tr(r,e,t,n=.2,i=1,a=!0,s=!1){let o=To(t,n),l=an(t,n/2);me(r,ee(e),l);let c=a?i*fe.scaleFactor:i;be(r,c),s&&!ki.find(p=>p.element===r)&&xo(r,Tr,e,t,n,i,a)}function ko(r,e,t,n=.1,i=1){me(r,ee(e),nn(t,n)),be(r,i)}function Io(r,e,t,n=0,i=0,a=1){me(r,ee(e,n),ee(t,i)),be(r,a)}function Mo(r,e,t,n=.1,i=1){me(r,rn(e,n),ee(t)),be(r,i)}function Po(r,e,t,n=.1,i=1){me(r,sn(e,n),ee(t)),be(r,i)}function _o(r,e,t,n=.05,i=.05,a=1){me(r,rn(e,i),an(t,n)),be(r,a)}function jo(r,e,t,n=.05,i=.05,a=1){me(r,sn(e,i),an(t,n)),be(r,a)}function Oo(r,e,t,n=.05,i=.05,a=1){me(r,rn(e,i),nn(t,n)),be(r,a)}function Ro(r,e,t,n=.05,i=.05,a=1){me(r,sn(e,i),nn(t,n)),be(r,a)}function me(r,e,t){r&&r.position?typeof r.position.set=="function"?r.position.set(e,t):(r.position.x=e,r.position.y=t):r&&(r.x=e,r.y=t)}function be(r,e){e!==1&&r&&r.scale&&(typeof r.scale.set=="function"?r.scale.set(e,e):r.scale.x!==void 0&&r.scale.y!==void 0&&(r.scale.x=e,r.scale.y=e))}var $e={default:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}},wide:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.9,screen_scale_y:1.1},engine:{scale:1,background_scale:1.1,background_offset_y:0,background_alpha:.95,label_pulse_speed:3,label_pulse_intensity:.03}},square:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.85,screen_scale_y:.85},engine:{scale:1,background_scale:1,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}},tall:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1.1,screen_scale_y:.9},engine:{scale:1,background_scale:.95,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}}};function zo(r){return r&&$e[r]?JSON.parse(JSON.stringify($e[r])):JSON.parse(JSON.stringify(Et))}function xt(r){Object.keys(r).forEach(e=>{let t=e;Et[t]&&r[t]&&Object.assign(Et[t],r[t])}),console.log("Config applied:",r)}function $o(r,e){let t=r/e;t>1.6?(xt($e.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(xt($e.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(xt($e.square),console.log("Applied SQUARE config for ratio:",t)):(xt($e.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let r=window;r.configPresets=$e,r.resolveAnchorVec2=r.resolveAnchorVec2||tn,r.resolveScreenAnchorPoint=r.resolveScreenAnchorPoint||Ar,r.resolveScreenRatioPoint=r.resolveScreenRatioPoint||Cr}yn();function q(r,e){let t=(i,a)=>a===0?i:t(a,i%a),n=t(r,e);return`${r/n}:${e/n}`}var td=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:q(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:q(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:q(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:q(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:q(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:q(360,780)}],nd=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:q(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:q(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:q(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:q(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:q(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:q(412,915)}],id=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:q(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:q(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:q(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:q(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:q(800,1280)}],Gi=[{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:q(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:q(768,1024),mraidScale:.7}];var qi=[...Gi],Vi=[{category:"playable",label:"Playable Ad",devices:Gi}],vn=Gi[0];function Be(r){return qi.find(e=>e.id===r)||vn}function qo(r){return qi.filter(e=>e.category===r)}X();var ke=class{async updateProperty(e,t,n,i={}){var l,c,p;console.log("[PropertyUpdateManager] Updating:",e,t,n);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}le({objectId:e,path:t,value:n},{persist:!0});let o=window.applyEditableObjectConfig;if(typeof o=="function"){let d=window.__editableConfig,u=(p=(c=(l=d==null?void 0:d.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?p:s;await o(e,u),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(e),i.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let n=t.split("."),i=e;for(let a of n)if(i&&typeof i=="object"&&a in i)i=i[a];else return;return i}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function Wi(r){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let n=(a=t.target.files)==null?void 0:a[0];if(!n)return;let i=new FileReader;i.onload=async()=>{let s=i.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 d=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(!(d!=null&&d.success)){alert(`Upload failed: ${(d==null?void 0:d.error)||"Unknown error"}`);return}let u=window.addAssetToRegistry;typeof u=="function"&&u(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(d.path)}catch(p){console.error("[QuickActionsBar] Upload error:",p),alert("Upload failed. Check console.")}},i.readAsDataURL(n)},e.click()}var wn=class{constructor(){this.updateManager=new ke}async handleAction(e,t,n){console.log("[QuickActionsBar] Action:",e,t,n);let i=window.getEditableObjectConfig;if(typeof i!="function")return;let a=i(t);if(!a)return;let s=this.updateManager.getNestedProperty(a,n);if(e==="ai-convert"||e==="upload"||e==="library"){let o=n==="ui.text"||n==="render.asset.path",l=n==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(e){case"library":this.openLibrary(t,n,s);break;case"ai-edit":this.openAIEditor(t,n,s);break;case"upload":this.openUpload(t,n);break;case"reset":await this.resetToDefault(t,n);break;case"ai-convert":this.handleAiConvert(t,n,s);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var n,i;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=((i=(n=t.transform)==null?void 0:n.scale)!=null?i: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 n=window.getEditableAssets;if(typeof n!="function")return;let i=n();if(!i||!i.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!i.slots.some(p=>p.objectId===a||p.slotId===a)){let p=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),i.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:p,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:p,assetType:"image"}),i.categories&&!i.categories.includes(p)&&i.categories.push(p),i.libraryAssets&&!i.libraryAssets[p]&&(i.libraryAssets[p]=[]);let d=window.reRenderAssetLibrary;typeof d=="function"&&d()}}openLibrary(e,t,n){var a;let i=window.__debugContext;if(i){if(i.activeTab!=="library"){i.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(i.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),i.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,n){let i=window.__openAiEditor;if(typeof i=="function"){let a=t.split(".").pop()||t;i(a,`Edit ${a} for ${e}`,n,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var s;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e),a=((s=i==null?void 0:i.identity)==null?void 0:s.category)||(t.split(".")[0]==="render"?"environment":"ui");Wi({objectId:e,category:a,onApply:async o=>{var p,d;await this.updateManager.updateProperty(e,t,o);let l=window.__debugContext;(d=(p=l==null?void 0:l.options)==null?void 0:p.onPropertyChange)==null||d.call(p,e,t,o);let c=window.__highlightLibrarySlot;typeof c=="function"&&setTimeout(()=>{c(e,a)},500),window.dispatchEvent(new CustomEvent("inspector:refresh"))}})}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let n=await this.getDefaultValue(e,t);n!==void 0?(await this.updateManager.updateProperty(e,t,n),console.log("[QuickActionsBar] Reset to default value:",n)):alert("No default value found for this property.")}catch(n){console.error("[QuickActionsBar] Failed to reset to default:",n),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let n=t.split(".");if(n.length<2)return;let i=n[0],a=n.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(i):typeof s.schemas=="object"&&(o=s.schemas[i]),!(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,n){let i=window.__openAiEditor;if(typeof i=="function"){let s=`A single, high-quality, high-detail game UI icon/asset representing "${String(n||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),i(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 Vo=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],Wo=["environment","ui","character","system","backgrounds"],Yo=["bg","world","ui"],Nr={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}}},xn=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=`
|
|
46
|
+
`,this.modal=n}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(s=>{s.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(s=>{s.addEventListener("click",o=>{let c=o.target.dataset.tab;c&&this.switchTab(c)})});let n=this.modal.querySelector("[data-ai-generate]");n==null||n.addEventListener("click",()=>{this.openAiEditor("generate")});let i=this.modal.querySelector("[data-ai-edit]");i==null||i.addEventListener("click",()=>{this.openAiEditor("edit")});let a=this.modal.querySelector("[data-modal-apply]");a==null||a.addEventListener("click",()=>{this.apply()}),this.modal.addEventListener("click",s=>{s.target===this.modal&&this.close()})}switchTab(e){if(!this.modal)return;this.modal.querySelectorAll("[data-tab]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab-panel")===e)})}openAiEditor(e){let t=window.__openAiEditor;if(typeof t!="function"){alert("AI Editor not available. Please check your setup.");return}let n="";e==="edit"&&this.currentAsset?n=`Edit this image: ${this.currentObjectId}`:n=`Create an image for: ${this.currentObjectId}`,t(this.currentObjectId||"unknown",n,this.currentAsset,{path:this.currentPath,onApply:i=>{this.onApplyCallback&&this.onApplyCallback(i),this.close()}})}apply(){this.onApplyCallback&&this.onApplyCallback("library/placeholder.png"),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.currentObjectId=null,this.currentPath=null,this.onApplyCallback=null}}});var Ll={};vt(Ll,{COLORS:()=>pe,ConfigWatcher:()=>Ge,DebugPanel:()=>Ht,DefaultReloadStrategy:()=>jt,Handler:()=>se,PlayableLoadingScreen:()=>ai,PreviewShell:()=>ti,STROKE_WIDTH:()=>_s,THEME:()=>Ps,applyConfigOverride:()=>ce,applyConfigOverrides:()=>ke,applyConfigsToDisk:()=>hn,applyDefaults:()=>Ue,baseLottie:()=>bi,bootstrap:()=>ml,clearConfigOverrides:()=>ne,clearConfigOverridesForObject:()=>_r,configOverrideManager:()=>Pr,createPreviewShell:()=>La,deepClone:()=>W,default:()=>$e,defaultPreset:()=>xn,deviceGroups:()=>Wi,devicePresets:()=>Vi,diffConfigs:()=>Ni,exportConfigsAsJSON:()=>Fe,getConfigOverrides:()=>X,getConfigStateSummary:()=>Ie,getOverrideMode:()=>Tt,getPresetById:()=>qe,getPresetsByCategory:()=>qo,loadAllObjectConfigs:()=>bn,loadComponentSchemas:()=>mn,loadEngineConfig:()=>yn,loadGamePromptConfig:()=>$i,loadObjectCentricConfig:()=>xe,loadObjectConfig:()=>je,loadSceneConfig:()=>vn,redoLastConfigChange:()=>gn,rehydrateObject:()=>Fi,removeConfigOverride:()=>Lt,resetToApplied:()=>kt,resetToOriginal:()=>fn,setBootstrapDependencies:()=>hl,setOverrideMode:()=>Oi,setupHotReload:()=>Gi,setupLiveEditBridge:()=>ni,toLegacyFormat:()=>Di,trackObjectCreation:()=>Or,trackObjectDeletion:()=>Rr,undoLastConfigChange:()=>un,validateObjectConfig:()=>it});module.exports=Qs(Ll);var Ce={};function Xt(r,e,t=!1){Ce[r]||(Ce[r]=[]),Ce[r].push({fn:e,once:t})}function gi(r,e){if(Ce[r]){if(!e){delete Ce[r];return}Ce[r]=Ce[r].filter(t=>t.fn!==e)}}function Jt(r,...e){let t=Ce[r];if(t)for(let n of[...t])n.fn(...e),n.once&&gi(r,n.fn)}function Q(r,e){Xt(r,e,!0)}var q=null,ae=[],Qe=null;function qa(r){q=r,ae=[],Qe!==null&&(clearTimeout(Qe),Qe=null)}function Va(){var r,e,t;return{endpoint:(q==null?void 0:q.endpoint)||"",transport:(q==null?void 0:q.transport)||"beacon",batchSize:(r=q==null?void 0:q.batchSize)!=null?r:10,flushIntervalMs:(e=q==null?void 0:q.flushIntervalMs)!=null?e:300,maxQueue:(t=q==null?void 0:q.maxQueue)!=null?t:200,debug:!!(q!=null&&q.debug)}}async function Ua(r,e,t,n){let i=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(r,new Blob([i],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:i,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",e)}catch(a){n&&console.warn("[handler.telemetry] fetch failed",a)}}function hi(r,e){let t=Va();if(e&&t.endpoint){if(ae.push(r),ae.length>t.maxQueue&&(ae=ae.slice(ae.length-t.maxQueue)),ae.length>=t.batchSize){Ga();return}Qe===null&&(Qe=window.setTimeout(()=>{Qe=null,Ga()},t.flushIntervalMs))}}async function Ga(){let r=Va();if(!r.endpoint||ae.length===0)return;let e=ae.splice(0,r.batchSize);await Ua(r.endpoint,{events:e},r.transport,r.debug),ae.length>0&&await Ua(r.endpoint,{events:ae.splice(0,r.batchSize)},r.transport,r.debug)}function Wa(r){return Math.max(0,Math.min(1,r))}function eo(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.]+)\)/),n=t?Number(t[1]):1.8;return i=>1+(n+1)*Math.pow(i-1,3)+n*Math.pow(i-1,2)}return t=>1-(1-t)*(1-t)}function wt(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function to(r,e){let t=r==null?void 0:r[e];return typeof t=="number"?t:0}function Ya(r,e,t){try{r[e]=t}catch{}}function no(r){let e=r==null?void 0:r.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,n=typeof e.y=="number"?e.y:1;return{x:t,y:n}}function Ka(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 Xa(r,e){let t=no(r);if(!t)return{from:null,to:null};let n=null,i=null;return typeof e.scale=="number"?(n=e.scale,i=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(n=e.scale.x),typeof e.scale.y=="number"&&(i=e.scale.y)),typeof e.scaleX=="number"&&(n=e.scaleX),typeof e.scaleY=="number"&&(i=e.scaleY),n===null&&i===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:n!=null?n:t.x,y:i!=null?i:t.y}}}function Ja(){let r=new Set,e=new WeakMap,t=null,n=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),r.size>0&&n()})},i=p=>{var u;r.add(p);let d=(u=e.get(p.target))!=null?u:new Set;d.add(p),e.set(p.target,d),n()},a=p=>{r.delete(p);let d=e.get(p.target);d&&(d.delete(p),d.size===0&&e.delete(p.target))},s=p=>{p.killed||(p.killed=!0,a(p))},o=()=>{var d,u;let p=wt();for(let g of Array.from(r)){if(g.killed||g.paused)continue;let m=p-g.startMs-g.delayMs;if(m<0)continue;let h=g.durationMs>0?m/g.durationMs:1,f=Wa(h),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(h),b-1):0;if(g.repeat>0&&h>=1){let E=h-y;f=Wa(E)}let v=g.ease(f);g.yoyo&&y%2===1&&(v=1-v);for(let E of g.props)Ya(g.target,E.key,E.from+(E.to-E.from)*v);g.scaleFrom&&g.scaleTo&&Ka(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{(d=g.onUpdate)==null||d.call(g)}catch{}if(h>=b){s(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(p,d,u)=>{var E;let g=Math.max(0,(typeof d.duration=="number"?d.duration:.5)*1e3),m=Math.max(0,(typeof d.delay=="number"?d.delay:0)*1e3+((E=u==null?void 0:u.delayMsOverride)!=null?E:0)),h=eo(d.ease),f=typeof d.repeat=="number"?Math.max(0,d.repeat|0):0,b=d.yoyo===!0,y=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let j of Object.keys(d)){if(y.has(j))continue;let z=d[j];typeof z=="number"&&v.push({key:j,from:to(p,j),to:z})}let w=Xa(p,d);return{target:p,startMs:wt(),delayMs:m,durationMs:g,ease:h,props:v,scaleFrom:w.from,scaleTo:w.to,repeat:f,yoyo:b,onUpdate:typeof d.onUpdate=="function"?d.onUpdate:void 0,onComplete:typeof d.onComplete=="function"?d.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(p,d){let u=l(p,d);return i(u),{kill:()=>s(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=wt())},resume:()=>{var h;if(!u.paused)return;let g=(h=u.pauseAtMs)!=null?h:wt(),m=wt()-g;u.startMs+=m,u.paused=!1,u.pauseAtMs=null},isActive:()=>!u.killed&&!u.paused}},fromTo(p,d,u){return c.set(p,d),c.to(p,u)},set(p,d){if(!p||!d)return;for(let g of Object.keys(d)){let m=d[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof m=="number"&&Ya(p,g,m)}let u=Xa(p,d);u.to&&Ka(p,u.to)},killTweensOf(p){let d=e.get(p);if(d)for(let u of Array.from(d))s(u)},timeline(p={}){let d=[],u=0,g=!1,m=[],h=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},f=y=>{d.push(y);let v=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);u=Math.max(u,y.atMs+v)},b={to(y,v,w){return f({kind:"to",target:y,vars:v,atMs:h(w)}),b},fromTo(y,v,w,E){return f({kind:"fromTo",target:y,vars:w,from:v,atMs:h(E)}),b},play(){var y,v;if(g)return b;g=!0,m=[];for(let w of d)w.kind==="fromTo"&&c.set(w.target,(y=w.from)!=null?y:{}),m.push(c.to(w.target,{...w.vars,delay:w.atMs/1e3+((v=w.vars.delay)!=null?v:0)}));return b},pause(){for(let y of m)y.pause();return b},kill(){for(let y of m)y.kill();m=[],g=!1}};return p.paused||b.play(),b}};return c}function Za(){if(typeof window=="undefined")return;let r=window;if(!r.gsap)try{r.gsap=Ja()}catch{}}var Qa={name:"handler-playable-sdk",version:"0.5.54",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 && 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/ && chmod +x dist/cli/*.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 && 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; 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 ee=0,ao=ee++,er=ee++,tr=ee++,nr=ee++,ir=ee++,ar=ee++,rr=ee++,sr=ee++,or=ee++,lr=ee++,cr=ee++,dr=ee++,U=ao;function pr(){return U===er}function ur(){return U===tr}function gr(){return U===nr}function hr(){return U===ir}function et(){return U===ar}function tt(){return U===rr}function fr(){return U===sr}function mr(){return U===or}function br(){return U===lr}function fi(){return U===cr}function mi(){return U===dr}function yr(){let r=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(r==="mraid")try{mraid.getState(),U=er;return}catch{}else if(r==="dapi")try{dapi.isReady(),U=tr;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(U=nr)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(U=ir)}catch{}else if(e==="mintegral")window.gameReady&&(U=ar);else if(e==="tapjoy")window.TJ_API&&(U=rr);else if(e==="tiktok")window.openAppStore&&(U=sr);else if(e==="smadex")try{window.smxTracking&&(U=or)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(U=lr)}catch{}else e==="vungle"?U=cr:(r==="nucleo"||e==="nucleo")&&(U=dr)}var Zt=Ze(require("lottie-web"),1),bi=Zt.default;typeof window!="undefined"&&(window.lottie=Zt.default,window.__baseLottie=Zt.default);var ro=require("pixi.js");var yi=require("pixi.js");var so=null;function vi(r){so=r}Qt();wi();var xt=require("pixi.js");Qt();var go=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",Ai=go;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&&(Ai=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${Ai}`))}}catch{}function ho(r){var t,n,i,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:(n=r[1])!=null?n:.5};if(r&&typeof r=="object"&&"x"in r&&"y"in r)return{x:(i=r.x)!=null?i:.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 Le=class{static async create(e,t,n){var l,c,p,d,u,g,m;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${Ai}`);let i=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!i){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let h=new xt.Container;return this.applyTransform(h,t==null?void 0:t.transform,t),h}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: ${i.type}, path: ${i.path}`);let s=await He.load(e,i,n,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(p=s==null?void 0:s.constructor)==null?void 0:p.name}`);let o;if(i.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",e),o=new xt.Sprite(s),console.log("[ObjectFactory] Created object:",o,"type:",(d=o==null?void 0:o.constructor)==null?void 0:d.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(i.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=s==null?void 0:s.constructor)==null?void 0:u.name,s),s&&(((g=s.constructor)==null?void 0:g.name)==="Container"||s instanceof xt.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let h=[i.path,`/assets/${i.path}`,`assets/${i.path}`,`../assets/${i.path}`],f=!1;for(let b of h)try{let y=await fetch(b);if(y.ok){o=await y.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(m=o==null?void 0:o.constructor)==null?void 0:m.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,n){var i,a,s,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(i=t.position.x)!=null?i: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=ho(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 Et=class{constructor(){this.config=null}init(e){this.config=e}get(e){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return this.config.objects.get(e)}getAllIds(){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return Array.from(this.config.objects.keys())}has(e){return this.config?this.config.objects.has(e):!1}};var bo=Ze(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=bo);nt();var en=require("pixi.js");nt();var Li=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new Et}init(e,t){this.registry.init(e),this.app=t}updateConfig(e){this.registry.init(e),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let t=this.registry.getAllIds().filter(i=>!this.instanceCache.has(i));if(t.length===0)return;let n=async i=>{i.length&&(console.log("[Assets] Loading objects:",i),await Promise.all(i.map(async a=>{var o;let s=this.registry.get(a);if(!s){console.warn("[Assets] No config found for object:",a);return}try{let l=await Le.create(a,s,this.app);this.instanceCache.set(a,l),console.log("[Assets] Loaded object:",a,(o=l==null?void 0:l.constructor)==null?void 0:o.name)}catch(l){console.error("[Assets] Failed to load object:",a,l)}})))};return this.readyPromise=(async()=>{await n(t);let i=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));i.length>0&&(console.warn("[Assets] Retrying missing assets:",i),await n(i)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(e){let t=this.registry.get(e);if(t){let n=await Le.create(e,t,this.app);this.instanceCache.set(e,n)}}get(e){return this.instanceCache.get(e)}},yo=new Li,vo=new Proxy(yo,{get(r,e){if(e in r&&typeof r[e]=="function")return r[e].bind(r);if(r.get(e))return r.get(e)}});nt();var Ar=require("pixi.js"),ye={width:400,height:600,designWidth:400,scaleFactor:1},nn={scale:1,position:1},Ii=[];function xo(r,e,t,n,i,a,s){Ii.push({element:r,originalScale:a,positionHelper:e,heightPercent:i}),e(r,t,n,i,a,s,!1)}function Eo(){Ii.forEach(({element:r,originalScale:e,positionHelper:t,heightPercent:n})=>{let i=e*ye.scaleFactor;t(r,ye.width,ye.height,n,i,!0,!1)})}function ki(r,e){console.log(`[SCREEN] updateScreenState called: ${r}x${e}`),ye.width=r,ye.height=e,ye.scaleFactor=Math.min(r/ye.designWidth,1.15),nn.scale=ye.scaleFactor,nn.position=1,console.log(`[SCREEN] Global multipliers - scale: ${nn.scale.toFixed(3)}`),Eo()}var At={layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}};function So(r,e,t){let n=At[r];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${r}.${e} = ${t}`))}function Ao(){return At}var Co={center:{x:.5,y:.5},"center-center":{x:.5,y:.5},middle:{x:.5,y:.5},"middle-center":{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},"left-center":{x:0,y:.5},"right-center":{x:1,y:.5},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};function tn(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function an(r,e={x:.5,y:.5}){var t;if(Array.isArray(r))return{x:tn(r[0],e.x),y:tn(r[1],e.y)};if(r&&typeof r=="object"){let n=r;return{x:tn(n.x,e.x),y:tn(n.y,e.y)}}if(typeof r=="string"){let n=r.trim().toLowerCase();return(t=Co[n])!=null?t:e}return e}function Cr(r,e,t,n={}){var g,m,h,f,b,y;let i=an(t),a=(g=n.inset)!=null?g:{},s=(m=n.padding)!=null?m:{x:0,y:0},o=((h=a.left)!=null?h:0)+s.x,l=((f=a.right)!=null?f:0)+s.x,c=((b=a.top)!=null?b:0)+s.y,p=((y=a.bottom)!=null?y:0)+s.y,d=Math.max(0,r-o-l),u=Math.max(0,e-c-p);return{x:o+d*i.x,y:c+u*i.y}}function Tr(r,e,t,n={}){var h,f,b,y,v,w;let i=(h=n.inset)!=null?h:{},a=(f=n.padding)!=null?f:{x:0,y:0},s=((b=i.left)!=null?b:0)+a.x,o=((y=i.right)!=null?y:0)+a.x,l=((v=i.top)!=null?v:0)+a.y,c=((w=i.bottom)!=null?w:0)+a.y,p=Math.max(0,r-s-o),d=Math.max(0,e-l-c),u=an(t,{x:.5,y:.5}),g=Math.min(Math.max(u.x,0),1),m=Math.min(Math.max(u.y,0),1);return{x:s+p*g,y:l+d*m}}if(typeof window!="undefined"){let r=window.innerWidth,e=window.innerHeight,t=()=>{let n=window.innerWidth,i=window.innerHeight;(n!==r||i!==e)&&(r=n,e=i,ki(n,i))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),ki(window.innerWidth,window.innerHeight),window.updateDebugConfig=So,window.getDebugConfig=Ao,window.copyConfig=zo,window.applyConfig=St,window.applyConfigForRatio=$o,window.positionAtBottom=Lr,window.positionAtTop=ko,window.positionAtCenter=Io,window.positionAtLeft=jo,window.positionAtRight=Mo,window.positionAtBottomLeft=_o,window.positionAtBottomRight=Po,window.positionAtTopLeft=Oo,window.positionAtTopRight=Ro,window.applyPositionContract=Lo,console.log("\u{1F3AE} Debug Config Functions Available:"),console.log("\u2022 updateDebugConfig(category, key, value)"),console.log("\u2022 getDebugConfig()"),console.log("\u2022 copyConfig(presetName)"),console.log("\u2022 applyConfig(config)"),console.log("\u2022 applyConfigForRatio(width, height)"),console.log("\u{1F4CD} Positioning Helpers Available (with scale):"),console.log("\u2022 positionAtBottom(element, w, h, percent, scale)"),console.log("\u2022 positionAtTop(element, w, h, percent, scale)"),console.log("\u2022 positionAtCenter(element, w, h, offsetX, offsetY, scale)"),console.log("\u2022 positionAtLeft/Right(element, w, h, percent, scale)"),console.log("\u2022 Corner positions: BottomLeft/Right, TopLeft/Right (all with scale)"),console.log("\u2022 applyPositionContract(element, w, h, contract)"),console.log("Example: positionAtCenter(mySprite, 400, 600, 0, -50, 1.2)")}function rn(r,e,t=0){return r*e+t}function sn(r,e,t=0){return r*(1-e)+t}function on(r,e,t=0){return r*e+t}function ln(r,e,t=0){return r*(1-e)+t}function te(r,e=0){return r/2+e}function To(r,e){return r*e}function Lo(r,e,t,n){var s,o,l,c,p,d,u,g,m,h,f,b,y,v,w,E,j,z,S,_;let i=0,a=0;switch(n.type){case"top":i=te(e,(o=(s=n.offset)==null?void 0:s.x)!=null?o:0),a=rn(t,n.percent,(c=(l=n.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":i=te(e,(d=(p=n.offset)==null?void 0:p.x)!=null?d:0),a=sn(t,n.percent,(g=(u=n.offset)==null?void 0:u.y)!=null?g:0);break;case"left":i=on(e,n.percent,(h=(m=n.offset)==null?void 0:m.x)!=null?h:0),a=te(t,(b=(f=n.offset)==null?void 0:f.y)!=null?b:0);break;case"right":i=ln(e,n.percent,(v=(y=n.offset)==null?void 0:y.x)!=null?v:0),a=te(t,(E=(w=n.offset)==null?void 0:w.y)!=null?E:0);break;case"center":i=te(e,(z=(j=n.offset)==null?void 0:j.x)!=null?z:0),a=te(t,(_=(S=n.offset)==null?void 0:S.y)!=null?_:0);break}r.position?r.position.set(i,a):(r.x=i,r.y=a),n.scale!==void 0&&n.scale!==1&&r.scale&&(typeof r.scale.set=="function"?r.scale.set(n.scale,n.scale):(r.scale.x=n.scale,r.scale.y=n.scale))}function Lr(r,e,t,n=.2,i=1,a=!0,s=!1){let o=To(t,n),l=sn(t,n/2);ve(r,te(e),l);let c=a?i*ye.scaleFactor:i;we(r,c),s&&!Ii.find(p=>p.element===r)&&xo(r,Lr,e,t,n,i,a)}function ko(r,e,t,n=.1,i=1){ve(r,te(e),rn(t,n)),we(r,i)}function Io(r,e,t,n=0,i=0,a=1){ve(r,te(e,n),te(t,i)),we(r,a)}function jo(r,e,t,n=.1,i=1){ve(r,on(e,n),te(t)),we(r,i)}function Mo(r,e,t,n=.1,i=1){ve(r,ln(e,n),te(t)),we(r,i)}function _o(r,e,t,n=.05,i=.05,a=1){ve(r,on(e,i),sn(t,n)),we(r,a)}function Po(r,e,t,n=.05,i=.05,a=1){ve(r,ln(e,i),sn(t,n)),we(r,a)}function Oo(r,e,t,n=.05,i=.05,a=1){ve(r,on(e,i),rn(t,n)),we(r,a)}function Ro(r,e,t,n=.05,i=.05,a=1){ve(r,ln(e,i),rn(t,n)),we(r,a)}function ve(r,e,t){r&&r.position?typeof r.position.set=="function"?r.position.set(e,t):(r.position.x=e,r.position.y=t):r&&(r.x=e,r.y=t)}function we(r,e){e!==1&&r&&r.scale&&(typeof r.scale.set=="function"?r.scale.set(e,e):r.scale.x!==void 0&&r.scale.y!==void 0&&(r.scale.x=e,r.scale.y=e))}var Ne={default:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}},wide:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.9,screen_scale_y:1.1},engine:{scale:1,background_scale:1.1,background_offset_y:0,background_alpha:.95,label_pulse_speed:3,label_pulse_intensity:.03}},square:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.85,screen_scale_y:.85},engine:{scale:1,background_scale:1,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}},tall:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1.1,screen_scale_y:.9},engine:{scale:1,background_scale:.95,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}}};function zo(r){return r&&Ne[r]?JSON.parse(JSON.stringify(Ne[r])):JSON.parse(JSON.stringify(At))}function St(r){Object.keys(r).forEach(e=>{let t=e;At[t]&&r[t]&&Object.assign(At[t],r[t])}),console.log("Config applied:",r)}function $o(r,e){let t=r/e;t>1.6?(St(Ne.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(St(Ne.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(St(Ne.square),console.log("Applied SQUARE config for ratio:",t)):(St(Ne.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let r=window;r.configPresets=Ne,r.resolveAnchorVec2=r.resolveAnchorVec2||an,r.resolveScreenAnchorPoint=r.resolveScreenAnchorPoint||Cr,r.resolveScreenRatioPoint=r.resolveScreenRatioPoint||Tr}wn();function V(r,e){let t=(i,a)=>a===0?i:t(a,i%a),n=t(r,e);return`${r/n}:${e/n}`}var td=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:V(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:V(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:V(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:V(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:V(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:V(360,780)}],nd=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:V(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:V(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:V(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:V(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:V(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:V(412,915)}],id=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:V(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:V(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:V(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:V(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:V(800,1280)}],qi=[{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:V(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:V(768,1024),mraidScale:.7}];var Vi=[...qi],Wi=[{category:"playable",label:"Playable Ad",devices:qi}],xn=qi[0];function qe(r){return Vi.find(e=>e.id===r)||xn}function qo(r){return Vi.filter(e=>e.category===r)}J();var Me=class{async updateProperty(e,t,n,i={}){var l,c,p;console.log("[PropertyUpdateManager] Updating:",e,t,n);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}ce({objectId:e,path:t,value:n},{persist:!0});let o=window.applyEditableObjectConfig;if(typeof o=="function"){let d=window.__editableConfig,u=(p=(c=(l=d==null?void 0:d.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?p:s;await o(e,u),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(e),i.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let n=t.split("."),i=e;for(let a of n)if(i&&typeof i=="object"&&a in i)i=i[a];else return;return i}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function Yi(r){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let n=(a=t.target.files)==null?void 0:a[0];if(!n)return;let i=new FileReader;i.onload=async()=>{let s=i.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 d=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(!(d!=null&&d.success)){alert(`Upload failed: ${(d==null?void 0:d.error)||"Unknown error"}`);return}let u=window.addAssetToRegistry;typeof u=="function"&&u(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(d.path)}catch(p){console.error("[QuickActionsBar] Upload error:",p),alert("Upload failed. Check console.")}},i.readAsDataURL(n)},e.click()}var En=class{constructor(){this.updateManager=new Me}async handleAction(e,t,n){console.log("[QuickActionsBar] Action:",e,t,n);let i=window.getEditableObjectConfig;if(typeof i!="function")return;let a=i(t);if(!a)return;let s=this.updateManager.getNestedProperty(a,n);if(e==="ai-convert"||e==="upload"||e==="library"){let o=n==="ui.text"||n==="render.asset.path",l=n==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(e){case"library":this.openLibrary(t,n,s);break;case"ai-edit":this.openAIEditor(t,n,s);break;case"upload":this.openUpload(t,n);break;case"reset":await this.resetToDefault(t,n);break;case"ai-convert":this.handleAiConvert(t,n,s);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var n,i;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=((i=(n=t.transform)==null?void 0:n.scale)!=null?i: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 n=window.getEditableAssets;if(typeof n!="function")return;let i=n();if(!i||!i.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!i.slots.some(p=>p.objectId===a||p.slotId===a)){let p=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),i.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:p,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:p,assetType:"image"}),i.categories&&!i.categories.includes(p)&&i.categories.push(p),i.libraryAssets&&!i.libraryAssets[p]&&(i.libraryAssets[p]=[]);let d=window.reRenderAssetLibrary;typeof d=="function"&&d()}}openLibrary(e,t,n){var a;let i=window.__debugContext;if(i){if(i.activeTab!=="library"){i.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(i.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),i.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,n){let i=window.__openAiEditor;if(typeof i=="function"){let a=t.split(".").pop()||t;i(a,`Edit ${a} for ${e}`,n,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var s;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e),a=((s=i==null?void 0:i.identity)==null?void 0:s.category)||(t.split(".")[0]==="render"?"environment":"ui");Yi({objectId:e,category:a,onApply:async o=>{var p,d;await this.updateManager.updateProperty(e,t,o);let l=window.__debugContext;(d=(p=l==null?void 0:l.options)==null?void 0:p.onPropertyChange)==null||d.call(p,e,t,o);let c=window.__highlightLibrarySlot;typeof c=="function"&&setTimeout(()=>{c(e,a)},500),window.dispatchEvent(new CustomEvent("inspector:refresh"))}})}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let n=await this.getDefaultValue(e,t);n!==void 0?(await this.updateManager.updateProperty(e,t,n),console.log("[QuickActionsBar] Reset to default value:",n)):alert("No default value found for this property.")}catch(n){console.error("[QuickActionsBar] Failed to reset to default:",n),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let n=t.split(".");if(n.length<2)return;let i=n[0],a=n.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(i):typeof s.schemas=="object"&&(o=s.schemas[i]),!(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,n){let i=window.__openAiEditor;if(typeof i=="function"){let s=`A single, high-quality, high-detail game UI icon/asset representing "${String(n||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),i(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 Vo=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],Wo=["environment","ui","character","system","backgrounds"],Yo=["bg","world","ui"],Fr={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}}},Sn=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=`
|
|
47
47
|
<div class="wizard-card">
|
|
48
48
|
<div class="wizard-header">
|
|
49
49
|
<div class="wizard-title">
|
|
@@ -266,7 +266,7 @@
|
|
|
266
266
|
<label class="wizard-label">Logic Component</label>
|
|
267
267
|
<select class="wizard-select" data-field="logicId">
|
|
268
268
|
<option value="">None</option>
|
|
269
|
-
${Object.keys(
|
|
269
|
+
${Object.keys(Fr).map(e=>`<option value="${e}">${e}</option>`).join("")}
|
|
270
270
|
</select>
|
|
271
271
|
</div>
|
|
272
272
|
<div class="wizard-field-group">
|
|
@@ -293,14 +293,14 @@
|
|
|
293
293
|
<div class="wizard-type-icon">${t}</div>
|
|
294
294
|
<div class="wizard-type-name">${n}</div>
|
|
295
295
|
</button>
|
|
296
|
-
`}attachEventListeners(){if(!this.modal||!this.state)return;this.modal.addEventListener("click",t=>{var a;let n=t.target,i=n.dataset.action||((a=n.closest("[data-action]"))==null?void 0:a.getAttribute("data-action"));if(i)switch(i){case"close":case"cancel":this.close();break;case"back":this.goToStep(this.state.step-1);break;case"next":this.state.step<6?this.goToStep(this.state.step+1):this.submit();break}}),this.modal.addEventListener("click",t=>{let i=t.target.closest("[data-asset-action]");if(!i)return;let a=i.dataset.assetAction;a&&(t.preventDefault(),this.handleAssetAction(a))}),this.modal.addEventListener("click",t=>{let i=t.target.closest("[data-object-type]");if(!i)return;let a=i.dataset.objectType;a&&this.setObjectType(a)}),Array.from(this.modal.querySelectorAll("[data-field]")).forEach(t=>{let n=()=>this.handleFieldChange(t);t.addEventListener("input",n),t.addEventListener("change",n)}),this.modal.addEventListener("click",t=>{t.target===this.modal&&this.close()})}handleAssetAction(e){if(this.state)switch(e){case"library":this.openLibraryPicker();break;case"upload":this.openUploadPicker();break;case"ai":this.openAiPicker();break;default:break}}openLibraryPicker(){if(!this.state)return;this.setAssetPickerHint("Select an asset from the Library tab."),window.__wizardAssetPicker={onPick:t=>{this.state.assetPath=t,this.setAssetPickerHint(""),this.updateStepUI()}};let e=window.__debugContext;if(e){e.activeTab="library";let t=window.__updateWorkbenchTabs;typeof t=="function"&&t()}}openUploadPicker(){if(!this.state)return;this.setAssetPickerHint("Upload an image to add it to the library.");let e=this.state.instanceId||"new_asset",t=this.state.category||"environment";
|
|
296
|
+
`}attachEventListeners(){if(!this.modal||!this.state)return;this.modal.addEventListener("click",t=>{var a;let n=t.target,i=n.dataset.action||((a=n.closest("[data-action]"))==null?void 0:a.getAttribute("data-action"));if(i)switch(i){case"close":case"cancel":this.close();break;case"back":this.goToStep(this.state.step-1);break;case"next":this.state.step<6?this.goToStep(this.state.step+1):this.submit();break}}),this.modal.addEventListener("click",t=>{let i=t.target.closest("[data-asset-action]");if(!i)return;let a=i.dataset.assetAction;a&&(t.preventDefault(),this.handleAssetAction(a))}),this.modal.addEventListener("click",t=>{let i=t.target.closest("[data-object-type]");if(!i)return;let a=i.dataset.objectType;a&&this.setObjectType(a)}),Array.from(this.modal.querySelectorAll("[data-field]")).forEach(t=>{let n=()=>this.handleFieldChange(t);t.addEventListener("input",n),t.addEventListener("change",n)}),this.modal.addEventListener("click",t=>{t.target===this.modal&&this.close()})}handleAssetAction(e){if(this.state)switch(e){case"library":this.openLibraryPicker();break;case"upload":this.openUploadPicker();break;case"ai":this.openAiPicker();break;default:break}}openLibraryPicker(){if(!this.state)return;this.setAssetPickerHint("Select an asset from the Library tab."),window.__wizardAssetPicker={onPick:t=>{this.state.assetPath=t,this.setAssetPickerHint(""),this.updateStepUI()}};let e=window.__debugContext;if(e){e.activeTab="library";let t=window.__updateWorkbenchTabs;typeof t=="function"&&t()}}openUploadPicker(){if(!this.state)return;this.setAssetPickerHint("Upload an image to add it to the library.");let e=this.state.instanceId||"new_asset",t=this.state.category||"environment";Yi({objectId:e,category:t,onApply:n=>{this.state.assetPath=n,this.setAssetPickerHint(""),this.updateStepUI()}})}openAiPicker(){if(!this.state)return;this.setAssetPickerHint('Generate and click "Save to Library" to use it here.'),window.__wizardAssetPicker={onPick:n=>{this.state.assetPath=n,this.setAssetPickerHint(""),this.updateStepUI()}};let e=window.__openAiEditor;if(typeof e!="function"){alert("AI Editor is not available.");return}let t=this.state.displayName||this.state.instanceId||"new asset";e(this.state.instanceId||"new_asset",`Create an image for ${t}`,"",{})}setAssetPickerHint(e){if(!this.modal)return;let t=this.modal.querySelector("[data-asset-picker-hint]");if(t){if(!e){t.style.display="none",t.textContent="";return}t.textContent=e,t.style.display="block"}}handleFieldChange(e){if(!this.state)return;let t=e.dataset.field;if(t){if(e instanceof HTMLInputElement&&e.type==="checkbox")this.state[t]=e.checked;else if(e instanceof HTMLInputElement&&e.type==="number"){let n=e.value===""?0:Number(e.value);this.state[t]=Number.isNaN(n)?0:n}else this.state[t]=e.value;t==="anchorPreset"&&this.applyAnchorPreset(this.state.anchorPreset),t==="logicId"&&this.applyLogicDefaults(this.state.logicId),this.updateStepUI()}}setObjectType(e){this.state&&(this.state.objectType=e,this.state.scale=e==="sprite"||e==="ui-image"?.2:1,(e==="ui-text"||e==="ui-image")&&(this.state.category="ui",this.state.layer="ui"),this.updateStepUI())}applyAnchorPreset(e){if(!this.state)return;let t={center:[.5,.5],"top-left":[0,0],"top-right":[1,0],"bottom-left":[0,1],"bottom-right":[1,1]};if(e!=="custom"&&t[e]){let[n,i]=t[e];this.state.anchorX=n,this.state.anchorY=i}}applyLogicDefaults(e){if(!this.state)return;if(!e){this.state.logicPropsRaw="";return}let t=Fr[e];t&&(this.state.logicPropsRaw=JSON.stringify(t,null,2))}goToStep(e){if(!this.state)return;let t=Math.max(1,Math.min(6,e));this.state.step=t,this.updateStepUI()}updateStepUI(){if(!this.modal||!this.state)return;Array.from(this.modal.querySelectorAll(".wizard-step")).forEach(t=>{let n=Number(t.dataset.step||"0");t.classList.toggle("active",n===this.state.step)}),this.updateProgressDots(),this.updateTypeSections(),this.syncFieldValues(),this.updatePreview(),this.updateActionButtons()}updateProgressDots(){if(!this.modal||!this.state)return;let e=this.modal.querySelector("[data-wizard-progress]");if(!e)return;let t=Array.from({length:6},(n,i)=>{let a=i+1;return`
|
|
297
297
|
<div class="wizard-step-indicator">
|
|
298
298
|
<span class="wizard-step-dot ${a===this.state.step?"active":a<this.state.step?"completed":""}"></span>
|
|
299
299
|
<span class="wizard-step-label">Step ${a}</span>
|
|
300
300
|
</div>
|
|
301
301
|
`});e.innerHTML=t.join("")}updateTypeSections(){if(!this.modal||!this.state)return;let e=this.state.objectType;Array.from(this.modal.querySelectorAll("[data-type-section]")).forEach(i=>{let a=i.dataset.typeSection,o=a==="sprite"&&(e==="sprite"||e==="ui-image")||a===e;i.style.display=o?"block":"none"});let n=this.modal.querySelector("[data-type-help]");if(n){let i=e==="ui-text"?"UI text uses the UI renderer with font settings.":e==="graphics"?"Graphics are simple shapes with width/height and fill.":e==="container"?"Containers are empty parents for grouping objects.":"Sprite/UI image uses image assets.";n.textContent=i}}syncFieldValues(){if(!this.modal||!this.state)return;let e=this.state;Array.from(this.modal.querySelectorAll("[data-field]")).forEach(i=>{let a=i.dataset.field;if(!a)return;let s=e[a];i instanceof HTMLInputElement&&i.type==="checkbox"?i.checked=!!s:typeof s!="undefined"&&(i.value=String(s))}),Array.from(this.modal.querySelectorAll("[data-object-type]")).forEach(i=>{i.classList.toggle("selected",i.dataset.objectType===this.state.objectType)})}updatePreview(){if(!this.modal||!this.state)return;let e=this.modal.querySelector("[data-preview-json]"),t=this.modal.querySelector("[data-validation-errors]");if(!e||!t)return;let n=this.buildPayload();e.textContent=JSON.stringify(n,null,2);let i=this.validate();i.length>0?(t.style.display="block",t.textContent=i.join(`
|
|
302
302
|
`)):(t.style.display="none",t.textContent="")}updateActionButtons(){if(!this.modal||!this.state)return;let e=this.modal.querySelector('[data-action="back"]'),t=this.modal.querySelector('[data-action="next"]');e&&(e.disabled=this.state.step===1),t&&(t.textContent=this.state.step===6?"Create":"Next",t.disabled=this.state.step===6&&this.validate().length>0)}validate(){if(!this.state)return[];let e=[],t=this.state.instanceId.trim();return t||e.push("Object ID is required."),t.startsWith("json.")&&e.push('Object ID must not start with "json." (instance id only).'),t&&!/^[a-zA-Z0-9._-]+$/.test(t)&&e.push("Object ID must use letters, numbers, dot, dash, or underscore."),t&&!this.isInstanceIdUnique(t)&&e.push(`Object ID "${t}" already exists.`),(this.state.objectType==="sprite"||this.state.objectType==="ui-image")&&!this.state.assetPath.trim()&&e.push("Asset path is required for image-based objects."),this.state.objectType==="ui-text"&&!this.state.text.trim()&&e.push("Text content is required for UI Text."),e}isInstanceIdUnique(e){let t=window.getEditableObjectList;if(typeof t=="function"){let a=t();if(Array.isArray(a))return!a.includes(e)}let n=window.__HANDLER_SCREEN_INDEX,i=n==null?void 0:n.instanceToScreen;return i&&typeof i=="object"?!Object.prototype.hasOwnProperty.call(i,e):!0}buildPayload(){if(!this.state)return{};let e=this.state.instanceId.trim(),t=`json.${e}`;return{screenId:this.state.screenId,instanceId:e,objectConfigId:t,layer:this.state.layer,config:this.buildObjectConfig(t)}}buildObjectConfig(e){if(!this.state)return{};let t={identity:{id:e,category:this.state.category},transform:{position:{x:this.state.positionX,y:this.state.positionY},offset:{x:this.state.offsetX,y:this.state.offsetY},scale:this.state.scale,rotation:this.state.rotation,anchor:{x:this.state.anchorX,y:this.state.anchorY},position_ratio:null,position_mode:this.state.positionMode},render:{alpha:this.state.alpha,visible:!0,tint:this.state.tint||null,z_index:this.state.zIndex},instance_id:this.state.instanceId.trim(),object_config:e};return(this.state.objectType==="sprite"||this.state.objectType==="ui-image")&&(t.render.asset={type:"image",path:this.normalizeAssetPath(this.state.assetPath.trim())}),this.state.objectType==="ui-text"&&(t.ui={kind:"text",renderMode:"text",text:this.state.text,font:this.state.font,fontSize:this.state.fontSize,letterSpacing:this.state.letterSpacing,align:this.state.align,color:this.state.tint||"#FFFFFF"},t.render.tint=null),this.state.objectType==="graphics"&&(t.effects={width:this.state.graphicsWidth,height:this.state.graphicsHeight,fill_color:this.state.graphicsFill,fill_alpha:this.state.graphicsAlpha}),this.state.interactionEnabled&&(t.interaction={enabled:!0,drag:{enabled:this.state.dragEnabled},hover:{enabled:this.state.hoverEnabled},click:{enabled:this.state.clickEnabled}}),this.state.logicId&&(t.logic={id:this.state.logicId,props:this.parseLogicProps(this.state.logicPropsRaw)}),t}parseLogicProps(e){if(!e||!e.trim())return{};try{return JSON.parse(e)}catch{return{}}}normalizeAssetPath(e){return!e||e.startsWith("raw/")?e:e.startsWith("/raw/")?e.replace(/^\/raw\//,"raw/"):e}async submit(){var n;if(!this.state)return;if(this.validate().length>0){this.updatePreview();return}let t=this.buildPayload();try{let i=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),a=await i.json().catch(()=>({}));if(!i.ok||(a==null?void 0:a.success)===!1){let s=((n=a==null?void 0:a.errors)==null?void 0:n.join(`
|
|
303
|
-
`))||(a==null?void 0:a.error)||"Failed to create object.";alert(s);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),this.close()}catch(i){alert(`Failed to create object: ${i instanceof Error?i.message:String(i)}`)}}async syncScreens(){try{await fetch("/api/sync-screens",{method:"POST"})}catch(e){console.warn("[AddObjectWizard] Failed to sync screens:",e)}}};var
|
|
303
|
+
`))||(a==null?void 0:a.error)||"Failed to create object.";alert(s);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),this.close()}catch(i){alert(`Failed to create object: ${i instanceof Error?i.message:String(i)}`)}}async syncScreens(){try{await fetch("/api/sync-screens",{method:"POST"})}catch(e){console.warn("[AddObjectWizard] Failed to sync screens:",e)}}};var An=class{constructor(e){this.menu=null;this.closeHandler=null;this.keyHandler=null;this.options=e}open(e){this.createMenu(),document.body.appendChild(this.menu),this.positionMenu(e),this.attachListeners()}close(){var e,t;this.menu&&this.menu.parentNode&&this.menu.parentNode.removeChild(this.menu),this.closeHandler&&(window.removeEventListener("click",this.closeHandler),this.closeHandler=null),this.keyHandler&&(window.removeEventListener("keydown",this.keyHandler),this.keyHandler=null),this.menu=null,(t=(e=this.options).onClose)==null||t.call(e)}createMenu(){let e=document.createElement("div");e.className="context-menu",e.setAttribute("data-context-menu","true"),e.innerHTML=`
|
|
304
304
|
<div class="context-menu-item" data-action="duplicate">Duplicate</div>
|
|
305
305
|
<div class="context-menu-item" data-action="rename">Rename</div>
|
|
306
306
|
<div class="context-menu-item" data-action="move">Move to Screen</div>
|
|
@@ -313,7 +313,16 @@
|
|
|
313
313
|
OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceId:this.options.objectId,newInstanceId:t,shareConfig:n,screenId:this.options.screenId})}),p=await c.json().catch(()=>({}));if(!c.ok||(p==null?void 0:p.success)===!1){let d=((i=p==null?void 0:p.errors)==null?void 0:i.join(`
|
|
314
314
|
`))||(p==null?void 0:p.error)||"Duplicate failed.";alert(d);return}(s=(a=this.options).onRefresh)==null||s.call(a),(l=(o=this.options).onSelect)==null||l.call(o,t),this.close()}catch(c){alert(`Duplicate failed: ${c instanceof Error?c.message:String(c)}`)}}async handleRename(){var t,n,i,a,s;let e=window.prompt("New instance ID",this.options.objectId);if(!(!e||e===this.options.objectId)){if(!this.isInstanceIdUnique(e)){alert(`Instance ID "${e}" already exists.`);return}try{let o=await fetch("/api/objects/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:this.options.objectId,screenId:this.options.screenId,newInstanceId:e})}),l=await o.json().catch(()=>({}));if(!o.ok||(l==null?void 0:l.success)===!1){let c=((t=l==null?void 0:l.errors)==null?void 0:t.join(`
|
|
315
315
|
`))||(l==null?void 0:l.error)||"Rename failed.";alert(c);return}(i=(n=this.options).onRefresh)==null||i.call(n),(s=(a=this.options).onSelect)==null||s.call(a,e),this.close()}catch(o){alert(`Rename failed: ${o instanceof Error?o.message:String(o)}`)}}}async handleMove(){var n,i,a;let e=window.prompt("Move to screen (loading/start/gameplay/tutorial/endgame)",this.options.screenId);if(!e)return;let t=e.trim();if(!["loading","start","gameplay","tutorial","endgame"].includes(t)){alert("Invalid screen. Use: loading, start, gameplay, tutorial, endgame.");return}if(t!==this.options.screenId){if(this.options.onMoveRequest){this.options.onMoveRequest(this.options.objectId,t),this.close();return}try{let s=await fetch("/api/objects/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:this.options.objectId,fromScreenId:this.options.screenId,toScreenId:t})}),o=await s.json().catch(()=>({}));if(!s.ok||(o==null?void 0:o.success)===!1){let l=((n=o==null?void 0:o.errors)==null?void 0:n.join(`
|
|
316
|
-
`))||(o==null?void 0:o.error)||"Move failed.";alert(l);return}(a=(i=this.options).onRefresh)==null||a.call(i),this.close()}catch(s){alert(`Move failed: ${s instanceof Error?s.message:String(s)}`)}}}handleCopyConfig(){var i,a;let e=window.getEditableObjectConfig,t=typeof e=="function"?e(this.options.objectId):null;if(!t){let s=window.__editableObjectConfigs;s&&typeof s.get=="function"&&(t=(i=s.get(this.options.objectId))!=null?i:null)}if(!t){alert("Config not found.");return}let n=JSON.stringify(t,null,2);(a=navigator.clipboard)==null||a.writeText(n).catch(()=>{alert("Failed to copy to clipboard.")}),this.close()}handleOpenInspector(){var t,n;let e=window.__previewSelectObject;typeof e=="function"&&e(this.options.objectId),(n=(t=this.options).onSelect)==null||n.call(t,this.options.objectId),this.close()}isInstanceIdUnique(e){let t=window.getEditableObjectList;if(typeof t=="function"){let a=t();if(Array.isArray(a))return!a.includes(e)}let n=window.__HANDLER_SCREEN_INDEX,i=n==null?void 0:n.instanceToScreen;return i&&typeof i=="object"?!Object.prototype.hasOwnProperty.call(i,e):!0}};var
|
|
316
|
+
`))||(o==null?void 0:o.error)||"Move failed.";alert(l);return}(a=(i=this.options).onRefresh)==null||a.call(i),this.close()}catch(s){alert(`Move failed: ${s instanceof Error?s.message:String(s)}`)}}}handleCopyConfig(){var i,a;let e=window.getEditableObjectConfig,t=typeof e=="function"?e(this.options.objectId):null;if(!t){let s=window.__editableObjectConfigs;s&&typeof s.get=="function"&&(t=(i=s.get(this.options.objectId))!=null?i:null)}if(!t){alert("Config not found.");return}let n=JSON.stringify(t,null,2);(a=navigator.clipboard)==null||a.writeText(n).catch(()=>{alert("Failed to copy to clipboard.")}),this.close()}handleOpenInspector(){var t,n;let e=window.__previewSelectObject;typeof e=="function"&&e(this.options.objectId),(n=(t=this.options).onSelect)==null||n.call(t,this.options.objectId),this.close()}isInstanceIdUnique(e){let t=window.getEditableObjectList;if(typeof t=="function"){let a=t();if(Array.isArray(a))return!a.includes(e)}let n=window.__HANDLER_SCREEN_INDEX,i=n==null?void 0:n.instanceToScreen;return i&&typeof i=="object"?!Object.prototype.hasOwnProperty.call(i,e):!0}};var Mt=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],Cn=class{constructor(e){this.menu=null;this.closeHandler=null;this.keyHandler=null;this.templates=[];this.isLoadingTemplates=!1;this.targetScreen="gameplay";this.options=e}getTargetScreenStorageKey(){return`handler_preview_add_menu_target_screen::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}async open(e){await this.loadTemplates(),this.loadTargetScreen(),this.createMenu(),document.body.appendChild(this.menu),this.positionMenu(e),this.attachListeners()}close(){var e,t;this.menu&&this.menu.parentNode&&this.menu.parentNode.removeChild(this.menu),this.closeHandler&&(window.removeEventListener("click",this.closeHandler),this.closeHandler=null),this.keyHandler&&(window.removeEventListener("keydown",this.keyHandler),this.keyHandler=null),this.menu=null,(t=(e=this.options).onClose)==null||t.call(e)}async loadTemplates(){if(!this.isLoadingTemplates){this.isLoadingTemplates=!0;try{let e=await fetch("/api/objects/templates");if(e.ok){let t=await e.json();this.templates=Array.isArray(t.templates)?t.templates:[]}}catch(e){console.warn("[AddObjectMenu] Failed to load templates:",e),this.templates=[]}finally{this.isLoadingTemplates=!1}}}createMenu(){let e=document.createElement("div");e.className="context-menu",e.setAttribute("data-context-menu","true");let t=this.templates.length>0?this.templates.map(n=>`<div class="context-menu-item" data-action="template" data-template-id="${this.escapeHtml(n.id)}">${this.escapeHtml(n.label)}</div>`).join(""):'<div class="context-menu-item disabled">No templates available</div>';e.innerHTML=`
|
|
317
|
+
<div class="context-menu-section-title">Target Screen</div>
|
|
318
|
+
<div class="context-menu-screen-grid">
|
|
319
|
+
${Mt.map(n=>`
|
|
320
|
+
<button class="context-menu-screen-chip ${n.value===this.targetScreen?"active":""}" type="button" data-action="set-screen" data-screen-id="${this.escapeHtml(n.value)}">
|
|
321
|
+
${this.escapeHtml(n.label)}
|
|
322
|
+
</button>
|
|
323
|
+
`).join("")}
|
|
324
|
+
</div>
|
|
325
|
+
<div class="context-menu-separator"></div>
|
|
317
326
|
<div class="context-menu-section-title">Objects</div>
|
|
318
327
|
<div class="context-menu-item" data-action="object" data-object-type="sprite">\u{1F5BC}\uFE0F Sprite</div>
|
|
319
328
|
<div class="context-menu-item" data-action="object" data-object-type="ui-image">\u{1F9E9} UI Image</div>
|
|
@@ -324,6 +333,12 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
324
333
|
<div class="context-menu-section-title">Templates</div>
|
|
325
334
|
${t}
|
|
326
335
|
<div class="context-menu-separator"></div>
|
|
336
|
+
<div class="context-menu-section-title">Screens</div>
|
|
337
|
+
<div class="context-menu-item" data-action="system" data-system-type="start-screen" data-screen-id="start">Start Screen (Hand)</div>
|
|
338
|
+
<div class="context-menu-item" data-action="system" data-system-type="start-screen-no-hand" data-screen-id="start">Start Screen (No Hand)</div>
|
|
339
|
+
<div class="context-menu-item" data-action="system" data-system-type="endgame-screen" data-screen-id="endgame">Endgame Screen (Hand)</div>
|
|
340
|
+
<div class="context-menu-item" data-action="system" data-system-type="endgame-screen-no-hand" data-screen-id="endgame">Endgame Screen (No Hand)</div>
|
|
341
|
+
<div class="context-menu-separator"></div>
|
|
327
342
|
<div class="context-menu-section-title">Systems</div>
|
|
328
343
|
<div class="context-menu-item" data-action="system" data-system-type="collectable-system">CollectableSystem</div>
|
|
329
344
|
<div class="context-menu-item" data-action="system" data-system-type="drag-snap-couples">DragSnapCouples</div>
|
|
@@ -332,7 +347,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
332
347
|
<div class="context-menu-item" data-action="system" data-system-type="scratch-card">ScratchCard</div>
|
|
333
348
|
<div class="context-menu-item" data-action="system" data-system-type="bullet-system">BulletSystem</div>
|
|
334
349
|
<div class="context-menu-item" data-action="system" data-system-type="spawner">Spawner</div>
|
|
335
|
-
`,this.menu=e}positionMenu(e){if(!this.menu)return;let{x:t,y:n}=e;this.menu.style.left=`${t}px`,this.menu.style.top=`${n}px`;let i=this.menu.getBoundingClientRect(),a=i.right-window.innerWidth,s=i.bottom-window.innerHeight;a>0&&(this.menu.style.left=`${t-a-8}px`),s>0&&(this.menu.style.top=`${n-s-8}px`)}attachListeners(){this.menu&&(this.menu.addEventListener("click",e=>{let t=e.target,n=t.
|
|
350
|
+
`,this.menu=e}positionMenu(e){if(!this.menu)return;let{x:t,y:n}=e;this.menu.style.left=`${t}px`,this.menu.style.top=`${n}px`;let i=this.menu.getBoundingClientRect(),a=i.right-window.innerWidth,s=i.bottom-window.innerHeight;a>0&&(this.menu.style.left=`${t-a-8}px`),s>0&&(this.menu.style.top=`${n-s-8}px`)}attachListeners(){this.menu&&(this.menu.addEventListener("click",e=>{let t=e.target,n=t.closest(".context-menu-item");if(!n){let p=t.closest('.context-menu-screen-chip[data-action="set-screen"]');if(!p)return;e.preventDefault(),e.stopPropagation();let d=p.dataset.screenId;if(!d||!Mt.some(u=>u.value===d))return;this.setTargetScreen(d);return}if(n.classList.contains("disabled"))return;let i=n.dataset.action;if(!i)return;e.stopPropagation();let a=n.dataset.objectType,s=n.dataset.systemType,o=n.dataset.templateId,l=n.dataset.screenId,c=l!=null?l:this.targetScreen;i==="object"&&a?this.handleCreateObject(a,c):i==="system"&&s?this.handleCreateSystem(s,c):i==="template"&&o&&this.handleCreateFromTemplate(o,c)}),this.closeHandler=e=>{let t=e.target;this.menu&&t&&this.menu.contains(t)||this.close()},window.addEventListener("click",this.closeHandler),this.keyHandler=e=>{e.key==="Escape"&&this.close()},window.addEventListener("keydown",this.keyHandler))}async promptScreen(e="Select Screen"){return new Promise(t=>{var c,p,d;let n=document.createElement("div");n.className="add-menu-modal-overlay",n.innerHTML=`
|
|
336
351
|
<div class="add-menu-modal">
|
|
337
352
|
<div class="add-menu-modal-header">
|
|
338
353
|
<div class="add-menu-modal-title">${this.escapeHtml(e)}</div>
|
|
@@ -341,7 +356,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
341
356
|
<div class="add-menu-modal-body">
|
|
342
357
|
<label class="add-menu-modal-label">Screen:</label>
|
|
343
358
|
<select class="add-menu-modal-select" id="screen-select" required>
|
|
344
|
-
${
|
|
359
|
+
${Mt.map((u,g)=>`<option value="${this.escapeHtml(u.value)}" ${g===2?"selected":""}>${this.escapeHtml(u.label)}</option>`).join("")}
|
|
345
360
|
</select>
|
|
346
361
|
</div>
|
|
347
362
|
<div class="add-menu-modal-footer">
|
|
@@ -349,7 +364,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
349
364
|
<button class="add-menu-modal-btn add-menu-modal-btn-primary" type="button" data-action="confirm">Confirm</button>
|
|
350
365
|
</div>
|
|
351
366
|
</div>
|
|
352
|
-
`;let i=()=>{n.parentNode&&n.parentNode.removeChild(n)},a=()=>{let g=n.querySelector("#screen-select").value.trim();if(!g||!
|
|
367
|
+
`;let i=()=>{n.parentNode&&n.parentNode.removeChild(n)},a=()=>{let g=n.querySelector("#screen-select").value.trim();if(!g||!Mt.some(m=>m.value===g)){alert("Please select a valid screen.");return}i(),t(g)},s=()=>{i(),t(null)};n.querySelector(".add-menu-modal").addEventListener("click",u=>{u.stopPropagation()}),(c=n.querySelector('[data-action="confirm"]'))==null||c.addEventListener("click",a),(p=n.querySelector('[data-action="cancel"]'))==null||p.addEventListener("click",s),(d=n.querySelector(".add-menu-modal-close"))==null||d.addEventListener("click",s),n.addEventListener("click",u=>{u.target===n&&s()});let l=n.querySelector("#screen-select");l.addEventListener("keydown",u=>{u.key==="Enter"?(u.preventDefault(),a()):u.key==="Escape"&&(u.preventDefault(),s())}),document.body.appendChild(n),l.focus()})}loadTargetScreen(){try{let t=(window.localStorage.getItem(this.getTargetScreenStorageKey())||"").trim();Mt.some(n=>n.value===t)?this.targetScreen=t:this.targetScreen="gameplay"}catch{this.targetScreen="gameplay"}}setTargetScreen(e){this.targetScreen=e;try{window.localStorage.setItem(this.getTargetScreenStorageKey(),e)}catch{}this.updateTargetScreenUI()}updateTargetScreenUI(){let e=this.menu;if(!e)return;Array.from(e.querySelectorAll(".context-menu-screen-chip[data-screen-id]")).forEach(n=>{let i=n.dataset.screenId;n.classList.toggle("active",i===this.targetScreen)})}async promptName(e="new_object",t="Enter Object Name"){return new Promise(n=>{var p,d,u;let i=document.createElement("div");i.className="add-menu-modal-overlay",i.innerHTML=`
|
|
353
368
|
<div class="add-menu-modal">
|
|
354
369
|
<div class="add-menu-modal-header">
|
|
355
370
|
<div class="add-menu-modal-title">${this.escapeHtml(t)}</div>
|
|
@@ -457,16 +472,18 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
457
472
|
<button class="add-menu-modal-btn add-menu-modal-btn-primary" type="button" data-action="confirm">Create</button>
|
|
458
473
|
</div>
|
|
459
474
|
</div>
|
|
460
|
-
`;let c=()=>{t.parentNode&&t.parentNode.removeChild(t)},p=b=>{let y=b.trim();if(!y)return null;try{return JSON.parse(y)}catch{return null}},d=()=>{var
|
|
461
|
-
`))||(
|
|
462
|
-
`))||(
|
|
463
|
-
`))||(x==null?void 0:x.error)||"Failed to create collectable system.";alert(
|
|
464
|
-
`))||(x==null?void 0:x.error)||"Failed to create drag-snap system.";alert(
|
|
465
|
-
`))||(x==null?void 0:x.error)||"Failed to create swerve collect system.";alert(
|
|
466
|
-
`))||(x==null?void 0:x.error)||"Failed to create tap destroy system.";alert(
|
|
467
|
-
`))||(x==null?void 0:x.error)||"Failed to create scratch card system.";alert(
|
|
468
|
-
`))||(
|
|
469
|
-
`))||(I==null?void 0:I.error)||"Failed to create
|
|
475
|
+
`;let c=()=>{t.parentNode&&t.parentNode.removeChild(t)},p=b=>{let y=b.trim();if(!y)return null;try{return JSON.parse(y)}catch{return null}},d=()=>{var G;let b=t.querySelector("#spawner-instance-id").value.trim(),y=t.querySelector("#spawner-template-id").value.trim(),v=t.querySelector("#spawner-spawn-templates").value,w=t.querySelector("#spawner-position-source").value.trim(),E=t.querySelector("#spawner-point-mode").value.trim(),j=t.querySelector("#spawner-spawn-points").value,z=t.querySelector("#spawner-random-bounds").value,S=t.querySelector("#spawner-pattern").value.trim(),_=Number(t.querySelector("#spawner-rate").value.trim()),R=Number(t.querySelector("#spawner-pool").value.trim()),T=Number(t.querySelector("#spawner-lifetime").value.trim()),C=t.querySelector("#spawner-return-on-invisible").checked,M=t.querySelector("#spawner-movement").value.trim(),k=t.querySelector("#spawner-velocity").value.trim(),A=t.querySelector("#spawner-velocity-range").value,x=p(v),I=Array.isArray(x)&&x.length?x:null,L=typeof((G=I==null?void 0:I[0])==null?void 0:G.templateId)=="string"?String(I[0].templateId):y;if(!b){alert("Instance ID is required.");return}if(!L){alert("Template ID is required (or provide Spawn Templates JSON).");return}let P={templateId:L,spawnPattern:S,spawnRate:Number.isFinite(_)?_:650,poolSize:Number.isFinite(R)?R:18,returnOnInvisible:C,positionSource:w,spawnPointMode:E,movementMode:M,lifetime:Number.isFinite(T)?T:5e3};I&&(P.spawnTemplates=I);let O=p(j);Array.isArray(O)&&(P.spawnPoints=O);let H=p(z);if(H&&typeof H=="object"&&(P.randomBounds=H),k.includes(",")){let[K,ze]=k.split(",").map(Ye=>Ye.trim()),ue=Number(K),ge=Number(ze);Number.isFinite(ue)&&Number.isFinite(ge)&&(P.velocity={x:ue,y:ge})}let N=p(A);N&&typeof N=="object"&&(P.velocityRange=N),c(),e({templateId:L,instanceId:b,spawnerProps:P})},u=()=>{c(),e(null)};t.querySelector(".add-menu-modal").addEventListener("click",b=>b.stopPropagation()),(m=t.querySelector('[data-action="confirm"]'))==null||m.addEventListener("click",d),(h=t.querySelector('[data-action="cancel"]'))==null||h.addEventListener("click",u),(f=t.querySelector(".add-menu-modal-close"))==null||f.addEventListener("click",u),t.addEventListener("click",b=>{b.target===t&&u()}),document.body.appendChild(t),t.querySelector("#spawner-instance-id").focus()})}sanitizeInstanceId(e){let t=e.trim();return!t||!/^[a-zA-Z0-9._-]+$/.test(t)?null:t}buildDefaultConfig(e,t,n){let i=`json.${t}`,a={identity:{id:i,category:e==="ui-image"||e==="ui-text"?"ui":"environment"},transform:{position:{x:0,y:0},offset:{x:0,y:0},scale:e==="sprite"||e==="ui-image"?.2:1,rotation:0,anchor:{x:.5,y:.5},position_ratio:null,position_mode:"static"},render:{alpha:1,visible:!0,tint:null,z_index:0},instance_id:t,object_config:i};return(e==="sprite"||e==="ui-image")&&(a.render.asset={type:"image",path:`raw/${n}.png`}),e==="ui-text"&&(a.ui={kind:"text",renderMode:"text",text:n,font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",color:"#FFFFFF"}),e==="graphics"&&(a.effects={width:200,height:200,fill_color:"#FFFFFF",fill_alpha:1}),a}async handleCreateObject(e,t){var l,c,p;this.close();let n=t!=null?t:await this.promptScreen();if(!n)return;let i=e==="ui-text"?"text_1":e==="graphics"?"graphics_1":"sprite_1",a=await this.promptName(i);if(!a)return;let s=a,o=this.buildDefaultConfig(e,s,a);try{let d=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,instanceId:s,objectConfigId:o.identity.id,layer:e==="ui-image"||e==="ui-text"?"ui":"world",config:o})}),u=await d.json().catch(()=>({}));if(!d.ok||(u==null?void 0:u.success)===!1){let m=((l=u==null?void 0:u.errors)==null?void 0:l.join(`
|
|
476
|
+
`))||(u==null?void 0:u.error)||"Failed to create object.";alert(m);return}let{trackObjectCreation:g}=await Promise.resolve().then(()=>(J(),Be));g(s,n,o),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed")),(p=(c=this.options).onRefresh)==null||p.call(c)}catch(d){alert(`Failed to create object: ${d instanceof Error?d.message:String(d)}`)}}async handleCreateFromTemplate(e,t){var s,o,l;this.close();let n=t!=null?t:await this.promptScreen();if(!n)return;let i=e.replace(/\.template$/,"").replace(/^json\./,"").replace(/[._]/g,"_")+"_1",a=await this.promptName(i);if(a)try{let c=await fetch("/api/objects/create-from-template",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({templateId:e,instanceId:a,screenId:n})}),p=await c.json().catch(()=>({}));if(!c.ok||(p==null?void 0:p.success)===!1){let d=((s=p==null?void 0:p.errors)==null?void 0:s.join(`
|
|
477
|
+
`))||(p==null?void 0:p.error)||"Failed to create from template.";alert(d);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(l=(o=this.options).onRefresh)==null||l.call(o)}catch(c){alert(`Failed to create from template: ${c instanceof Error?c.message:String(c)}`)}}async handleCreateSystem(e,t){var i,a,s,o,l,c,p,d,u,g,m,h,f,b,y,v,w,E,j,z,S,_,R,T,C,M,k;this.close();let n=t!=null?t:await this.promptScreen();if(n){if(e==="collectable-system")try{let A=await fetch("/api/systems/collectable-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await A.json().catch(()=>({}));if(!A.ok||(x==null?void 0:x.success)===!1){let I=((i=x==null?void 0:x.errors)==null?void 0:i.join(`
|
|
478
|
+
`))||(x==null?void 0:x.error)||"Failed to create collectable system.";alert(I);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(s=(a=this.options).onRefresh)==null||s.call(a)}catch(A){alert(`Failed to create collectable system: ${A instanceof Error?A.message:String(A)}`)}if(e==="drag-snap-couples")try{let A=await fetch("/api/systems/drag-snap-couples",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await A.json().catch(()=>({}));if(!A.ok||(x==null?void 0:x.success)===!1){let I=((o=x==null?void 0:x.errors)==null?void 0:o.join(`
|
|
479
|
+
`))||(x==null?void 0:x.error)||"Failed to create drag-snap system.";alert(I);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(c=(l=this.options).onRefresh)==null||c.call(l)}catch(A){alert(`Failed to create drag-snap system: ${A instanceof Error?A.message:String(A)}`)}if(e==="swerve-collect")try{let A=await fetch("/api/systems/swerve-collect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await A.json().catch(()=>({}));if(!A.ok||(x==null?void 0:x.success)===!1){let I=((p=x==null?void 0:x.errors)==null?void 0:p.join(`
|
|
480
|
+
`))||(x==null?void 0:x.error)||"Failed to create swerve collect system.";alert(I);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(u=(d=this.options).onRefresh)==null||u.call(d)}catch(A){alert(`Failed to create swerve collect system: ${A instanceof Error?A.message:String(A)}`)}if(e==="tap-destroy")try{let A=await fetch("/api/systems/tap-destroy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await A.json().catch(()=>({}));if(!A.ok||(x==null?void 0:x.success)===!1){let I=((g=x==null?void 0:x.errors)==null?void 0:g.join(`
|
|
481
|
+
`))||(x==null?void 0:x.error)||"Failed to create tap destroy system.";alert(I);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(h=(m=this.options).onRefresh)==null||h.call(m)}catch(A){alert(`Failed to create tap destroy system: ${A instanceof Error?A.message:String(A)}`)}if(e==="scratch-card")try{let A=await fetch("/api/systems/scratch-card",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await A.json().catch(()=>({}));if(!A.ok||(x==null?void 0:x.success)===!1){let I=((f=x==null?void 0:x.errors)==null?void 0:f.join(`
|
|
482
|
+
`))||(x==null?void 0:x.error)||"Failed to create scratch card system.";alert(I);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(y=(b=this.options).onRefresh)==null||y.call(b)}catch(A){alert(`Failed to create scratch card system: ${A instanceof Error?A.message:String(A)}`)}if(e==="start-screen"||e==="start-screen-no-hand")try{let x=await fetch("/api/systems/start-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,withHand:e==="start-screen"})}),I=await x.json().catch(()=>({}));if(!x.ok||(I==null?void 0:I.success)===!1){let L=((v=I==null?void 0:I.errors)==null?void 0:v.join(`
|
|
483
|
+
`))||(I==null?void 0:I.error)||"Failed to create start screen template.";alert(L);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(E=(w=this.options).onRefresh)==null||E.call(w)}catch(A){alert(`Failed to create start screen template: ${A instanceof Error?A.message:String(A)}`)}if(e==="endgame-screen"||e==="endgame-screen-no-hand")try{let x=await fetch("/api/systems/endgame-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,withHand:e==="endgame-screen"})}),I=await x.json().catch(()=>({}));if(!x.ok||(I==null?void 0:I.success)===!1){let L=((j=I==null?void 0:I.errors)==null?void 0:j.join(`
|
|
484
|
+
`))||(I==null?void 0:I.error)||"Failed to create endgame screen template.";alert(L);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(S=(z=this.options).onRefresh)==null||S.call(z)}catch(A){alert(`Failed to create endgame screen template: ${A instanceof Error?A.message:String(A)}`)}if(e==="bullet-system")try{let A=await fetch("/api/systems/bullet-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await A.json().catch(()=>({}));if(!A.ok||(x==null?void 0:x.success)===!1){let I=((_=x==null?void 0:x.errors)==null?void 0:_.join(`
|
|
485
|
+
`))||(x==null?void 0:x.error)||"Failed to create bullet system.";alert(I);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(T=(R=this.options).onRefresh)==null||T.call(R)}catch(A){alert(`Failed to create bullet system: ${A instanceof Error?A.message:String(A)}`)}if(e==="spawner"){let A=await this.promptSpawnerConfig();if(!A)return;let{templateId:x,instanceId:I,spawnerProps:L}=A;try{let P=await fetch("/api/systems/spawner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,templateId:x,instanceId:I,spawnerProps:L})}),O=await P.json().catch(()=>({}));if(!P.ok||(O==null?void 0:O.success)===!1){let H=((C=O==null?void 0:O.errors)==null?void 0:C.join(`
|
|
486
|
+
`))||(O==null?void 0:O.error)||"Failed to create spawner.";alert(H);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(k=(M=this.options).onRefresh)==null||k.call(M)}catch(P){alert(`Failed to create spawner: ${P instanceof Error?P.message:String(P)}`)}}}}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}async syncScreens(){try{await fetch("/api/sync-screens",{method:"POST"})}catch(e){console.warn("[AddObjectMenu] Failed to sync screens:",e)}}};var Tn=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.selectedIds=new Set;this.lastSelectedIndex=-1;this.objectEntries=[];this.options=null;this.retryTimer=null;this.screenFilter="all";this.showTemplates=!1;this.isContextMenuOpen=!1;this.systemBundles=new Map}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getShowTemplatesStorageKey(){return`handler_preview_show_templates::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}render(){return`
|
|
470
487
|
<div class="scene-panel scene-objects panel-accent-teal" data-panel="scene-objects">
|
|
471
488
|
<div class="scene-panel-header" data-panel-handle>
|
|
472
489
|
<div class="panel-title">
|
|
@@ -505,7 +522,39 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
505
522
|
</div>
|
|
506
523
|
<div class="panel-resize-handle-v" data-panel-resize-v></div>
|
|
507
524
|
</div>
|
|
508
|
-
`}initialize(e,t){var s,o,l,c,p,d,u,g;this.options=t,this.root=e.querySelector('[data-panel="scene-objects"]'),this.listContainer=(s=this.root)==null?void 0:s.querySelector("[data-object-list]"),this.searchInput=(o=this.root)==null?void 0:o.querySelector("#scene-object-search"),(l=this.searchInput)==null||l.addEventListener("input",()=>this.refreshObjects());let n=(
|
|
525
|
+
`}initialize(e,t){var s,o,l,c,p,d,u,g,m;this.options=t,this.root=e.querySelector('[data-panel="scene-objects"]'),this.listContainer=(s=this.root)==null?void 0:s.querySelector("[data-object-list]"),this.searchInput=(o=this.root)==null?void 0:o.querySelector("#scene-object-search"),(l=this.searchInput)==null||l.addEventListener("input",()=>this.refreshObjects()),(c=this.listContainer)==null||c.addEventListener("click",h=>{let f=h.target,b=f==null?void 0:f.closest("[data-system-bundle-action][data-system-bundle-id]");if(!b)return;h.preventDefault(),h.stopPropagation();let y=b.dataset.systemBundleAction,v=b.dataset.systemBundleId;if(!(!y||!v)){if(y==="toggle-visibility"){this.toggleSystemBundleVisibility(v);return}y==="delete"&&this.deleteSystemBundle(v)}});let n=(p=this.root)==null?void 0:p.querySelector("[data-add-object]");n==null||n.addEventListener("click",h=>{h.stopPropagation();let f=n.getBoundingClientRect();this.openAddObjectMenu({x:f.left,y:f.bottom+4})});let i=(d=this.root)==null?void 0:d.querySelector("#scene-screen-filter");if(i){try{let h=window.localStorage.getItem(this.getScreenFilterStorageKey());h&&(this.screenFilter=h)}catch{}i.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}i.addEventListener("change",()=>{let h=i.value||"all";this.screenFilter=h;try{window.localStorage.setItem(this.getScreenFilterStorageKey(),this.screenFilter)}catch{}try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}this.refreshObjects()})}let a=(u=this.root)==null?void 0:u.querySelector("#scene-templates-toggle");if(a){try{let h=window.localStorage.getItem(this.getShowTemplatesStorageKey());this.showTemplates=h==="true"}catch{}a.checked=this.showTemplates,a.addEventListener("change",()=>{this.showTemplates=!!a.checked;try{window.localStorage.setItem(this.getShowTemplatesStorageKey(),this.showTemplates?"true":"false")}catch{}this.refreshObjects()})}(g=this.root)==null||g.addEventListener("click",h=>{let f=h.target;if(!f||f.closest("[data-context-menu]"))return;if(f.tagName==="INPUT"&&f.classList.contains("scene-object-checkbox")){let j=f.dataset.objectId;if(!j)return;h.stopPropagation(),this.toggleBatchSelect(j);return}let b=f.closest(".scene-object-item[data-object-id]");if(!b)return;let y=b.dataset.objectId;if(!y)return;let v=h.ctrlKey||h.metaKey;h.shiftKey&&this.lastSelectedIndex>=0?this.selectRange(this.lastSelectedIndex,y):v?this.toggleBatchSelect(y):this.select(y)}),(m=this.listContainer)==null||m.addEventListener("contextmenu",h=>{var j;let f=h.target,b=f==null?void 0:f.closest("[data-object-id]");if(!b)return;let y=b.dataset.objectId;if(!y)return;h.preventDefault();let v=window.getEditableObjectConfig,w=typeof v=="function"?v(y):null;if(!w){let z=window.__editableObjectConfigs;z&&typeof z.get=="function"&&(w=(j=z.get(y))!=null?j:null)}let E=this.inferScreen(y,w);this.showContextMenu(y,E,h.clientX,h.clientY)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects()),window.addEventListener("handler:scene-objects-refresh",()=>this.refreshObjects())}setSelected(e){e?(this.selectedIds.clear(),this.selectedIds.add(e),this.selectedId=e):(this.selectedIds.clear(),this.selectedId=null),this.updateSelectionUI()}getSelectedIds(){return Array.from(this.selectedIds)}updateSelectionUI(){var a,s,o,l,c;if(!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(p=>{let d=p.dataset.objectId,u=d?this.selectedIds.has(d):!1,g=d===this.selectedId;p.classList.toggle("selected",u),p.classList.toggle("active",g);let m=p.closest(".scene-object-item-wrapper"),h=m==null?void 0:m.querySelector(".scene-object-checkbox");h&&(h.checked=u)});let t=(a=this.root)==null?void 0:a.querySelector("[data-breadcrumbs]"),n=(s=this.root)==null?void 0:s.querySelector("[data-breadcrumb-screen]"),i=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumb-object]");if(t&&n&&i){let p=this.selectedIds.size===1?this.selectedId:null;if(p){let d=window.getEditableObjectConfig,u=typeof d=="function"?d(p):null;if(!u){let b=window.__editableObjectConfigs;b&&typeof b.get=="function"&&(u=(l=b.get(p))!=null?l:null)}let g=this.inferScreen(p,u),m={loading:"Loading",start:"Start",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},h=(((c=u==null?void 0:u.identity)==null?void 0:c.id)||p).toString(),f=this.formatDisplayName(h);n.textContent=m[g]||g,i.textContent=f,t.style.display="flex"}else t.style.display="none"}}refreshObjects(){var v;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.refreshEditableConfigIndex;if(typeof t=="function"&&t(),typeof e!="function"){this.scheduleRetry();return}let n=e();if(!Array.isArray(n)||n.length===0){let w=window.__editableObjectConfigs;w&&typeof w.keys=="function"&&(n=Array.from(w.keys()))}if(!Array.isArray(n)||n.length===0){this.scheduleRetry();return}let i=(((v=this.searchInput)==null?void 0:v.value)||"").trim().toLowerCase(),a=["loading","start","gameplay","tutorial","endgame"],s=Object.fromEntries(a.map(w=>[w,[]])),o=Object.fromEntries(a.map(w=>[w,[]])),l=[],c=[],p=new Map;this.systemBundles=new Map;let d=w=>{var z,S,_,R,T;let E=(R=(_=(S=(z=window.__editableConfig)==null?void 0:z.objects)==null?void 0:S.get)==null?void 0:_.call(S,w))!=null?R:null;if(E)return E;let j=window.__editableObjectConfigs;return j&&typeof j.get=="function"&&(T=j.get(w))!=null?T:null};n.forEach(w=>{var H,N,G,K,ze,ue,ge,Ye;let E=d(w),j=(((H=E==null?void 0:E.identity)==null?void 0:H.category)||"scene").toString(),z=(((N=E==null?void 0:E.identity)==null?void 0:N.id)||w).toString(),S=j.toLowerCase(),_=z.toLowerCase(),R=S.includes("ui")||_.startsWith("ui")||_.includes("label"),T=S==="system",C=((G=E==null?void 0:E.identity)==null?void 0:G.is_template)===!0||_.includes(".template")||w.toLowerCase().includes(".template"),M=typeof((K=E==null?void 0:E.identity)==null?void 0:K.system_group)=="string"?E.identity.system_group:null,k=typeof((ze=E==null?void 0:E.identity)==null?void 0:ze.system_label)=="string"?E.identity.system_label:M?this.formatDisplayName(M):null,A=this.formatDisplayName(z||w),x=((ue=E==null?void 0:E.render)==null?void 0:ue.visible)===!1||(E==null?void 0:E.enabled)===!1,I=this.getObjectType(E),L={id:w,label:A,category:j,isUi:R,isTemplate:C,isUnused:x,objectType:I,systemGroupId:M,systemLabel:k},P=this.inferScreen(L.id,E);if(!(this.screenFilter!=="all"&&P!==this.screenFilter||!(!i||L.id.toLowerCase().includes(i)||L.label.toLowerCase().includes(i)))){if(M){if(C&&!this.showTemplates)return;let D=(ge=p.get(M))!=null?ge:[];D.push(L),p.set(M,D);let Z=(Ye=this.systemBundles.get(M))!=null?Ye:{label:k!=null?k:M,objectIds:[]};Z.label=k!=null?k:Z.label,Z.objectIds.push(w),this.systemBundles.set(M,Z);return}if(C){if(!this.showTemplates)return;c.push(L);return}T?l.push(L):(L.isUnused?o:s)[P].push(L)}});let u={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},m=[...Array.from(p.entries()).map(([w,E])=>{var j,z,S,_;return{groupId:w,label:(z=(j=this.systemBundles.get(w))==null?void 0:j.label)!=null?z:w,objectIds:(_=(S=this.systemBundles.get(w))==null?void 0:S.objectIds)!=null?_:[],entries:E}})].sort((w,E)=>w.label.localeCompare(E.label)),h=m.length>0?this.renderSystemBundlesGroup(m):"",f=l.length>0?this.renderSystemGroup(l):"",b=a.map(w=>this.renderGroup(u[w],[...s[w],...o[w]])).join(""),y=c.length>0?this.renderGroup("Templates",c):"";if(this.listContainer.innerHTML=h+f+b+y,this.objectEntries=[...m.flatMap(w=>w.entries),...l,...a.flatMap(w=>[...s[w],...o[w]]),...c],l.length>0){let w=this.listContainer.querySelector("[data-delete-system-group]");w==null||w.addEventListener("click",E=>{E.stopPropagation(),this.deleteSystemGroup(l)})}this.updateSelectionUI()}renderSystemBundlesGroup(e){if(!e.length)return"";let t=e.map(n=>this.renderSystemBundle(n.groupId,n.label,n.objectIds,n.entries)).join("");return`
|
|
526
|
+
<div class="scene-object-group scene-object-group-system">
|
|
527
|
+
<div class="scene-object-group-title">
|
|
528
|
+
<span>\u{1F9E9} Systems <span class="scene-object-count">${e.length}</span></span>
|
|
529
|
+
</div>
|
|
530
|
+
<div class="scene-object-group-items">
|
|
531
|
+
${t}
|
|
532
|
+
</div>
|
|
533
|
+
</div>
|
|
534
|
+
`}renderSystemBundle(e,t,n,i){let a=this.isBundleAllHidden(n),s=a?"Show all objects in this system":"Hide all objects in this system",o=a?"is-hidden":"",l=i.map(p=>this.renderEntryItem(p)).join(""),c=this.escapeHtml(e);return`
|
|
535
|
+
<div class="scene-object-group scene-object-group-bundle" data-system-bundle="${c}">
|
|
536
|
+
<div class="scene-object-group-title">
|
|
537
|
+
<span>${this.escapeHtml(t)} <span class="scene-object-count">${n.length}</span></span>
|
|
538
|
+
<div class="scene-object-group-actions">
|
|
539
|
+
<button class="scene-object-group-action scene-object-group-visibility ${o}" data-system-bundle-action="toggle-visibility" data-system-bundle-id="${c}" type="button" title="${s}">\u{1F441}\uFE0F</button>
|
|
540
|
+
<button class="scene-object-group-delete" data-system-bundle-action="delete" data-system-bundle-id="${c}" type="button" title="Delete this system">\u{1F5D1}\uFE0F</button>
|
|
541
|
+
</div>
|
|
542
|
+
</div>
|
|
543
|
+
<div class="scene-object-group-items">
|
|
544
|
+
${l}
|
|
545
|
+
</div>
|
|
546
|
+
</div>
|
|
547
|
+
`}renderEntryItem(e){var o,l;let t=window.getEditableObjectConfig,n=typeof t=="function"?t(e.id):null;if(!n){let c=window.__editableObjectConfigs;c&&typeof c.get=="function"&&(n=(o=c.get(e.id))!=null?o:null)}let i=(l=n==null?void 0:n.ui)!=null&&l.text?`"${n.ui.text.substring(0,12)}${n.ui.text.length>12?"...":""}"`:"",a=e.isTemplate?'<span class="scene-object-badge template">template</span>':"";return`
|
|
548
|
+
<div class="scene-object-item-wrapper">
|
|
549
|
+
<input type="checkbox" class="scene-object-checkbox" ${this.selectedIds.has(e.id)?"checked":""} data-object-id="${e.id}">
|
|
550
|
+
<button class="scene-object-item ${e.isUnused?"unused":""}" data-object-id="${e.id}">
|
|
551
|
+
<span class="scene-object-label">${e.label}</span>
|
|
552
|
+
${i?`<span class="scene-object-text-preview">${i}</span>`:""}
|
|
553
|
+
${a}
|
|
554
|
+
<span class="scene-object-badge ${e.isUi?"ui":"scene"}">${e.category}</span>
|
|
555
|
+
</button>
|
|
556
|
+
</div>
|
|
557
|
+
`}escapeHtml(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}isBundleAllHidden(e){var n;if(!e.length)return!1;let t=(n=window.__editableConfig)==null?void 0:n.objects;return e.every(i=>{var s,o,l;let a=(o=(s=t==null?void 0:t.get)==null?void 0:s.call(t,i))!=null?o:null;return((l=a==null?void 0:a.render)==null?void 0:l.visible)===!1})}toggleSystemBundleVisibility(e){var o;let t=this.systemBundles.get(e);if(!t)return;let n=t.objectIds||[];if(!n.length)return;let i=(o=window.__editableConfig)==null?void 0:o.objects;if(!i||typeof i.get!="function")return;let s=this.isBundleAllHidden(n);n.forEach(l=>{let c=i.get(l);c&&(c.render||(c.render={}),c.render.visible=s)});try{window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}}))}catch{}this.refreshObjects()}async deleteSystemBundle(e){let t=this.systemBundles.get(e);if(!t)return;let n=t.label||e,i=Array.from(new Set(t.objectIds||[]));!i.length||!window.confirm(`Delete system "${n}" (${i.length} object${i.length!==1?"s":""})? This removes them from the screen configuration.`)||await this.deleteMultipleObjects(i)}formatDisplayName(e){let t=e.replace(/^json\./,"").replace(/^ui\./,"").replace(/_\d+$/,"").replace(/\./g," ").replace(/_/g," ");return t=t.split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" "),t}inferScreen(e,t){var o,l;let n=window.__HANDLER_SCREEN_INDEX,i=(o=n==null?void 0:n.instanceToScreen)==null?void 0:o[e];if(i==="loading"||i==="start"||i==="gameplay"||i==="tutorial"||i==="endgame")return i;let a=(((l=t==null?void 0:t.identity)==null?void 0:l.id)||"").toString(),s=`${e} ${a}`.toLowerCase();return s.includes("loading")?"loading":s.includes("start")?"start":s.includes("tutorial")?"tutorial":s.includes("endgame")||s.includes("end_card")||s.includes("endcard")?"endgame":"gameplay"}getObjectType(e){var t,n,i,a,s,o,l,c,p;return e?(t=e.ui)!=null&&t.text?"text":(a=(i=(n=e.render)==null?void 0:n.asset)==null?void 0:i.path)!=null&&a.endsWith(".json")?"animation":((o=(s=e.render)==null?void 0:s.asset)==null?void 0:o.type)==="image"||(l=e.render)!=null&&l.texture?"sprite":(p=(c=e.gameplay)==null?void 0:c.tuning)!=null&&p.panel_width?"graphics":"container":"container"}renderGroup(e,t){if(!t.length)return"";let n=window.getEditableObjectConfig,i=t.map(a=>{var u,g;let s=typeof n=="function"?n(a.id):null;if(!s){let m=window.__editableObjectConfigs;m&&typeof m.get=="function"&&(s=(u=m.get(a.id))!=null?u:null)}let o=this.getTypeIconByType(a.objectType),l=this.getAssetPreview(s),c=(g=s==null?void 0:s.ui)!=null&&g.text?`"${s.ui.text.substring(0,12)}${s.ui.text.length>12?"...":""}"`:"",p=a.isTemplate?'<span class="scene-object-badge template">template</span>':"";return`
|
|
509
558
|
<div class="scene-object-item-wrapper">
|
|
510
559
|
<input type="checkbox" class="scene-object-checkbox" ${this.selectedIds.has(a.id)?"checked":""} data-object-id="${a.id}">
|
|
511
560
|
<button class="scene-object-item ${a.isUnused?"unused":""}" data-object-id="${a.id}">
|
|
@@ -541,18 +590,20 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
541
590
|
${n}
|
|
542
591
|
</div>
|
|
543
592
|
</div>
|
|
544
|
-
`}getTypeIconByType(e){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[e]||"\u{1F4E6}"}getTypeIcon(e){var n,i,a,s,o,l;if(!e)return"\u{1F4E6}";if((n=e.render)!=null&&n.texture){let c=e.render.texture;return c.includes("button")?"\u{1F518}":c.includes("key")?"\u{1F511}":"\u{1F5BC}\uFE0F"}if((i=e.ui)!=null&&i.text)return"\u{1F4DD}";if(((a=e.identity)==null?void 0:a.category)==="ui")return"\u{1F3A8}";if(e.effects||(o=(s=e.identity)==null?void 0:s.id)!=null&&o.includes("effect"))return"\u2728";if(e.audio)return"\u{1F50A}";let t=((l=e.identity)==null?void 0:l.id)||"";return t.includes("background")?"\u{1F5BC}\uFE0F":t.includes("character")?"\u{1F464}":t.includes("key")?"\u{1F511}":t.includes("draggable")?"\u{1F3AF}":t.includes("machine")?"\u2699\uFE0F":t.includes("tutorial")||t.includes("hand")?"\u{1F446}":"\u{1F4E6}"}getAssetPreview(e){var n;if(!e)return null;let t=(n=e.render)==null?void 0:n.texture;return t&&(t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg"))?t.startsWith("library/")||t.startsWith("/raw/")?`/raw/${t.replace(/^\/raw\//,"")}`:`/raw/${t}`:null}getColorIndicator(e){var n,i,a,s;if(!e)return"";let t=((n=e.render)==null?void 0:n.background_color)||((a=(i=e.gameplay)==null?void 0:i.tuning)==null?void 0:a.panel_bg_color)||((s=e.ui)==null?void 0:s.backgroundColor);return t?`<span class="scene-object-color-dot" style="background-color: ${t}" title="${t}"></span>`:""}getMetadata(e){var n,i,a,s;if(!e)return"";let t=[];return((n=e.render)==null?void 0:n.visible)===!1&&t.push("hidden"),((i=e.render)==null?void 0:i.z_index)!==void 0&&t.push(`z:${e.render.z_index}`),((a=e.interaction)!=null&&a.clickable||(s=e.ui)!=null&&s.button)&&t.push("clickable"),t.length>0?t.join(" \u2022 "):""}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refreshObjects()},400))}select(e){var t,n,i;this.selectedId=e,this.selectedIds.has(e)||this.selectedIds.add(e),this.updateLastSelectedIndex(e),this.updateSelectionUI(),(t=this.options)==null||t.onSelect(e),(i=(n=this.options)==null?void 0:n.onMultiSelect)==null||i.call(n,Array.from(this.selectedIds))}toggleBatchSelect(e){var t,n;this.selectedIds.has(e)?this.selectedIds.delete(e):this.selectedIds.add(e),this.updateSelectionUI(),(n=(t=this.options)==null?void 0:t.onMultiSelect)==null||n.call(t,Array.from(this.selectedIds))}toggleSelect(e){this.toggleBatchSelect(e)}selectRange(e,t){var s,o,l;let n=this.objectEntries.findIndex(c=>c.id===t);if(n===-1)return;let i=Math.min(e,n),a=Math.max(e,n);for(let c=i;c<=a;c++)c>=0&&c<this.objectEntries.length&&this.selectedIds.add(this.objectEntries[c].id);this.selectedId=t,this.updateLastSelectedIndex(t),this.updateSelectionUI(),(s=this.options)==null||s.onSelect(this.selectedId),(l=(o=this.options)==null?void 0:o.onMultiSelect)==null||l.call(o,Array.from(this.selectedIds))}updateLastSelectedIndex(e){this.lastSelectedIndex=this.objectEntries.findIndex(t=>t.id===e)}getDefaultScreenForCreate(){if(this.screenFilter!=="all")return this.screenFilter;let e=window.__HANDLER_ACTIVE_SCREEN;return e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"}async openAddObjectMenu(e){try{await new
|
|
545
|
-
`))||(o==null?void 0:o.error)||"Delete failed.";alert(l);return}
|
|
593
|
+
`}getTypeIconByType(e){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[e]||"\u{1F4E6}"}getTypeIcon(e){var n,i,a,s,o,l;if(!e)return"\u{1F4E6}";if((n=e.render)!=null&&n.texture){let c=e.render.texture;return c.includes("button")?"\u{1F518}":c.includes("key")?"\u{1F511}":"\u{1F5BC}\uFE0F"}if((i=e.ui)!=null&&i.text)return"\u{1F4DD}";if(((a=e.identity)==null?void 0:a.category)==="ui")return"\u{1F3A8}";if(e.effects||(o=(s=e.identity)==null?void 0:s.id)!=null&&o.includes("effect"))return"\u2728";if(e.audio)return"\u{1F50A}";let t=((l=e.identity)==null?void 0:l.id)||"";return t.includes("background")?"\u{1F5BC}\uFE0F":t.includes("character")?"\u{1F464}":t.includes("key")?"\u{1F511}":t.includes("draggable")?"\u{1F3AF}":t.includes("machine")?"\u2699\uFE0F":t.includes("tutorial")||t.includes("hand")?"\u{1F446}":"\u{1F4E6}"}getAssetPreview(e){var n;if(!e)return null;let t=(n=e.render)==null?void 0:n.texture;return t&&(t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg"))?t.startsWith("library/")||t.startsWith("/raw/")?`/raw/${t.replace(/^\/raw\//,"")}`:`/raw/${t}`:null}getColorIndicator(e){var n,i,a,s;if(!e)return"";let t=((n=e.render)==null?void 0:n.background_color)||((a=(i=e.gameplay)==null?void 0:i.tuning)==null?void 0:a.panel_bg_color)||((s=e.ui)==null?void 0:s.backgroundColor);return t?`<span class="scene-object-color-dot" style="background-color: ${t}" title="${t}"></span>`:""}getMetadata(e){var n,i,a,s;if(!e)return"";let t=[];return((n=e.render)==null?void 0:n.visible)===!1&&t.push("hidden"),((i=e.render)==null?void 0:i.z_index)!==void 0&&t.push(`z:${e.render.z_index}`),((a=e.interaction)!=null&&a.clickable||(s=e.ui)!=null&&s.button)&&t.push("clickable"),t.length>0?t.join(" \u2022 "):""}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refreshObjects()},400))}select(e){var t,n,i;this.selectedId=e,this.selectedIds.has(e)||this.selectedIds.add(e),this.updateLastSelectedIndex(e),this.updateSelectionUI(),(t=this.options)==null||t.onSelect(e),(i=(n=this.options)==null?void 0:n.onMultiSelect)==null||i.call(n,Array.from(this.selectedIds))}toggleBatchSelect(e){var t,n;this.selectedIds.has(e)?this.selectedIds.delete(e):this.selectedIds.add(e),this.updateSelectionUI(),(n=(t=this.options)==null?void 0:t.onMultiSelect)==null||n.call(t,Array.from(this.selectedIds))}toggleSelect(e){this.toggleBatchSelect(e)}selectRange(e,t){var s,o,l;let n=this.objectEntries.findIndex(c=>c.id===t);if(n===-1)return;let i=Math.min(e,n),a=Math.max(e,n);for(let c=i;c<=a;c++)c>=0&&c<this.objectEntries.length&&this.selectedIds.add(this.objectEntries[c].id);this.selectedId=t,this.updateLastSelectedIndex(t),this.updateSelectionUI(),(s=this.options)==null||s.onSelect(this.selectedId),(l=(o=this.options)==null?void 0:o.onMultiSelect)==null||l.call(o,Array.from(this.selectedIds))}updateLastSelectedIndex(e){this.lastSelectedIndex=this.objectEntries.findIndex(t=>t.id===e)}getDefaultScreenForCreate(){if(this.screenFilter!=="all")return this.screenFilter;let e=window.__HANDLER_ACTIVE_SCREEN;return e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"}async openAddObjectMenu(e){try{await new Cn({onRefresh:()=>this.refreshObjects(),onClose:()=>{}}).open(e)}catch(t){console.warn("[SceneObjectsPanel] Failed to open AddObjectMenu:",t)}}async openAddObjectWizard(e){try{new Sn().open({screenId:e})}catch(t){console.warn("[SceneObjectsPanel] Failed to open AddObjectWizard:",t)}}async showContextMenu(e,t,n,i){if(!this.isContextMenuOpen){this.isContextMenuOpen=!0,this.selectedIds.has(e)||this.select(e);try{new An({objectId:e,screenId:t,onSelect:s=>{s&&this.select(s)},onRefresh:()=>this.refreshObjects(),onClose:()=>{this.isContextMenuOpen=!1},onDeleteRequest:s=>this.deleteObject(s),onMoveRequest:(s,o)=>this.moveObject(s,o)}).open({x:n,y:i})}catch(a){this.isContextMenuOpen=!1,console.warn("[SceneObjectsPanel] Failed to open context menu:",a)}}}async deleteObject(e){var i;let t=this.getSelectedIds();if(t.length>1&&t.includes(e)){if(!window.confirm(`Delete ${t.length} selected object${t.length!==1?"s":""}? This removes them from the screen configuration.`))return;await this.deleteMultipleObjects(t)}else{if(!window.confirm(`Delete "${e}"? This removes it from the screen configuration.`))return;try{let s=await fetch("/api/objects/delete",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e})}),o=await s.json().catch(()=>null);if(!s.ok||(o==null?void 0:o.success)===!1){let l=((i=o==null?void 0:o.errors)==null?void 0:i.join(`
|
|
594
|
+
`))||(o==null?void 0:o.error)||"Delete failed.";alert(l);return}o!=null&&o.failedDeletions&&o.failedDeletions.length>0&&alert(`Warning: Some files could not be deleted:
|
|
595
|
+
${o.failedDeletions.join(`
|
|
596
|
+
`)}`),o!=null&&o.deletedFiles&&o.deletedFiles.length>0&&console.log(`[SceneObjectsPanel] Successfully deleted files: ${o.deletedFiles.join(", ")}`),await this.syncScreens(),this.selectedIds.delete(e),this.selectedId===e&&(this.selectedId=null),this.refreshObjects()}catch(s){alert(`Delete failed: ${s instanceof Error?s.message:String(s)}`)}}}async deleteMultipleObjects(e){var a;let t=0,n=0,i=[];for(let s of e)try{let o=await fetch("/api/objects/delete",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:s})}),l=await o.json().catch(()=>null);if(o.ok&&(l==null?void 0:l.success)!==!1)t++,this.selectedIds.delete(s);else{n++;let c=((a=l==null?void 0:l.errors)==null?void 0:a.join(`
|
|
546
597
|
`))||(l==null?void 0:l.error)||"Delete failed.";i.push(`${s}: ${c}`)}}catch(o){n++,i.push(`${s}: ${o instanceof Error?o.message:String(o)}`)}if(n>0){let s=i.length>0?i.join(`
|
|
547
598
|
`):`${n} object(s) failed to delete.`;alert(`Deleted ${t} object(s). Errors:
|
|
548
|
-
${s}`)}this.selectedId=this.selectedIds.size>0?Array.from(this.selectedIds)[0]:null,await this.syncScreens(),this.refreshObjects()}async deleteSystemGroup(e){var l;let t=e.length;if(!window.confirm(`Delete all ${t} system object${t!==1?"s":""}? This will remove them from all screens.`))return;let i=e.map(c=>c.id),a=0,s=0,o=[];for(let c of i)try{let p=await fetch("/api/objects/delete",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:c})}),d=await p.json().catch(()=>null);if(p.ok&&(d==null?void 0:d.success)!==!1)a++;else{s++;let u=((l=d==null?void 0:d.errors)==null?void 0:l.join(`
|
|
599
|
+
${s}`)}t===e.length&&console.log(`[SceneObjectsPanel] Successfully deleted ${t} object(s)`),this.selectedId=this.selectedIds.size>0?Array.from(this.selectedIds)[0]:null,await this.syncScreens(),this.refreshObjects()}async deleteSystemGroup(e){var l;let t=e.length;if(!window.confirm(`Delete all ${t} system object${t!==1?"s":""}? This will remove them from all screens.`))return;let i=e.map(c=>c.id),a=0,s=0,o=[];for(let c of i)try{let p=await fetch("/api/objects/delete",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:c})}),d=await p.json().catch(()=>null);if(p.ok&&(d==null?void 0:d.success)!==!1)a++;else{s++;let u=((l=d==null?void 0:d.errors)==null?void 0:l.join(`
|
|
549
600
|
`))||(d==null?void 0:d.error)||"Delete failed.";o.push(`${c}: ${u}`)}}catch(p){s++,o.push(`${c}: ${p instanceof Error?p.message:String(p)}`)}if(s>0){let c=o.length>0?o.join(`
|
|
550
601
|
`):`${s} object(s) failed to delete.`;alert(`Deleted ${a} object(s). Errors:
|
|
551
602
|
${c}`)}await this.syncScreens(),this.refreshObjects()}async moveObject(e,t){var a;let n=this.getSelectedIds();if(n.length>1&&n.includes(e))await this.moveMultipleObjects(n,t);else{let s=this.inferScreen(e,null);if(t===s)return;try{let o=await fetch("/api/objects/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e,fromScreenId:s,toScreenId:t})}),l=await o.json().catch(()=>({}));if(!o.ok||(l==null?void 0:l.success)===!1){let c=((a=l==null?void 0:l.errors)==null?void 0:a.join(`
|
|
552
603
|
`))||(l==null?void 0:l.error)||"Move failed.";alert(c);return}this.refreshObjects()}catch(o){alert(`Move failed: ${o instanceof Error?o.message:String(o)}`)}}}async moveMultipleObjects(e,t){var s;let n=0,i=0,a=[];for(let o of e){let l=this.inferScreen(o,null);if(t===l){n++;continue}try{let c=await fetch("/api/objects/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:o,fromScreenId:l,toScreenId:t})}),p=await c.json().catch(()=>({}));if(c.ok&&(p==null?void 0:p.success)!==!1)n++;else{i++;let d=((s=p==null?void 0:p.errors)==null?void 0:s.join(`
|
|
553
604
|
`))||(p==null?void 0:p.error)||"Move failed.";a.push(`${o}: ${d}`)}}catch(c){i++,a.push(`${o}: ${c instanceof Error?c.message:String(c)}`)}}if(i>0){let o=a.length>0?a.join(`
|
|
554
605
|
`):`${i} object(s) failed to move.`;alert(`Moved ${n} object(s). Errors:
|
|
555
|
-
${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-screens",{method:"POST"})}catch(e){console.warn("[SceneObjectsPanel] Failed to sync screens:",e)}}};var
|
|
606
|
+
${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-screens",{method:"POST"})}catch(e){console.warn("[SceneObjectsPanel] Failed to sync screens:",e)}}};var Ln=class{constructor(){this.root=null;this.options=null;this.isCollapsed=!1}render(){return`
|
|
556
607
|
<div class="scene-tools-corner-panel ${this.isCollapsed?"collapsed":""}" data-panel="scene-tools-corner">
|
|
557
608
|
<div class="scene-tools-header" data-tools-header data-panel-handle>
|
|
558
609
|
<span class="scene-tools-title">Scene Tools</span>
|
|
@@ -597,7 +648,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
597
648
|
</div>
|
|
598
649
|
</div>
|
|
599
650
|
</div>
|
|
600
|
-
`}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let n=localStorage.getItem("scene-tools-collapsed");n!==null&&(this.isCollapsed=n==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let i=this.root.querySelector("[data-tools-collapse]");i==null||i.addEventListener("click",()=>{var c;this.isCollapsed=!this.isCollapsed,(c=this.root)==null||c.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let a=(c,p)=>{var u;let d=(u=this.root)==null?void 0:u.querySelector(`[data-status="${c}"]`);d&&d.classList.toggle("active",p)},s=this.root.querySelector("#debug-highlight-object");s==null||s.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightObject(!!s.checked),a("bounds",s.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightAnchor(!!o.checked),a("anchor",o.checked)});let l=this.root.querySelector("#debug-nudge-enabled");l==null||l.addEventListener("change",()=>{a("nudge",l.checked)})}updateInfo(e){}};var
|
|
651
|
+
`}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let n=localStorage.getItem("scene-tools-collapsed");n!==null&&(this.isCollapsed=n==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let i=this.root.querySelector("[data-tools-collapse]");i==null||i.addEventListener("click",()=>{var c;this.isCollapsed=!this.isCollapsed,(c=this.root)==null||c.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let a=(c,p)=>{var u;let d=(u=this.root)==null?void 0:u.querySelector(`[data-status="${c}"]`);d&&d.classList.toggle("active",p)},s=this.root.querySelector("#debug-highlight-object");s==null||s.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightObject(!!s.checked),a("bounds",s.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightAnchor(!!o.checked),a("anchor",o.checked)});let l=this.root.querySelector("#debug-nudge-enabled");l==null||l.addEventListener("change",()=>{a("nudge",l.checked)})}updateInfo(e){}};var kn=class{constructor(){this.root=null;this.options=null}render(){return`
|
|
601
652
|
<div class="nudge-panel hidden" data-panel="nudge-panel">
|
|
602
653
|
<div class="nudge-panel-header" data-panel-handle>
|
|
603
654
|
<span class="nudge-panel-title">Nudge Controls</span>
|
|
@@ -654,7 +705,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
654
705
|
</div>
|
|
655
706
|
</div>
|
|
656
707
|
</div>
|
|
657
|
-
`}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="nudge-panel"]'),!this.root)return;Array.from(this.root.querySelectorAll(".nudge-arrow-btn")).forEach(a=>{a.addEventListener("click",()=>{var l,c,p,d;let s=a.dataset.nudge,o=this.getNudgeStep();switch(s){case"up":(l=this.options)==null||l.onNudge(0,-o);break;case"down":(c=this.options)==null||c.onNudge(0,o);break;case"left":(p=this.options)==null||p.onNudge(-o,0);break;case"right":(d=this.options)==null||d.onNudge(o,0);break}})}),Array.from(this.root.querySelectorAll(".nudge-scale-btn")).forEach(a=>{a.addEventListener("click",()=>{var l;let o=a.dataset.scale==="up"?.1:-.1;(l=this.options)==null||l.onScale(o)})})}show(){var e;(e=this.root)==null||e.classList.remove("hidden")}hide(){var e;(e=this.root)==null||e.classList.add("hidden")}getNudgeStep(){var n,i;let e=(n=this.root)==null?void 0:n.querySelector("#nudge-step-input"),t=Number((i=e==null?void 0:e.value)!=null?i:10);return Number.isFinite(t)&&t>0?t:10}};var
|
|
708
|
+
`}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="nudge-panel"]'),!this.root)return;Array.from(this.root.querySelectorAll(".nudge-arrow-btn")).forEach(a=>{a.addEventListener("click",()=>{var l,c,p,d;let s=a.dataset.nudge,o=this.getNudgeStep();switch(s){case"up":(l=this.options)==null||l.onNudge(0,-o);break;case"down":(c=this.options)==null||c.onNudge(0,o);break;case"left":(p=this.options)==null||p.onNudge(-o,0);break;case"right":(d=this.options)==null||d.onNudge(o,0);break}})}),Array.from(this.root.querySelectorAll(".nudge-scale-btn")).forEach(a=>{a.addEventListener("click",()=>{var l;let o=a.dataset.scale==="up"?.1:-.1;(l=this.options)==null||l.onScale(o)})})}show(){var e;(e=this.root)==null||e.classList.remove("hidden")}hide(){var e;(e=this.root)==null||e.classList.add("hidden")}getNudgeStep(){var n,i;let e=(n=this.root)==null?void 0:n.querySelector("#nudge-step-input"),t=Number((i=e==null?void 0:e.value)!=null?i:10);return Number.isFinite(t)&&t>0?t:10}};var _t=class{constructor(){this.root=null;this.slotsContainer=null;this.options=null;this.registry=null;this.expandedSlot=null}mergeRegistries(e,t){let n=e||{},i=t||{},a={slots:Array.isArray(i.slots)?[...i.slots]:[],libraryAssets:typeof i.libraryAssets=="object"&&i.libraryAssets?{...i.libraryAssets}:{},categories:Array.isArray(i.categories)?[...i.categories]:[]},s=Array.isArray(n.slots)?n.slots:[];if(s.length>0&&a.slots.length>0)for(let c of a.slots){let p=s.find(d=>(d==null?void 0:d.slotId)&&d.slotId===(c==null?void 0:c.slotId));p!=null&&p.currentAsset&&p.currentAsset!==(c==null?void 0:c.currentAsset)&&(c.currentAsset=p.currentAsset)}let o=n.libraryAssets||{};for(let[c,p]of Object.entries(o)){if(!Array.isArray(p))continue;a.libraryAssets[c]||(a.libraryAssets[c]=[]);let d=new Set((a.libraryAssets[c]||[]).map(u=>u==null?void 0:u.filename));for(let u of p){let g=u==null?void 0:u.filename;!g||d.has(g)||(a.libraryAssets[c].unshift(u),d.add(g))}}let l=new Set(a.categories||[]);for(let c of n.categories||[])typeof c=="string"&&l.add(c);return a.categories=Array.from(l),a}render(){return`
|
|
658
709
|
<div class="scene-panel library-panel panel-accent-purple" data-panel="library">
|
|
659
710
|
<div class="scene-panel-header" data-panel-handle>
|
|
660
711
|
<div class="panel-title">
|
|
@@ -673,7 +724,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
673
724
|
</div>
|
|
674
725
|
<div class="panel-resize-handle" data-panel-resize></div>
|
|
675
726
|
</div>
|
|
676
|
-
`}initialize(e,t){var a,s,o;this.options=t,this.root=e.querySelector('[data-panel="library"]'),this.slotsContainer=(a=this.root)==null?void 0:a.querySelector("[data-library-slots]");let n=(s=this.root)==null?void 0:s.querySelector("[data-create-ai]");n==null||n.addEventListener("click",()=>{this.handleCreateWithAI()});let i=(o=this.root)==null?void 0:o.querySelector("[data-refresh-library]");i==null||i.addEventListener("click",()=>{i.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>i.classList.remove("pulse-anim"),500)}),this.loadAssetRegistry()}reRender(){console.log("[LIBRARY] Re-rendering slots..."),this.loadAssetRegistry()}async refresh(){console.log("[LIBRARY] Force refreshing asset registry...");try{let e=window.getEditableAssets,t=typeof e=="function"?e():null,n=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(n.ok){let i=await n.json(),a=this.mergeRegistries(t,i);window.getEditableAssets=()=>a,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(e){console.warn("[LIBRARY] Failed to re-fetch registry:",e)}this.loadAssetRegistry()}loadAssetRegistry(e=0){let t=window.getEditableAssets;if(typeof t=="function"){let n=t();if(n!=null&&n.slots&&Array.isArray(n.slots)&&n.slots.length>0){this.registry=n,console.log("[LIBRARY] Loaded slot-based registry:",this.registry.slots.length,"slots"),this.renderSlots();return}}e<15?(console.log(`[LIBRARY] Waiting for asset registry... (attempt ${e+1}/15)`),setTimeout(()=>this.loadAssetRegistry(e+1),200)):(console.warn("[LIBRARY] Failed to load asset registry"),this.slotsContainer&&(this.slotsContainer.innerHTML='<div class="library-info">No editable assets available</div>'))}renderSlots(){if(!this.slotsContainer||!this.registry)return;let e={};for(let n of this.registry.slots)e[n.category]||(e[n.category]=[]),e[n.category].push(n);let t=Date.now();this.slotsContainer.innerHTML="";for(let n of this.registry.categories){let i=e[n]||[];if(i.length===0)continue;let a=document.createElement("div");a.className="library-category";let s=document.createElement("div");s.className="library-category-header",s.textContent=this.formatCategoryName(n),a.appendChild(s);let o=document.createElement("div");o.className="library-category-slots";for(let l of i){let c=this.createSlotElement(l,t);o.appendChild(c)}a.appendChild(o),this.slotsContainer.appendChild(a)}}createSlotElement(e,t){let n=this.expandedSlot===e.slotId,i=document.createElement("div");i.className=`library-slot ${n?"expanded":""}`,i.dataset.slotId=e.slotId;let a=document.createElement("div");a.className="slot-header";let s=document.createElement("div");s.className="slot-current";let o=document.createElement("img");o.src=`/raw/${e.currentAsset}?t=${t}`,o.alt=e.displayName,o.className="slot-thumbnail",o.onerror=()=>{o.style.display="none"},s.appendChild(o),a.appendChild(s);let l=document.createElement("div");l.className="slot-info";let c=document.createElement("div");c.className="slot-name",c.textContent=e.displayName;let p=document.createElement("div");p.className="slot-asset",p.textContent=e.currentAsset,l.appendChild(c),l.appendChild(p),a.appendChild(l);let d=document.createElement("div");d.className="slot-actions";let u=document.createElement("button");u.className="slot-ai-edit",u.title="Edit with AI",u.textContent="\u2728 AI",u.addEventListener("click",async f=>{f.stopPropagation(),await this.handleAIEdit(e)}),d.appendChild(u);let g=document.createElement("button");g.className="slot-upload",g.title="Upload new asset",g.textContent="\u{1F4E4}",g.addEventListener("click",async f=>{f.stopPropagation(),await this.handleUpload(e)}),d.appendChild(g);let m=document.createElement("button");m.className="slot-reset",m.title="Reset to default",m.textContent="\u21BA",m.addEventListener("click",async f=>{f.stopPropagation(),await this.handleReset(e)}),d.appendChild(m);let h=document.createElement("span");if(h.className="slot-expand-icon",h.textContent=n?"\u25BC":"\u25B6",d.appendChild(h),a.appendChild(d),a.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===e.slotId?null:e.slotId,this.renderSlots()}),i.appendChild(a),n){let f=this.createLibraryElement(e,t);i.appendChild(f)}return i}createLibraryElement(e,t){var a;let n=document.createElement("div");n.className="slot-library";let i=((a=this.registry)==null?void 0:a.libraryAssets[e.libraryFolder])||[];return this.fetchFolderAssets(e.libraryFolder,t).then(s=>{let o=new Map;for(let c of i)o.set(c.filename,c);for(let c of s)o.has(c.filename)||o.set(c.filename,c);let l=Array.from(o.values());if(l.length===0){n.innerHTML='<div class="library-empty">No alternative assets</div>';return}n.innerHTML="";for(let c of l){let p=document.createElement("div");p.className="library-item";let d=document.createElement("img");d.src=`/raw/library/${e.libraryFolder}/${c.filename}?t=${t}`,d.alt=c.displayName,d.className="library-thumbnail",d.onerror=()=>{d.style.opacity="0.3"},p.appendChild(d);let u=document.createElement("div");u.className="library-label",u.textContent=c.displayName,p.appendChild(u),p.addEventListener("click",async()=>{await this.handleApply(e,c.filename)}),n.appendChild(p)}}),n.innerHTML='<div class="library-loading">Loading assets...</div>',n}async fetchFolderAssets(e,t){try{let n=await fetch(`/raw/library/${e}/?t=${t}`);if(!n.ok)return[];let i=await n.text(),a=[],s=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=s.exec(i))!==null;){let l=o[1];if(!l.startsWith("/")&&!l.startsWith("..")){let c=l.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");a.push({filename:l,displayName:c})}}return a}catch{return console.log("[LIBRARY] Could not fetch folder listing, using registry only"),[]}}async handleApply(e,t){var n;console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{let i=window.__wizardAssetPicker;if(i!=null&&i.onPick){let a=`raw/library/${e.libraryFolder}/${t}`;i.onPick(a),window.__wizardAssetPicker=null;return}await((n=this.options)==null?void 0:n.onApply(e.objectId,t,e.category)),e.currentAsset=t,this.renderSlots()}catch(i){console.error("[LIBRARY] Failed to apply asset:",i)}}async handleReset(e){var t;console.log("[LIBRARY] Resetting slot:",e.slotId,"to default:",e.defaultAsset);try{await((t=this.options)==null?void 0:t.onReset(e.objectId,e.defaultAsset,e.category)),e.currentAsset=e.defaultAsset,this.renderSlots()}catch(n){console.error("[LIBRARY] Failed to reset slot:",n)}}formatCategoryName(e){return e.replace(/_/g," ").split(" ").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async handleAIEdit(e){console.log("[Library] Opening AI Edit for slot:",e);let t=window.__openAiEditor;if(typeof t=="function"){let n=e.slotId||e.objectId,i="render.texture";e.category==="ui"&&(i="ui.image"),e.category==="audio"&&(i="audio.src"),t(n,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:i})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}async handleUpload(e){console.log("[Library] Opening file upload for slot:",e);let t=document.createElement("input");t.type="file",t.accept="image/*",t.style.display="none",t.addEventListener("change",async()=>{var i;let n=(i=t.files)==null?void 0:i[0];if(n){console.log("[Library] File selected:",n.name);try{let a=await this.fileToDataUrl(n);if(!a){alert("Failed to read file");return}let o=`${e.displayName.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,l=e.category;console.log("[Library] Saving uploaded file:",o,"to category:",l);let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:l,filename:`${o}.png`,data:a,overwrite:!0})})).json();if(p.success){console.log("[Library] \u2705 Upload saved:",p.path);let d=window.addAssetToRegistry;typeof d=="function"&&d(l,`${o}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(u){console.warn("[Library] Setup-library not available:",u)}await this.handleApply(e,`${o}.png`),e.currentAsset=`${o}.png`,await this.refresh(),setTimeout(()=>{this.highlightSlot(e.objectId,l)},500),console.log("[Library] \u2705 Upload complete and applied")}else console.error("[Library] \u274C Upload failed:",p.error),alert(`Upload failed: ${p.error}`)}catch(a){console.error("[Library] \u274C Upload error:",a),alert("Upload failed. Check console for details.")}finally{t.remove()}}}),document.body.appendChild(t),t.click()}fileToDataUrl(e){return new Promise(t=>{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>t(null),n.readAsDataURL(e)})}handleCreateWithAI(){console.log("[Library] Opening AI Create modal");let e=window.__openAiEditor;typeof e=="function"?e("new_asset","Create new asset with AI"):(console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded."))}highlightSlot(e,t){if(!this.registry||!this.slotsContainer)return;let n=e.startsWith("json.")?e.replace("json.",""):e,i=this.registry.slots.find(a=>(a.objectId===n||a.slotId===n)&&(!t||a.category===t));i?(console.log("[LIBRARY] Highlighting slot:",i.slotId),this.expandedSlot=i.slotId,this.renderSlots(),setTimeout(()=>{var s;let a=(s=this.slotsContainer)==null?void 0:s.querySelector(`[data-slot-id="${i.slotId}"]`);a&&(a.scrollIntoView({behavior:"smooth",block:"center"}),a.classList.add("highlight-pulse"),setTimeout(()=>a.classList.remove("highlight-pulse"),3e3))},100)):console.warn("[LIBRARY] No slot found for highlight:",e,t)}};var Ln=class{detectType(e,t,n){let i=e.toLowerCase();return i==="logic_id"||i==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":i.includes("color")||i.includes("tint")?"color":typeof t=="boolean"?"boolean":typeof t=="number"?"number":Array.isArray(t)?"array":typeof t=="object"&&t!==null?"object":"text"}isHexColor(e){return/^#[0-9a-fA-F]{6}$/i.test(e)}isImagePath(e){return/\.(png|jpg|jpeg|gif|svg)$/i.test(e)}};var kn=class{render(e,t,n,i){let a=this.formatLabel(t),s=n?this.getThumbnailUrl(n):"";return`
|
|
727
|
+
`}initialize(e,t){var a,s,o;this.options=t,this.root=e.querySelector('[data-panel="library"]'),this.slotsContainer=(a=this.root)==null?void 0:a.querySelector("[data-library-slots]");let n=(s=this.root)==null?void 0:s.querySelector("[data-create-ai]");n==null||n.addEventListener("click",()=>{this.handleCreateWithAI()});let i=(o=this.root)==null?void 0:o.querySelector("[data-refresh-library]");i==null||i.addEventListener("click",()=>{i.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>i.classList.remove("pulse-anim"),500)}),this.loadAssetRegistry()}reRender(){console.log("[LIBRARY] Re-rendering slots..."),this.loadAssetRegistry()}async refresh(){console.log("[LIBRARY] Force refreshing asset registry...");try{let e=window.getEditableAssets,t=typeof e=="function"?e():null,n=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(n.ok){let i=await n.json(),a=this.mergeRegistries(t,i);window.getEditableAssets=()=>a,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(e){console.warn("[LIBRARY] Failed to re-fetch registry:",e)}this.loadAssetRegistry()}loadAssetRegistry(e=0){let t=window.getEditableAssets;if(typeof t=="function"){let n=t();if(n!=null&&n.slots&&Array.isArray(n.slots)&&n.slots.length>0){this.registry=n,console.log("[LIBRARY] Loaded slot-based registry:",this.registry.slots.length,"slots"),this.renderSlots();return}}e<15?(console.log(`[LIBRARY] Waiting for asset registry... (attempt ${e+1}/15)`),setTimeout(()=>this.loadAssetRegistry(e+1),200)):(console.warn("[LIBRARY] Failed to load asset registry"),this.slotsContainer&&(this.slotsContainer.innerHTML='<div class="library-info">No editable assets available</div>'))}renderSlots(){if(!this.slotsContainer||!this.registry)return;let e={};for(let n of this.registry.slots)e[n.category]||(e[n.category]=[]),e[n.category].push(n);let t=Date.now();this.slotsContainer.innerHTML="";for(let n of this.registry.categories){let i=e[n]||[];if(i.length===0)continue;let a=document.createElement("div");a.className="library-category";let s=document.createElement("div");s.className="library-category-header",s.textContent=this.formatCategoryName(n),a.appendChild(s);let o=document.createElement("div");o.className="library-category-slots";for(let l of i){let c=this.createSlotElement(l,t);o.appendChild(c)}a.appendChild(o),this.slotsContainer.appendChild(a)}}createSlotElement(e,t){let n=this.expandedSlot===e.slotId,i=document.createElement("div");i.className=`library-slot ${n?"expanded":""}`,i.dataset.slotId=e.slotId;let a=document.createElement("div");a.className="slot-header";let s=document.createElement("div");s.className="slot-current";let o=document.createElement("img");o.src=`/raw/${e.currentAsset}?t=${t}`,o.alt=e.displayName,o.className="slot-thumbnail",o.onerror=()=>{o.style.display="none"},s.appendChild(o),a.appendChild(s);let l=document.createElement("div");l.className="slot-info";let c=document.createElement("div");c.className="slot-name",c.textContent=e.displayName;let p=document.createElement("div");p.className="slot-asset",p.textContent=e.currentAsset,l.appendChild(c),l.appendChild(p),a.appendChild(l);let d=document.createElement("div");d.className="slot-actions";let u=document.createElement("button");u.className="slot-ai-edit",u.title="Edit with AI",u.textContent="\u2728 AI",u.addEventListener("click",async f=>{f.stopPropagation(),await this.handleAIEdit(e)}),d.appendChild(u);let g=document.createElement("button");g.className="slot-upload",g.title="Upload new asset",g.textContent="\u{1F4E4}",g.addEventListener("click",async f=>{f.stopPropagation(),await this.handleUpload(e)}),d.appendChild(g);let m=document.createElement("button");m.className="slot-reset",m.title="Reset to default",m.textContent="\u21BA",m.addEventListener("click",async f=>{f.stopPropagation(),await this.handleReset(e)}),d.appendChild(m);let h=document.createElement("span");if(h.className="slot-expand-icon",h.textContent=n?"\u25BC":"\u25B6",d.appendChild(h),a.appendChild(d),a.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===e.slotId?null:e.slotId,this.renderSlots()}),i.appendChild(a),n){let f=this.createLibraryElement(e,t);i.appendChild(f)}return i}createLibraryElement(e,t){var a;let n=document.createElement("div");n.className="slot-library";let i=((a=this.registry)==null?void 0:a.libraryAssets[e.libraryFolder])||[];return this.fetchFolderAssets(e.libraryFolder,t).then(s=>{let o=new Map;for(let c of i)o.set(c.filename,c);for(let c of s)o.has(c.filename)||o.set(c.filename,c);let l=Array.from(o.values());if(l.length===0){n.innerHTML='<div class="library-empty">No alternative assets</div>';return}n.innerHTML="";for(let c of l){let p=document.createElement("div");p.className="library-item";let d=document.createElement("img");d.src=`/raw/library/${e.libraryFolder}/${c.filename}?t=${t}`,d.alt=c.displayName,d.className="library-thumbnail",d.onerror=()=>{d.style.opacity="0.3"},p.appendChild(d);let u=document.createElement("div");u.className="library-label",u.textContent=c.displayName,p.appendChild(u),p.addEventListener("click",async()=>{await this.handleApply(e,c.filename)}),n.appendChild(p)}}),n.innerHTML='<div class="library-loading">Loading assets...</div>',n}async fetchFolderAssets(e,t){try{let n=await fetch(`/raw/library/${e}/?t=${t}`);if(!n.ok)return[];let i=await n.text(),a=[],s=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=s.exec(i))!==null;){let l=o[1];if(!l.startsWith("/")&&!l.startsWith("..")){let c=l.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");a.push({filename:l,displayName:c})}}return a}catch{return console.log("[LIBRARY] Could not fetch folder listing, using registry only"),[]}}async handleApply(e,t){var n;console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{let i=window.__wizardAssetPicker;if(i!=null&&i.onPick){let a=`raw/library/${e.libraryFolder}/${t}`;i.onPick(a),window.__wizardAssetPicker=null;return}await((n=this.options)==null?void 0:n.onApply(e.objectId,t,e.category)),e.currentAsset=t,this.renderSlots()}catch(i){console.error("[LIBRARY] Failed to apply asset:",i)}}async handleReset(e){var t;console.log("[LIBRARY] Resetting slot:",e.slotId,"to default:",e.defaultAsset);try{await((t=this.options)==null?void 0:t.onReset(e.objectId,e.defaultAsset,e.category)),e.currentAsset=e.defaultAsset,this.renderSlots()}catch(n){console.error("[LIBRARY] Failed to reset slot:",n)}}formatCategoryName(e){return e.replace(/_/g," ").split(" ").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async handleAIEdit(e){console.log("[Library] Opening AI Edit for slot:",e);let t=window.__openAiEditor;if(typeof t=="function"){let n=e.slotId||e.objectId,i="render.texture";e.category==="ui"&&(i="ui.image"),e.category==="audio"&&(i="audio.src"),t(n,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:i})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}async handleUpload(e){console.log("[Library] Opening file upload for slot:",e);let t=document.createElement("input");t.type="file",t.accept="image/*",t.style.display="none",t.addEventListener("change",async()=>{var i;let n=(i=t.files)==null?void 0:i[0];if(n){console.log("[Library] File selected:",n.name);try{let a=await this.fileToDataUrl(n);if(!a){alert("Failed to read file");return}let o=`${e.displayName.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,l=e.category;console.log("[Library] Saving uploaded file:",o,"to category:",l);let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:l,filename:`${o}.png`,data:a,overwrite:!0})})).json();if(p.success){console.log("[Library] \u2705 Upload saved:",p.path);let d=window.addAssetToRegistry;typeof d=="function"&&d(l,`${o}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(u){console.warn("[Library] Setup-library not available:",u)}await this.handleApply(e,`${o}.png`),e.currentAsset=`${o}.png`,await this.refresh(),setTimeout(()=>{this.highlightSlot(e.objectId,l)},500),console.log("[Library] \u2705 Upload complete and applied")}else console.error("[Library] \u274C Upload failed:",p.error),alert(`Upload failed: ${p.error}`)}catch(a){console.error("[Library] \u274C Upload error:",a),alert("Upload failed. Check console for details.")}finally{t.remove()}}}),document.body.appendChild(t),t.click()}fileToDataUrl(e){return new Promise(t=>{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>t(null),n.readAsDataURL(e)})}handleCreateWithAI(){console.log("[Library] Opening AI Create modal");let e=window.__openAiEditor;typeof e=="function"?e("new_asset","Create new asset with AI"):(console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded."))}highlightSlot(e,t){if(!this.registry||!this.slotsContainer)return;let n=e.startsWith("json.")?e.replace("json.",""):e,i=this.registry.slots.find(a=>(a.objectId===n||a.slotId===n)&&(!t||a.category===t));i?(console.log("[LIBRARY] Highlighting slot:",i.slotId),this.expandedSlot=i.slotId,this.renderSlots(),setTimeout(()=>{var s;let a=(s=this.slotsContainer)==null?void 0:s.querySelector(`[data-slot-id="${i.slotId}"]`);a&&(a.scrollIntoView({behavior:"smooth",block:"center"}),a.classList.add("highlight-pulse"),setTimeout(()=>a.classList.remove("highlight-pulse"),3e3))},100)):console.warn("[LIBRARY] No slot found for highlight:",e,t)}};var In=class{detectType(e,t,n){let i=e.toLowerCase();return i==="logic_id"||i==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":i.includes("color")||i.includes("tint")?"color":typeof t=="boolean"?"boolean":typeof t=="number"?"number":Array.isArray(t)?"array":typeof t=="object"&&t!==null?"object":"text"}isHexColor(e){return/^#[0-9a-fA-F]{6}$/i.test(e)}isImagePath(e){return/\.(png|jpg|jpeg|gif|svg)$/i.test(e)}};var jn=class{render(e,t,n,i){let a=this.formatLabel(t),s=n?this.getThumbnailUrl(n):"";return`
|
|
677
728
|
<div class="inspector-property" data-property-type="image">
|
|
678
729
|
<div class="inspector-property-header">
|
|
679
730
|
<label class="inspector-label">${a}</label>
|
|
@@ -695,7 +746,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
695
746
|
</div>
|
|
696
747
|
`}
|
|
697
748
|
</div>
|
|
698
|
-
`}getThumbnailUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("http")?e:`/raw/${e}?t=${Date.now()}`}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
749
|
+
`}getThumbnailUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("http")?e:`/raw/${e}?t=${Date.now()}`}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Mn=class{render(e,t,n,i){let a=n||"#000000";return`
|
|
699
750
|
<div class="inspector-property inspector-property-color">
|
|
700
751
|
<label class="inspector-property-label">${this.formatLabel(t)}</label>
|
|
701
752
|
<div class="inspector-color-group">
|
|
@@ -711,7 +762,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
711
762
|
data-object-id="${e}" />
|
|
712
763
|
</div>
|
|
713
764
|
</div>
|
|
714
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
765
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var _n=class{render(e,t,n,i){return`
|
|
715
766
|
<div class="inspector-property inspector-property-number">
|
|
716
767
|
<label class="inspector-property-label">${this.formatLabel(t)}</label>
|
|
717
768
|
<input type="number"
|
|
@@ -732,7 +783,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
732
783
|
data-object-id="${e}" />
|
|
733
784
|
</div>
|
|
734
785
|
</div>
|
|
735
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
786
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var On=class{render(e,t,n,i){return`
|
|
736
787
|
<div class="inspector-property inspector-property-boolean">
|
|
737
788
|
<label class="inspector-property-label">
|
|
738
789
|
<input type="checkbox"
|
|
@@ -743,7 +794,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
743
794
|
<span>${this.formatLabel(t)}</span>
|
|
744
795
|
</label>
|
|
745
796
|
</div>
|
|
746
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
797
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Rn=class{constructor(e){this.registry=e}render(e,t,n,i){if(t==="logic"&&this.registry){let s=this.registry,o=Array.isArray(n)?n:[],l=o.map((p,d)=>{let u=`${i}.${d}`,g=`
|
|
747
798
|
<button class="inspector-button inspector-button-small"
|
|
748
799
|
data-logic-remove="true"
|
|
749
800
|
data-object-id="${e}"
|
|
@@ -807,7 +858,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
807
858
|
${a}
|
|
808
859
|
</div>
|
|
809
860
|
</div>
|
|
810
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
861
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var zn=class{constructor(e){this.registry=e}render(e,t,n,i){if(t==="logic"&&n&&typeof n=="object"&&!Array.isArray(n))return this.renderLogic(e,t,n,i);let a=[];for(let o in n){let l=n[o],c=`${i}.${o}`,p=this.registry.renderProperty(e,o,l,c);p&&a.push(p)}return a.length===0?"":a.length<=4&&a.every(o=>o.includes("inspector-property"))?`
|
|
811
862
|
<div class="inspector-subsection">
|
|
812
863
|
<div class="inspector-subsection-title">${this.formatLabel(t)}</div>
|
|
813
864
|
<div class="inspector-subsection-content">
|
|
@@ -834,30 +885,30 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
834
885
|
</select>
|
|
835
886
|
</div>
|
|
836
887
|
</div>
|
|
837
|
-
`);for(let u in n){if(u==="id")continue;let g=n[u],m=`${i}.${u}`;if(u==="props"&&g&&typeof g=="object"){let f=[];for(let b in g){let y=g[b],v=`${m}.${b}`,
|
|
888
|
+
`);for(let u in n){if(u==="id")continue;let g=n[u],m=`${i}.${u}`;if(u==="props"&&g&&typeof g=="object"){let f=[];for(let b in g){let y=g[b],v=`${m}.${b}`,w=o[b];if(b==="targetId"||b==="inputId"){let E=this.registry.getObjectIds(),j=typeof y=="string"?y:"",z=j&&!E.includes(j)?[j,...E]:E;f.push(`
|
|
838
889
|
<div class="inspector-property inspector-property-text">
|
|
839
890
|
<label class="inspector-property-label">${this.formatLabel(b)}</label>
|
|
840
891
|
<div class="inspector-input-group">
|
|
841
892
|
<select class="inspector-component-select inspector-input"
|
|
842
893
|
data-property-path="${v}"
|
|
843
894
|
data-object-id="${e}">
|
|
844
|
-
<option value="" ${
|
|
845
|
-
${z.map(
|
|
895
|
+
<option value="" ${j?"":"selected"}>None</option>
|
|
896
|
+
${z.map(S=>`<option value="${S}" ${S===j?"selected":""}>${S}</option>`).join("")}
|
|
846
897
|
</select>
|
|
847
898
|
</div>
|
|
848
899
|
</div>
|
|
849
|
-
`);continue}if(Array.isArray(
|
|
900
|
+
`);continue}if(Array.isArray(w)&&w.length)f.push(`
|
|
850
901
|
<div class="inspector-property inspector-property-text">
|
|
851
902
|
<label class="inspector-property-label">${this.formatLabel(b)}</label>
|
|
852
903
|
<div class="inspector-input-group">
|
|
853
904
|
<select class="inspector-component-select inspector-input"
|
|
854
905
|
data-property-path="${v}"
|
|
855
906
|
data-object-id="${e}">
|
|
856
|
-
${
|
|
907
|
+
${w.map(E=>`<option value="${String(E)}" ${String(E)===String(y)?"selected":""}>${String(E)}</option>`).join("")}
|
|
857
908
|
</select>
|
|
858
909
|
</div>
|
|
859
910
|
</div>
|
|
860
|
-
`);else{let
|
|
911
|
+
`);else{let E=this.registry.renderProperty(e,b,y,v);E&&f.push(E)}}f.length&&a.push(`
|
|
861
912
|
<div class="inspector-property inspector-property-object">
|
|
862
913
|
<div class="inspector-object-header">Props</div>
|
|
863
914
|
<div class="inspector-object-body">
|
|
@@ -882,7 +933,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
882
933
|
${d}
|
|
883
934
|
</div>
|
|
884
935
|
</div>
|
|
885
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
936
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var $n=class{render(e,t,n,i,a){let s=n==null?"":String(n),o=Array.from(new Set(a.map(c=>String(c)))),l=s&&!o.includes(s)?[s,...o]:o;return`
|
|
886
937
|
<div class="inspector-property inspector-property-text">
|
|
887
938
|
<label class="inspector-property-label">${this.formatLabel(t)}</label>
|
|
888
939
|
<div class="inspector-input-group">
|
|
@@ -893,7 +944,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
893
944
|
</select>
|
|
894
945
|
</div>
|
|
895
946
|
</div>
|
|
896
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
947
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Dn=class{render(e,t,n,i){let a=this.safeStringify(n);return`
|
|
897
948
|
<div class="inspector-property inspector-property-text">
|
|
898
949
|
<label class="inspector-property-label">${this.formatLabel(t)}</label>
|
|
899
950
|
<div class="inspector-input-group">
|
|
@@ -904,7 +955,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
904
955
|
rows="6">${a}</textarea>
|
|
905
956
|
</div>
|
|
906
957
|
</div>
|
|
907
|
-
`}safeStringify(e){try{return JSON.stringify(e!=null?e:[],null,2)}catch{return"[]"}}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
958
|
+
`}safeStringify(e){try{return JSON.stringify(e!=null?e:[],null,2)}catch{return"[]"}}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Hn=class{render(e,t,n,i){let s=(Array.isArray(n)?n:[]).map((o,l)=>{let c=typeof(o==null?void 0:o.x)=="number"?o.x:0,p=typeof(o==null?void 0:o.y)=="number"?o.y:0;return`
|
|
908
959
|
<div class="inspector-row" style="gap:8px; align-items:center;">
|
|
909
960
|
<input type="number"
|
|
910
961
|
class="inspector-input"
|
|
@@ -937,7 +988,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
937
988
|
</div>
|
|
938
989
|
</div>
|
|
939
990
|
</div>
|
|
940
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
991
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Nn=class{constructor(e){this.registry=e}render(e,t,n,i){let a=Array.isArray(n)?n:[],o=["",...this.registry.getObjectIds()],l=a.map((c,p)=>{let d=typeof(c==null?void 0:c.templateId)=="string"?c.templateId:"",u=typeof(c==null?void 0:c.weight)=="number"?c.weight:1,g=o.map(m=>`<option value="${m}"${m===d?" selected":""}>${m||"(none)"}</option>`).join("");return`
|
|
941
992
|
<div class="inspector-row" style="gap:8px; align-items:center;">
|
|
942
993
|
<select class="inspector-select inspector-input"
|
|
943
994
|
data-property-path="${i}.${p}.templateId"
|
|
@@ -972,7 +1023,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
972
1023
|
</div>
|
|
973
1024
|
</div>
|
|
974
1025
|
</div>
|
|
975
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
1026
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Fn=class{constructor(){this.typeDetector=new In,this.imageRenderer=new jn,this.colorRenderer=new Mn,this.numberRenderer=new _n,this.textRenderer=new Pn,this.booleanRenderer=new On,this.arrayRenderer=new Rn(this),this.objectRenderer=new zn(this),this.selectRenderer=new $n,this.jsonRenderer=new Dn,this.spawnPointsRenderer=new Hn,this.spawnTemplatesRenderer=new Nn(this)}getObjectIds(){try{let e=window,t=e==null?void 0:e.__editableConfig;if(!(t!=null&&t.objects))return[];let n=[];if(t.objects instanceof Map)for(let i of t.objects.keys())n.push(i);else typeof t.objects=="object"&&n.push(...Object.keys(t.objects));return n.sort()}catch{return[]}}getEnumOptionsFromSchemas(e){var t;try{let n=window,i=n==null?void 0:n.__editableConfig,a=i==null?void 0:i.schemas;if(!a)return null;let s=String(e||"").split(".").filter(Boolean);if(s.length<2)return null;let o=s[0],l=s.slice(1).join("."),c=a instanceof Map?a.get(o):a==null?void 0:a[o];if(!c)return null;let p=(t=c==null?void 0:c.types)==null?void 0:t[l];if(typeof p!="string"||!p.startsWith("enum:"))return null;let u=p.slice(5).split("|").map(g=>g.trim()).filter(Boolean);return u.length?u:null}catch{return null}}getLogicOptions(){try{let e=window,t=Array.isArray(e==null?void 0:e.__HANDLER_LOGIC_OPTIONS)?e.__HANDLER_LOGIC_OPTIONS:[],i=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...t].map(a=>String(a)).filter(a=>a.trim().length>0);return Array.from(new Set(i)).sort((a,s)=>a.localeCompare(s))}catch{return[]}}renderProperty(e,t,n,i){let a=t.toLowerCase(),s=a==="logic"||a==="logic_id"||a==="logicid",o=a==="id"&&i.toLowerCase().includes("logic");if((s||o)&&typeof n=="string"){let m=this.getLogicOptions(),h=this.selectRenderer.render(e,t,n,i,m);return s?`
|
|
976
1027
|
${h}
|
|
977
1028
|
<div class="inspector-array-actions">
|
|
978
1029
|
<button class="inspector-button"
|
|
@@ -982,7 +1033,7 @@ ${h}
|
|
|
982
1033
|
Add Logic
|
|
983
1034
|
</button>
|
|
984
1035
|
</div>
|
|
985
|
-
`:h}let l={zone:["bottom-left","bottom-center","bottom-right","top-left","top-center","top-right"],directionMode:["dominantAxis","free"],axis:["both","x","y"],ease:["power2.out","linear","sine.inOut","back.out(1.8)"],direction:["any","horizontal","vertical"],spawnPattern:["continuous","onClick","wave","burst"],positionSource:["spawner","target","custom","random","points"],spawnPointMode:["cycle","random"],movementMode:["none","velocity"],particleEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],collectSound:["","click_4.wav","click_6.wav","success_4.wav"],hitEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],destroyEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],destroySound:["","click_4.wav","click_6.wav","success_4.wav"]},c={anchor:["center","top-left","top-center","top-right","bottom-left","bottom-center","bottom-right"]},p=l[t];if(p&&i.includes("logic.props"))return this.selectRenderer.render(e,t,n,i,p);let d=c[t];if(d&&(i.includes("transform")||i.includes("render"))&&!(t==="anchor"&&typeof n!="string"&&n!=null)){let m=t==="anchor"&&n==null?"center":n;return this.selectRenderer.render(e,t,m,i,d)}if(t==="spawnPoints"&&i.includes("logic.props"))return this.spawnPointsRenderer.render(e,t,n,i);if(t==="spawnTemplates"&&i.includes("logic.props"))return this.spawnTemplatesRenderer.render(e,t,n,i);if((t==="targetId"||t==="inputId"||t==="hitTemplateId"||t==="hpLabelId"||t==="hitPopupTemplateId")&&(n==null||typeof n=="string")){let m=this.getObjectIds(),h=this.selectRenderer.render(e,t,n!=null?n:"",i,["",...m]);return t==="hitTemplateId"&&i.includes("logic.props")?h+'<div class="inspector-text-sm" style="opacity:0.7; margin-top:4px;">Use template id (e.g. bullet_template), not spawner.</div>':h}if(i.includes("motion.")){if(t==="enabled")return this.booleanRenderer.render(e,t,!!n,i);if(t==="direction"&&(i.includes("continuousMove")||i.includes("continuousRotate")||i.includes("orbit"))){let h=["1","-1"],f=n==null?"1":String(n);return this.selectRenderer.render(e,t,f,i,h)}if(["speed","amplitude","intensity","minScale","maxScale","radius","lifetime","pivotOffsetX","pivotOffsetY","duration","delay","startScale","startAlpha","startYOffset","startXOffset"].includes(t)){let h=typeof n=="number"&&!Number.isNaN(n)?n:0;return this.numberRenderer.render(e,t,h,i)}}let u=this.getEnumOptionsFromSchemas(i);if(u)return this.selectRenderer.render(e,t,n,i,u);switch(this.typeDetector.detectType(t,n)){case"image":return this.imageRenderer.render(e,t,n,i);case"color":return this.colorRenderer.render(e,t,n,i);case"number":return this.numberRenderer.render(e,t,n,i);case"boolean":return this.booleanRenderer.render(e,t,n,i);case"array":return this.arrayRenderer.render(e,t,n,i);case"object":return this.objectRenderer.render(e,t,n,i);case"select":return this.selectRenderer.render(e,t,n,i,[]);default:return this.textRenderer.render(e,t,n,i)}}getTypeDetector(){return this.typeDetector}};function Ko(r,e){let t;return function(...i){let a=()=>{clearTimeout(t),r(...i)};clearTimeout(t),t=setTimeout(a,e)}}var
|
|
1036
|
+
`:h}let l={zone:["bottom-left","bottom-center","bottom-right","top-left","top-center","top-right"],directionMode:["dominantAxis","free"],axis:["both","x","y"],ease:["power2.out","linear","sine.inOut","back.out(1.8)"],direction:["any","horizontal","vertical"],spawnPattern:["continuous","onClick","wave","burst"],positionSource:["spawner","target","custom","random","points"],spawnPointMode:["cycle","random"],movementMode:["none","velocity"],particleEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],collectSound:["","click_4.wav","click_6.wav","success_4.wav"],hitEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],destroyEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],destroySound:["","click_4.wav","click_6.wav","success_4.wav"]},c={anchor:["center","top-left","top-center","top-right","bottom-left","bottom-center","bottom-right"]},p=l[t];if(p&&i.includes("logic.props"))return this.selectRenderer.render(e,t,n,i,p);let d=c[t];if(d&&(i.includes("transform")||i.includes("render"))&&!(t==="anchor"&&typeof n!="string"&&n!=null)){let m=t==="anchor"&&n==null?"center":n;return this.selectRenderer.render(e,t,m,i,d)}if(t==="spawnPoints"&&i.includes("logic.props"))return this.spawnPointsRenderer.render(e,t,n,i);if(t==="spawnTemplates"&&i.includes("logic.props"))return this.spawnTemplatesRenderer.render(e,t,n,i);if((t==="targetId"||t==="inputId"||t==="hitTemplateId"||t==="hpLabelId"||t==="hitPopupTemplateId")&&(n==null||typeof n=="string")){let m=this.getObjectIds(),h=this.selectRenderer.render(e,t,n!=null?n:"",i,["",...m]);return t==="hitTemplateId"&&i.includes("logic.props")?h+'<div class="inspector-text-sm" style="opacity:0.7; margin-top:4px;">Use template id (e.g. bullet_template), not spawner.</div>':h}if(i.includes("motion.")){if(t==="enabled")return this.booleanRenderer.render(e,t,!!n,i);if(t==="direction"&&(i.includes("continuousMove")||i.includes("continuousRotate")||i.includes("orbit"))){let h=["1","-1"],f=n==null?"1":String(n);return this.selectRenderer.render(e,t,f,i,h)}if(["speed","amplitude","intensity","minScale","maxScale","radius","lifetime","pivotOffsetX","pivotOffsetY","duration","delay","startScale","startAlpha","startYOffset","startXOffset"].includes(t)){let h=typeof n=="number"&&!Number.isNaN(n)?n:0;return this.numberRenderer.render(e,t,h,i)}}let u=this.getEnumOptionsFromSchemas(i);if(u)return this.selectRenderer.render(e,t,n,i,u);switch(this.typeDetector.detectType(t,n)){case"image":return this.imageRenderer.render(e,t,n,i);case"color":return this.colorRenderer.render(e,t,n,i);case"number":return this.numberRenderer.render(e,t,n,i);case"boolean":return this.booleanRenderer.render(e,t,n,i);case"array":return this.arrayRenderer.render(e,t,n,i);case"object":return this.objectRenderer.render(e,t,n,i);case"select":return this.selectRenderer.render(e,t,n,i,[]);default:return this.textRenderer.render(e,t,n,i)}}getTypeDetector(){return this.typeDetector}};function Ko(r,e){let t;return function(...i){let a=()=>{clearTimeout(t),r(...i)};clearTimeout(t),t=setTimeout(a,e)}}var Bn=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.motionSimpleMode=!0;this.expandMotionOnNextRender=!1;this.rendererRegistry=new Fn,this.updateManager=new Me,this.quickActions=new En;try{let e=localStorage.getItem("inspector:motionSimple");e!==null&&(this.motionSimpleMode=e==="true")}catch{}window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
|
|
986
1037
|
<div class="scene-panel inspector-panel panel-accent-violet" data-panel="inspector">
|
|
987
1038
|
<div class="scene-panel-header" data-panel-handle>
|
|
988
1039
|
<div class="panel-title">
|
|
@@ -1071,7 +1122,7 @@ ${h}
|
|
|
1071
1122
|
<button class="debug-btn debug-btn-sm ${this.motionSimpleMode?"primary":""}" data-motion-simple-toggle>
|
|
1072
1123
|
${this.motionSimpleMode?"Simple":"Advanced"}
|
|
1073
1124
|
</button>
|
|
1074
|
-
`,d='<button class="debug-btn debug-btn-sm success" data-motion-preview>Preview Intro</button>',u=h=>{let f=h.split(".").filter(Boolean),b=s;for(let
|
|
1125
|
+
`,d='<button class="debug-btn debug-btn-sm success" data-motion-preview>Preview Intro</button>',u=h=>{let f=h.split(".").filter(Boolean),b=s;for(let w of f)b=b==null?void 0:b[w];let y=f[f.length-1],v=`${n}.${h}`;return this.rendererRegistry.renderProperty(e,y,b,v)};if(this.motionSimpleMode){let h=u("enabled");h&&i.push(h);let f=[],b=u("intro.enabled"),y=u("intro.type"),v=u("intro.duration"),w=u("intro.easing");b&&f.push(b),y&&f.push(y),v&&f.push(v),w&&f.push(w),f.length&&i.push(`
|
|
1075
1126
|
<div class="inspector-subsection">
|
|
1076
1127
|
<div class="inspector-subsection-title">Intro</div>
|
|
1077
1128
|
<div class="inspector-subsection-content">
|
|
@@ -1080,15 +1131,15 @@ ${h}
|
|
|
1080
1131
|
${f.join("")}
|
|
1081
1132
|
</div>
|
|
1082
1133
|
</div>
|
|
1083
|
-
`);let
|
|
1134
|
+
`);let E=[u("pulse.enabled"),u("pulse.speed"),u("pulse.intensity")].filter(Boolean),j=[u("swing.enabled"),u("swing.amplitude"),u("swing.speed"),u("swing.axis")].filter(Boolean),z=[u("continuousMove.enabled"),u("continuousMove.axis"),u("continuousMove.speed"),u("continuousMove.direction"),u("continuousMove.lifetime")].filter(Boolean),S=[u("continuousRotate.enabled"),u("continuousRotate.speed"),u("continuousRotate.direction")].filter(Boolean),_=[u("orbit.enabled"),u("orbit.radius"),u("orbit.speed"),u("orbit.direction"),u("orbit.pivotOffsetX"),u("orbit.pivotOffsetY")].filter(Boolean);if(E.length||j.length||z.length||S.length||_.length){let T=(M,k)=>k.length?`
|
|
1084
1135
|
<div class="inspector-motion-continuous-group">
|
|
1085
|
-
<div class="inspector-subsection-title">${
|
|
1086
|
-
<div class="inspector-subsection-content">${
|
|
1087
|
-
</div>`:"",
|
|
1136
|
+
<div class="inspector-subsection-title">${M}</div>
|
|
1137
|
+
<div class="inspector-subsection-content">${k.join("")}</div>
|
|
1138
|
+
</div>`:"",C=[T("Pulse",E),T("Swing",j),T("Move forever",z),T("Rotate (pivoting itself)",S),T("Rotate around",_)].filter(Boolean).join("");i.push(`
|
|
1088
1139
|
<div class="inspector-subsection inspector-subsection-continuous">
|
|
1089
1140
|
<div class="inspector-subsection-title">Continuous</div>
|
|
1090
1141
|
<div class="inspector-subsection-content inspector-motion-continuous-groups">
|
|
1091
|
-
${
|
|
1142
|
+
${C}
|
|
1092
1143
|
</div>
|
|
1093
1144
|
</div>
|
|
1094
1145
|
`)}}else for(let h in s){let f=s[h],b=`${n}.${h}`,y=this.rendererRegistry.renderProperty(e,h,f,b);y&&i.push(y)}return i.length===0?"":`
|
|
@@ -1104,7 +1155,7 @@ ${h}
|
|
|
1104
1155
|
${i.join("")}
|
|
1105
1156
|
</div>
|
|
1106
1157
|
</div>
|
|
1107
|
-
`}attachEventListeners(){var S,C,k,z;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=Ko((w,x,M)=>{var A,E;this.updateManager.updateProperty(w,x,M),(E=(A=this.options)==null?void 0:A.onPropertyChange)==null||E.call(A,w,x,M)},300),n=w=>w?/(^|\.)logic(\.\d+)?\.id$/.test(w):!1;e.forEach(w=>{let x=A=>{var _,P;let E=A.target,I=E.dataset.propertyPath,L=E.dataset.objectId;if(I&&L){let R=E.value;if(E.type==="checkbox")R=E.checked;else if(E.type==="number"){if(R=parseFloat(E.value),isNaN(R))return}else if(E.dataset.json==="true")try{R=JSON.parse(E.value)}catch{return}E.type==="text"||E.type==="range"||E.tagName==="TEXTAREA"?t(L,I,R):(this.updateManager.updateProperty(L,I,R),(P=(_=this.options)==null?void 0:_.onPropertyChange)==null||P.call(_,L,I,R))}},M=w.dataset.propertyPath;n(M)?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",M),w.addEventListener("change",async A=>{var O;let E=A.target,I=E.dataset.propertyPath,L=E.dataset.objectId,_=E.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",_),!I||!L)return;await this.updateManager.updateProperty(L,I,_),console.log("[Inspector v1.0.0] Logic ID updated");let P=window,R=(O=P==null?void 0:P.__HANDLER_LOGIC_META)==null?void 0:O[_],T=this.getDefaultPropsForLogic(_,R);console.log("[Inspector v1.0.0] New logic default props:",T);let j=I.replace(/\.id$/,".props");await this.updateManager.updateProperty(L,j,T),console.log("[Inspector v1.0.0] Logic props updated to:",T),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(L)})):(w.addEventListener("change",x),(w.tagName==="INPUT"||w.tagName==="TEXTAREA")&&w.addEventListener("input",x))}),this.contentContainer.querySelectorAll("[data-action]").forEach(w=>{w.addEventListener("click",x=>{let M=x.target,A=M.dataset.action,E=M.dataset.path,I=M.dataset.object;A&&E&&I&&this.quickActions.handleAction(A,I,E)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(w=>{w.addEventListener("click",x=>{var E,I;let M=x.target,A=M.dataset.sectionToggle||((E=M.closest("[data-section-toggle]"))==null?void 0:E.getAttribute("data-section-toggle"));if(A){let L=(I=this.contentContainer)==null?void 0:I.querySelector(`[data-section="${A}"]`);L==null||L.classList.toggle("collapsed")}})}),this.contentContainer.querySelectorAll("[data-motion-preset]").forEach(w=>{w.addEventListener("click",async x=>{let A=x.currentTarget.dataset.motionPreset;!A||!this.selectedObjectId||await this.applyMotionPreset(this.selectedObjectId,A)})}),this.contentContainer.querySelectorAll("[data-motion-preview]").forEach(w=>{w.addEventListener("click",async()=>{this.selectedObjectId&&await this.previewMotionIntro(this.selectedObjectId)})});let l=this.contentContainer.querySelector("[data-motion-simple-toggle]");l==null||l.addEventListener("click",()=>{this.motionSimpleMode=!this.motionSimpleMode;try{localStorage.setItem("inspector:motionSimple",String(this.motionSimpleMode))}catch{}this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),this.contentContainer.querySelectorAll("[data-spawnpoints-add]").forEach(w=>{w.addEventListener("click",async x=>{let M=x.target,A=M.dataset.objectId,E=M.dataset.propertyPath;if(!A||!E)return;let I=window.getEditableObjectConfig,L=I==null?void 0:I(A);if(!L)return;let _=this.updateManager.getNestedProperty(L,E),P=Array.isArray(_)?[..._]:[];P.push({x:0,y:0}),await this.updateManager.updateProperty(A,E,P),this.loadObject(A)})}),this.contentContainer.querySelectorAll("[data-spawnpoints-remove]").forEach(w=>{w.addEventListener("click",async x=>{let M=x.target,A=M.dataset.objectId,E=M.dataset.propertyPath,I=Number(M.dataset.index||"-1");if(!A||!E||I<0)return;let L=window.getEditableObjectConfig,_=L==null?void 0:L(A);if(!_)return;let P=this.updateManager.getNestedProperty(_,E);if(!Array.isArray(P))return;let R=P.filter((T,j)=>j!==I);await this.updateManager.updateProperty(A,E,R),this.loadObject(A)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-add]").forEach(w=>{w.addEventListener("click",async x=>{let M=x.target,A=M.dataset.objectId,E=M.dataset.propertyPath;if(!A||!E)return;let I=window.getEditableObjectConfig,L=I==null?void 0:I(A);if(!L)return;let _=this.updateManager.getNestedProperty(L,E),P=Array.isArray(_)?[..._]:[];P.push({templateId:"",weight:1}),await this.updateManager.updateProperty(A,E,P),this.loadObject(A)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-remove]").forEach(w=>{w.addEventListener("click",async x=>{var T;let M=x.target,A=M.dataset.objectId,E=M.dataset.propertyPath,I=Number((T=M.dataset.index)!=null?T:-1);if(!A||!E||I<0)return;let L=window.getEditableObjectConfig,_=L==null?void 0:L(A);if(!_)return;let P=this.updateManager.getNestedProperty(_,E);if(!Array.isArray(P))return;let R=P.filter((j,O)=>O!==I);await this.updateManager.updateProperty(A,E,R),this.loadObject(A)})}),this.contentContainer.querySelectorAll("[data-logic-add]").forEach(w=>{w.addEventListener("click",async x=>{var H;let M=x.target,A=M.dataset.objectId,E=M.dataset.propertyPath;if(!A||!E)return;let I=window.getEditableObjectConfig,L=I==null?void 0:I(A);if(!L)return;let _=this.updateManager.getNestedProperty(L,E),P;Array.isArray(_)?P=[..._]:_!=null?typeof _=="string"?P=[{id:_,props:{}}]:typeof _=="object"?P=[_]:P=[]:P=[];let R=this.getDefaultLogicId(),T=window,j=(H=T==null?void 0:T.__HANDLER_LOGIC_META)==null?void 0:H[R],O=this.getDefaultPropsForLogic(R,j);P.push({id:R,props:O}),console.log("[InspectorPanel] Adding logic to array:",{objectId:A,path:E,current:_,next:P}),await this.updateManager.updateProperty(A,E,P),this.loadObject(A)})}),this.contentContainer.querySelectorAll("[data-logic-remove]").forEach(w=>{w.addEventListener("click",async x=>{var T;let M=x.target,A=M.dataset.objectId,E=M.dataset.propertyPath,I=Number((T=M.dataset.index)!=null?T:-1);if(!A||!E||I<0)return;let L=window.getEditableObjectConfig,_=L==null?void 0:L(A);if(!_)return;let P=this.updateManager.getNestedProperty(_,E);if(!Array.isArray(P))return;let R=P.filter((j,O)=>O!==I);await this.updateManager.updateProperty(A,E,R),this.loadObject(A)})}),this.contentContainer.querySelectorAll("[data-logic-convert]").forEach(w=>{w.addEventListener("click",async x=>{var F,W;let M=x.target,A=M.dataset.objectId,E=M.dataset.propertyPath,I=Number((F=M.dataset.index)!=null?F:-1);if(!A||!E||I<0)return;let L=window.getEditableObjectConfig,_=L==null?void 0:L(A);if(!_)return;let P=this.updateManager.getNestedProperty(_,E);if(!Array.isArray(P))return;let R=P[I];if(typeof R!="string")return;let T=window,j=(W=T==null?void 0:T.__HANDLER_LOGIC_META)==null?void 0:W[R],O=this.getDefaultPropsForLogic(R,j),H=[...P];H[I]={id:R,props:O},await this.updateManager.updateProperty(A,E,H),this.loadObject(A)})});let f=(S=this.root)==null?void 0:S.querySelector("[data-inspector-advanced]");f==null||f.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let b=(C=this.root)==null?void 0:C.querySelector("[data-convert-toggle]");b==null||b.addEventListener("click",()=>{var x;let w=(x=this.root)==null?void 0:x.querySelector("[data-convert-menu]");w==null||w.classList.toggle("hidden")});let y=(k=this.contentContainer)==null?void 0:k.querySelector("[data-inspector-add-component-btn]"),v=(z=this.contentContainer)==null?void 0:z.querySelector("[data-inspector-component-select]");y==null||y.addEventListener("click",async()=>{let w=v.value;w&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,w)})}getMotionDefaults(){var n,i,a,s;let e=window.__editableConfig,t=e==null?void 0:e.schemas;return t instanceof Map?(i=(n=t.get("motion"))==null?void 0:n.defaults)!=null?i:{enabled:!0}:t&&typeof t=="object"?(s=(a=t.motion)==null?void 0:a.defaults)!=null?s:{enabled:!0}:{enabled:!0}}async applyMotionPreset(e,t){var l,c;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i)return;let a=this.getMotionDefaults(),s={...(l=i.motion)!=null?l:a},o={...(c=s.intro)!=null?c:{}};s.enabled=!0,o.enabled=!0,o.type=t,o.duration=typeof o.duration=="number"&&o.duration>0?o.duration:500,o.delay=typeof o.delay=="number"?o.delay:0,o.easing=typeof o.easing=="string"?o.easing:"easeOut",s.intro=o,await this.updateManager.updateProperty(e,"motion",s),this.expandMotionOnNextRender=!0,this.loadObject(e)}async previewMotionIntro(e){var o,l;let t=window.getEditableObjectConfig,n=t==null?void 0:t(e);if(!n)return;let i=this.getMotionDefaults(),a={...(o=n.motion)!=null?o:i},s={...(l=a.intro)!=null?l:{}};a.enabled=!0,s.enabled=!0,a.intro=s,await this.updateManager.updateProperty(e,"motion",{...a,intro:{...s,enabled:!1}}),await this.updateManager.updateProperty(e,"motion",{...a,intro:{...s,enabled:!0}}),this.loadObject(e)}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};i[t]=c,await this.updateManager.updateProperty(e,t,c),this.loadObject(e),console.log("[InspectorPanel] Logic component added with default SwerveMove");return}t==="motion"&&(this.expandMotionOnNextRender=!0);let a=window.__editableConfig,s=a==null?void 0:a.schemas,o=null;s instanceof Map?o=s.get(t):s&&typeof s=="object"&&(o=s[t]),o||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(o==null?void 0:o.defaults)||{enabled:!0};i[t]={...l},await this.updateManager.updateProperty(e,t,i[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,n){var a,s;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((s=(a=n.render)==null?void 0:a.asset)==null?void 0:s.type)==="image")return!1;if(e==="interaction")return t.clickable===!0||t.draggable===!0;if(t.enabled===!0||t.active===!0||t.visible===!0)return!0;if(e==="ui")return!!(t.text||t.font||t.fontSize);let i=Object.keys(t);return i.length===0||i.length===1&&i[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
|
|
1158
|
+
`}attachEventListeners(){var w,E,j,z;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=Ko((S,_,R)=>{var T,C;this.updateManager.updateProperty(S,_,R),(C=(T=this.options)==null?void 0:T.onPropertyChange)==null||C.call(T,S,_,R)},300),n=S=>S?/(^|\.)logic(\.\d+)?\.id$/.test(S):!1;e.forEach(S=>{let _=T=>{var A,x;let C=T.target,M=C.dataset.propertyPath,k=C.dataset.objectId;if(M&&k){let I=C.value;if(C.type==="checkbox")I=C.checked;else if(C.type==="number"){if(I=parseFloat(C.value),isNaN(I))return}else if(C.dataset.json==="true")try{I=JSON.parse(C.value)}catch{return}C.type==="text"||C.type==="range"||C.tagName==="TEXTAREA"?t(k,M,I):(this.updateManager.updateProperty(k,M,I),(x=(A=this.options)==null?void 0:A.onPropertyChange)==null||x.call(A,k,M,I))}},R=S.dataset.propertyPath;n(R)?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",R),S.addEventListener("change",async T=>{var O;let C=T.target,M=C.dataset.propertyPath,k=C.dataset.objectId,A=C.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",A),!M||!k)return;await this.updateManager.updateProperty(k,M,A),console.log("[Inspector v1.0.0] Logic ID updated");let x=window,I=(O=x==null?void 0:x.__HANDLER_LOGIC_META)==null?void 0:O[A],L=this.getDefaultPropsForLogic(A,I);console.log("[Inspector v1.0.0] New logic default props:",L);let P=M.replace(/\.id$/,".props");await this.updateManager.updateProperty(k,P,L),console.log("[Inspector v1.0.0] Logic props updated to:",L),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(k)})):(S.addEventListener("change",_),(S.tagName==="INPUT"||S.tagName==="TEXTAREA")&&S.addEventListener("input",_))}),this.contentContainer.querySelectorAll("[data-action]").forEach(S=>{S.addEventListener("click",_=>{let R=_.target,T=R.dataset.action,C=R.dataset.path,M=R.dataset.object;T&&C&&M&&this.quickActions.handleAction(T,M,C)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(S=>{S.addEventListener("click",_=>{var C,M;let R=_.target,T=R.dataset.sectionToggle||((C=R.closest("[data-section-toggle]"))==null?void 0:C.getAttribute("data-section-toggle"));if(T){let k=(M=this.contentContainer)==null?void 0:M.querySelector(`[data-section="${T}"]`);k==null||k.classList.toggle("collapsed")}})}),this.contentContainer.querySelectorAll("[data-motion-preset]").forEach(S=>{S.addEventListener("click",async _=>{let T=_.currentTarget.dataset.motionPreset;!T||!this.selectedObjectId||await this.applyMotionPreset(this.selectedObjectId,T)})}),this.contentContainer.querySelectorAll("[data-motion-preview]").forEach(S=>{S.addEventListener("click",async()=>{this.selectedObjectId&&await this.previewMotionIntro(this.selectedObjectId)})});let l=this.contentContainer.querySelector("[data-motion-simple-toggle]");l==null||l.addEventListener("click",()=>{this.motionSimpleMode=!this.motionSimpleMode;try{localStorage.setItem("inspector:motionSimple",String(this.motionSimpleMode))}catch{}this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),this.contentContainer.querySelectorAll("[data-spawnpoints-add]").forEach(S=>{S.addEventListener("click",async _=>{let R=_.target,T=R.dataset.objectId,C=R.dataset.propertyPath;if(!T||!C)return;let M=window.getEditableObjectConfig,k=M==null?void 0:M(T);if(!k)return;let A=this.updateManager.getNestedProperty(k,C),x=Array.isArray(A)?[...A]:[];x.push({x:0,y:0}),await this.updateManager.updateProperty(T,C,x),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-spawnpoints-remove]").forEach(S=>{S.addEventListener("click",async _=>{let R=_.target,T=R.dataset.objectId,C=R.dataset.propertyPath,M=Number(R.dataset.index||"-1");if(!T||!C||M<0)return;let k=window.getEditableObjectConfig,A=k==null?void 0:k(T);if(!A)return;let x=this.updateManager.getNestedProperty(A,C);if(!Array.isArray(x))return;let I=x.filter((L,P)=>P!==M);await this.updateManager.updateProperty(T,C,I),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-add]").forEach(S=>{S.addEventListener("click",async _=>{let R=_.target,T=R.dataset.objectId,C=R.dataset.propertyPath;if(!T||!C)return;let M=window.getEditableObjectConfig,k=M==null?void 0:M(T);if(!k)return;let A=this.updateManager.getNestedProperty(k,C),x=Array.isArray(A)?[...A]:[];x.push({templateId:"",weight:1}),await this.updateManager.updateProperty(T,C,x),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-remove]").forEach(S=>{S.addEventListener("click",async _=>{var L;let R=_.target,T=R.dataset.objectId,C=R.dataset.propertyPath,M=Number((L=R.dataset.index)!=null?L:-1);if(!T||!C||M<0)return;let k=window.getEditableObjectConfig,A=k==null?void 0:k(T);if(!A)return;let x=this.updateManager.getNestedProperty(A,C);if(!Array.isArray(x))return;let I=x.filter((P,O)=>O!==M);await this.updateManager.updateProperty(T,C,I),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-logic-add]").forEach(S=>{S.addEventListener("click",async _=>{var H;let R=_.target,T=R.dataset.objectId,C=R.dataset.propertyPath;if(!T||!C)return;let M=window.getEditableObjectConfig,k=M==null?void 0:M(T);if(!k)return;let A=this.updateManager.getNestedProperty(k,C),x;Array.isArray(A)?x=[...A]:A!=null?typeof A=="string"?x=[{id:A,props:{}}]:typeof A=="object"?x=[A]:x=[]:x=[];let I=this.getDefaultLogicId(),L=window,P=(H=L==null?void 0:L.__HANDLER_LOGIC_META)==null?void 0:H[I],O=this.getDefaultPropsForLogic(I,P);x.push({id:I,props:O}),console.log("[InspectorPanel] Adding logic to array:",{objectId:T,path:C,current:A,next:x}),await this.updateManager.updateProperty(T,C,x),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-logic-remove]").forEach(S=>{S.addEventListener("click",async _=>{var L;let R=_.target,T=R.dataset.objectId,C=R.dataset.propertyPath,M=Number((L=R.dataset.index)!=null?L:-1);if(!T||!C||M<0)return;let k=window.getEditableObjectConfig,A=k==null?void 0:k(T);if(!A)return;let x=this.updateManager.getNestedProperty(A,C);if(!Array.isArray(x))return;let I=x.filter((P,O)=>O!==M);await this.updateManager.updateProperty(T,C,I),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-logic-convert]").forEach(S=>{S.addEventListener("click",async _=>{var N,G;let R=_.target,T=R.dataset.objectId,C=R.dataset.propertyPath,M=Number((N=R.dataset.index)!=null?N:-1);if(!T||!C||M<0)return;let k=window.getEditableObjectConfig,A=k==null?void 0:k(T);if(!A)return;let x=this.updateManager.getNestedProperty(A,C);if(!Array.isArray(x))return;let I=x[M];if(typeof I!="string")return;let L=window,P=(G=L==null?void 0:L.__HANDLER_LOGIC_META)==null?void 0:G[I],O=this.getDefaultPropsForLogic(I,P),H=[...x];H[M]={id:I,props:O},await this.updateManager.updateProperty(T,C,H),this.loadObject(T)})});let f=(w=this.root)==null?void 0:w.querySelector("[data-inspector-advanced]");f==null||f.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let b=(E=this.root)==null?void 0:E.querySelector("[data-convert-toggle]");b==null||b.addEventListener("click",()=>{var _;let S=(_=this.root)==null?void 0:_.querySelector("[data-convert-menu]");S==null||S.classList.toggle("hidden")});let y=(j=this.contentContainer)==null?void 0:j.querySelector("[data-inspector-add-component-btn]"),v=(z=this.contentContainer)==null?void 0:z.querySelector("[data-inspector-component-select]");y==null||y.addEventListener("click",async()=>{let S=v.value;S&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,S)})}getMotionDefaults(){var n,i,a,s;let e=window.__editableConfig,t=e==null?void 0:e.schemas;return t instanceof Map?(i=(n=t.get("motion"))==null?void 0:n.defaults)!=null?i:{enabled:!0}:t&&typeof t=="object"?(s=(a=t.motion)==null?void 0:a.defaults)!=null?s:{enabled:!0}:{enabled:!0}}async applyMotionPreset(e,t){var l,c;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i)return;let a=this.getMotionDefaults(),s={...(l=i.motion)!=null?l:a},o={...(c=s.intro)!=null?c:{}};s.enabled=!0,o.enabled=!0,o.type=t,o.duration=typeof o.duration=="number"&&o.duration>0?o.duration:500,o.delay=typeof o.delay=="number"?o.delay:0,o.easing=typeof o.easing=="string"?o.easing:"easeOut",s.intro=o,await this.updateManager.updateProperty(e,"motion",s),this.expandMotionOnNextRender=!0,this.loadObject(e)}async previewMotionIntro(e){var o,l;let t=window.getEditableObjectConfig,n=t==null?void 0:t(e);if(!n)return;let i=this.getMotionDefaults(),a={...(o=n.motion)!=null?o:i},s={...(l=a.intro)!=null?l:{}};a.enabled=!0,s.enabled=!0,a.intro=s,await this.updateManager.updateProperty(e,"motion",{...a,intro:{...s,enabled:!1}}),await this.updateManager.updateProperty(e,"motion",{...a,intro:{...s,enabled:!0}}),this.loadObject(e)}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};i[t]=c,await this.updateManager.updateProperty(e,t,c),this.loadObject(e),console.log("[InspectorPanel] Logic component added with default SwerveMove");return}t==="motion"&&(this.expandMotionOnNextRender=!0);let a=window.__editableConfig,s=a==null?void 0:a.schemas,o=null;s instanceof Map?o=s.get(t):s&&typeof s=="object"&&(o=s[t]),o||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(o==null?void 0:o.defaults)||{enabled:!0};i[t]={...l},await this.updateManager.updateProperty(e,t,i[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,n){var a,s;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((s=(a=n.render)==null?void 0:a.asset)==null?void 0:s.type)==="image")return!1;if(e==="interaction")return t.clickable===!0||t.draggable===!0;if(t.enabled===!0||t.active===!0||t.visible===!0)return!0;if(e==="ui")return!!(t.text||t.font||t.fontSize);let i=Object.keys(t);return i.length===0||i.length===1&&i[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
|
|
1108
1159
|
<div class="inspector-empty">
|
|
1109
1160
|
<span class="inspector-empty-icon">\u26A0\uFE0F</span>
|
|
1110
1161
|
<span class="inspector-empty-text">${e}</span>
|
|
@@ -1114,7 +1165,7 @@ ${h}
|
|
|
1114
1165
|
<span class="inspector-empty-icon">\u{1F3AF}</span>
|
|
1115
1166
|
<span class="inspector-empty-text">Select an object to inspect</span>
|
|
1116
1167
|
</div>
|
|
1117
|
-
`)}};var ts=
|
|
1168
|
+
`)}};var ts=Ze(require("jszip"),1);function Ki(r){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(r)})}function Br(r){var i;let[e,t]=r.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(i=n==null?void 0:n[1])!=null?i:"image/png"}}async function Ur(r){return await new Promise(e=>{let t=new Image;t.onload=()=>e({width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}),t.onerror=()=>e(null),t.src=r})}async function Un(r){var e,t;try{console.log("[ImageUtils] Fetching image data from URL:",r);let n=await fetch(r);if(!n.ok)return console.warn("[ImageUtils] Fetch failed with status:",n.status,r),null;let i=await n.blob();console.log("[ImageUtils] Blob received, size:",i.size,"type:",i.type);let a=await Ki(i),s=await Ur(a),o=Br(a);return console.log("[ImageUtils] Success resolution:",s==null?void 0:s.width,"x",s==null?void 0:s.height,"mime:",o.mimeType),{base64:o.base64,mimeType:o.mimeType,dataUrl:a,width:(e=s==null?void 0:s.width)!=null?e:0,height:(t=s==null?void 0:s.height)!=null?t:0}}catch(n){return console.error("[ImageUtils] Error fetching image data:",n),null}}async function _e(r){var e,t;try{let n=await Ki(r),i=await Ur(n),a=Br(n);return{base64:a.base64,mimeType:a.mimeType,dataUrl:n,width:(e=i==null?void 0:i.width)!=null?e:0,height:(t=i==null?void 0:i.height)!=null?t:0}}catch{return null}}function Xi(r){return Ki(r).then(e=>e).catch(()=>null)}function Ji(r,e){var t;try{let[n,i]=r.split(","),a=n.match(/data:(.*?);base64/),s=(t=a==null?void 0:a[1])!=null?t:"image/png",o=atob(i),l=new Uint8Array(o.length);for(let c=0;c<o.length;c++)l[c]=o.charCodeAt(c);return new File([l],e,{type:s})}catch{return null}}async function at(r,e=30){try{console.log("[ImageUtils] Removing background color...");let t=await new Promise((d,u)=>{let g=new Image;g.onload=()=>d(g),g.onerror=()=>u(new Error("Failed to load image")),g.src=r}),n=document.createElement("canvas");n.width=t.width,n.height=t.height;let i=n.getContext("2d");if(!i)return console.error("[ImageUtils] Failed to get canvas context"),r;i.drawImage(t,0,0);let a=i.getImageData(0,0,n.width,n.height),s=a.data,l=[{name:"top-left",offset:0},{name:"top-right",offset:(n.width-1)*4},{name:"bottom-left",offset:(n.height-1)*n.width*4},{name:"bottom-right",offset:((n.height-1)*n.width+(n.width-1))*4}].map(d=>({r:s[d.offset],g:s[d.offset+1],b:s[d.offset+2]})),c=0;for(let d=0;d<s.length;d+=4){let u=s[d],g=s[d+1],m=s[d+2],h=!1;for(let f of l)if(Math.sqrt(Math.pow(u-f.r,2)+Math.pow(g-f.g,2)+Math.pow(m-f.b,2))<e){h=!0;break}h&&(s[d+3]=0,c++)}return console.log(`[ImageUtils] Removed background from ${c} pixels (4-corner sampling, tolerance: ${e})`),i.putImageData(a,0,0),n.toDataURL("image/png")}catch(t){return console.error("[ImageUtils] Error removing background:",t),r}}function Gr(r,e){if(!r||!e)return"1:1";let t=r/e;return t>1.3?"16:9":t<.77?"9:16":"1:1"}function Ee(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Y(r){return typeof r=="string"?r:void 0}function qr(r){return r.toLowerCase().endsWith(".png")?r.slice(0,-4):r}function Xo(r){var n,i,a;let e=(n=Y(r.id))!=null?n:Y(r.name);if(e)return e;let t=(i=Y(r.file))!=null?i:Y(r.asset);return t?qr((a=t.split("/").pop())!=null?a:t):void 0}function Jo(r,e,t){var n,i,a;if(typeof e=="string")return{id:r,file:e,role:t};if(Ee(e)){let s=(n=Y(e.file))!=null?n:Y(e.asset);return s?{id:(i=Y(e.id))!=null?i:r,file:s,role:(a=Y(e.role))!=null?a:t,dataUrl:Y(e.dataUrl),layout:e.layout}:null}return null}function Zi(r,e){var t,n,i;if(!r)return[];if(Array.isArray(r)){let a=[];for(let s of r){if(typeof s=="string"){let o=qr((t=s.split("/").pop())!=null?t:s);a.push({id:o,file:s,role:e});continue}if(Ee(s)){let o=Xo(s),l=(n=Y(s.file))!=null?n:Y(s.asset);if(!o||!l)continue;a.push({id:o,file:l,role:(i=Y(s.role))!=null?i:e,dataUrl:Y(s.dataUrl),layout:s.layout})}}return a}if(Ee(r)){let a=[];for(let[s,o]of Object.entries(r)){let l=Jo(s,o,e);l&&a.push(l)}return a}return[]}function Zo(r){var e,t;return(t=(e=Y(r.brand_name))!=null?e:Y(r.brandName))!=null?t:Y(r.name)}function Qo(r){if(Ee(r.brand_dna)&&Ee(r.brand_dna.colors))return r.brand_dna;if(Ee(r.colors)){let e={colors:r.colors};return typeof r.style=="string"&&(e.style=r.style),Ee(r.fonts)&&(e.fonts=r.fonts),e}}function el(r){var t;let e=new Map;for(let n of r){let i=e.get(n.id);if(!i){e.set(n.id,n);continue}e.set(n.id,{...i,...n,file:n.file||i.file,role:n.role||i.role,dataUrl:n.dataUrl||i.dataUrl,layout:(t=n.layout)!=null?t:i.layout})}return Array.from(e.values())}function Qi(r,e={}){var s,o,l;let t=r.filter(Ee),n=(o=(s=t.map(Zo).find(Boolean))!=null?s:e.defaultBrandName)!=null?o:"Imported Brand",i=(l=t.map(Qo).find(Boolean))!=null?l:{colors:{}},a=[];for(let c of t)"layers"in c&&a.push(...Zi(c.layers,"visual element")),"assets"in c&&a.push(...Zi(c.assets,"visual element")),Ee(c.endgame)&&"assets"in c.endgame&&a.push(...Zi(c.endgame.assets,"endgame"));return{version:"1.0",brand_name:n,brand_dna:i,assets:el(a)}}var Vr=require("@google/genai");async function Gn(r,e,t=[],n={}){var i,a,s,o,l,c,p;try{if(!(r!=null&&r.trim()))throw new Error("Gemini API key is required");if(!(e!=null&&e.trim()))throw new Error("Prompt is required");for(let b=0;b<t.length;b++){let y=t[b];if(!y.base64||!y.mimeType)throw new Error(`Image ${b+1} is missing required data`);if(y.base64.length<1e3&&console.warn(`Image ${b+1} data appears very small, may be corrupted`),!y.mimeType.startsWith("image/"))throw new Error(`Image ${b+1} has invalid MIME type: ${y.mimeType}`)}let d=new Vr.GoogleGenAI({apiKey:r}),u="gemini-2.5-flash",g=[e];t.length>0&&t.forEach((b,y)=>{g.push({inlineData:{data:b.base64,mimeType:b.mimeType}}),console.log(`[Gemini] Added image ${y+1}: ${b.mimeType}, size: ${Math.round(b.base64.length/1024)}KB`)}),console.log(`[Gemini] Making request with ${t.length} images and prompt length: ${e.length}`);let m=await d.models.generateContent({model:u,contents:g}),h="",f=(s=(a=(i=m.candidates)==null?void 0:i[0])==null?void 0:a.content)==null?void 0:s.parts;if(f)for(let b of f)b.text&&(h+=b.text);if(!h.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${h.length}`),h}catch(d){throw console.error("[Gemini] API error:",d),(o=d.message)!=null&&o.includes("Unable to process input image")?new Error("Unable to process the uploaded image. Please ensure it's a valid PNG, JPG, or JPEG file under 10MB and not corrupted."):(l=d.message)!=null&&l.includes("API_KEY_INVALID")?new Error("Invalid Gemini API key. Please check your API key configuration."):(c=d.message)!=null&&c.includes("QUOTA_EXCEEDED")?new Error("Gemini API quota exceeded. Please try again later or check your billing."):(p=d.message)!=null&&p.includes("SAFETY")?new Error("Content was flagged by Gemini safety filters. Please try with different images."):d}}var Wr=require("@google/genai");async function rt(r,e,t=[],n={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let i=new Wr.GoogleGenAI({apiKey:r}),a=[{text:e}];t.length>0&&t.forEach((o,l)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${l}`),a.push({inlineData:{mimeType:o.mimeType,data:o.base64}})}),console.info("[GEMINI-REAL-SDK] Calling generateContent with model: gemini-2.5-flash-image");let s=await i.models.generateContent({model:"gemini-2.5-flash-image",contents:a});if(console.info("[GEMINI-REAL-SDK] Received response from model"),!s.candidates||!s.candidates[0]||!s.candidates[0].content||!s.candidates[0].content.parts)throw new Error("Gemini 2.5 Flash Image returned invalid response structure.");for(let o of s.candidates[0].content.parts)if(o.text)console.log(o.text);else if(o.inlineData){let l=o.inlineData.data,c=o.inlineData.mimeType||"image/png";return console.info("[GEMINI-REAL-SDK] Found inline image data in response"),`data:${c};base64,${l}`}throw new Error("Gemini 2.5 Flash Image returned no image data.")}catch(i){throw console.error("[GEMINI-REAL-SDK] Error in generateImageWithGemini25Flash:",JSON.stringify(i,Object.getOwnPropertyNames(i),2)),i}}function Yr(r){let e=r.brandAssets.map(a=>{let s=`- ${a.id}: ${a.role}`;return a.layout&&(s+=` [pos: ${a.layout.x.toFixed(0)},${a.layout.y.toFixed(0)}, size: ${a.layout.w.toFixed(0)}x${a.layout.h.toFixed(0)}, z: ${a.layout.z}, opacity: ${a.layout.opacity}]`),s}).join(`
|
|
1118
1169
|
`)||"None",t=r.brandDna?`Colors: ${JSON.stringify(r.brandDna.colors)}, Style: ${r.brandDna.style||"not specified"}`:"Not provided",n=r.gameObjects.map(a=>typeof a=="string"?`- id: ${a}`:`- id: ${a.id}${a.category?`, category: ${a.category}`:""}${a.type?`, type: ${a.type}`:""}`).join(`
|
|
1119
1170
|
`),i="";if(r.brandConfig){let a=r.brandConfig,s=[];a.splash&&s.push(`SPLASH: title="${a.splash.title||""}", subtitle="${a.splash.subtitle||""}", button="${a.splash.button_label||""}"`),a.endgame&&s.push(`ENDGAME: title="${a.endgame.title||""}", subtitle="${a.endgame.subtitle||""}", cta="${a.endgame.cta_label||""}"`),a.tutorial&&s.push(`TUTORIAL: text="${a.tutorial.label_text||""}", helper="${a.tutorial.helper_text||""}"`),s.length>0&&(i=`
|
|
1120
1171
|
BRAND CONTENT:
|
|
@@ -1199,7 +1250,7 @@ OUTPUT CONSTRAINTS (MUST FOLLOW):
|
|
|
1199
1250
|
|
|
1200
1251
|
OUTPUT:
|
|
1201
1252
|
Generate the requested asset matching the brand style.${r.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
|
|
1202
|
-
`.trim()}function Xr(r){return r.map(e=>{if(typeof e=="string"){let t=e,n,i;return t.includes("background")?(n="background",i="background"):t.includes("button")||t.includes("cta")?(n="ui",i="button"):t.includes("logo")?(n="ui",i="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(n="text",i="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(n="effects",i="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(n="ui",i="image"):(n="environment",i="interactive"),{id:t,category:n,type:i}}return e})}function Jr(r,e){return!(r.includes("background")&&(r.includes("_1")||r.includes("splash")||r.includes("endgame")||r.includes("main"))||e==="text"||e==="effects"&&r.includes("particle"))}async function Zr(r){var s,o;let e=Xr(r.gameObjects),t={gamePrompt:r.gamePrompt,gameObjects:e,brandAssets:r.manifest.assets,brandDna:r.manifest.brand_dna,brandName:r.manifest.brand_name},n=Yr(t),i=[];if(r.flatDesignDataUrl)try{let l=Qr(r.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(i.push(l),console.log("[Pipeline] Added flat design to analysis, size:",l.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(l){console.warn("[Pipeline] Error processing flat design:",l)}console.log("[Pipeline] Running analysis chain with",i.length,"images...");let a;try{a=await
|
|
1253
|
+
`.trim()}function Xr(r){return r.map(e=>{if(typeof e=="string"){let t=e,n,i;return t.includes("background")?(n="background",i="background"):t.includes("button")||t.includes("cta")?(n="ui",i="button"):t.includes("logo")?(n="ui",i="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(n="text",i="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(n="effects",i="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(n="ui",i="image"):(n="environment",i="interactive"),{id:t,category:n,type:i}}return e})}function Jr(r,e){return!(r.includes("background")&&(r.includes("_1")||r.includes("splash")||r.includes("endgame")||r.includes("main"))||e==="text"||e==="effects"&&r.includes("particle"))}async function Zr(r){var s,o;let e=Xr(r.gameObjects),t={gamePrompt:r.gamePrompt,gameObjects:e,brandAssets:r.manifest.assets,brandDna:r.manifest.brand_dna,brandName:r.manifest.brand_name},n=Yr(t),i=[];if(r.flatDesignDataUrl)try{let l=Qr(r.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(i.push(l),console.log("[Pipeline] Added flat design to analysis, size:",l.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(l){console.warn("[Pipeline] Error processing flat design:",l)}console.log("[Pipeline] Running analysis chain with",i.length,"images...");let a;try{a=await Gn(r.apiKey,n,i,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(s=l.message)!=null&&s.includes("Unable to process input image")?new Error("Gemini API unable to process the uploaded images. Please try with different images or ensure they are valid PNG/JPG files under 10MB."):(o=l.message)!=null&&o.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):l}return tl(a,r.gameObjects)}function tl(r,e){try{let t=r,n=r.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)t=n[1].trim();else{let a=r.match(/\{[\s\S]*\}/);a&&(t=a[0])}let i=JSON.parse(t);return i.mappings&&Array.isArray(i.mappings)?{mappingResult:i,rawResponse:r,parsed:!0}:{mappingResult:{mappings:e.map(a=>({game_object:a,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:r,parsed:!1,parseError:"Missing mappings[] array"}}catch(t){return{mappingResult:{mappings:e.map(n=>({game_object:n,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:r,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function ea(r,e,t={}){var i;let n=e.mappings.filter(a=>a.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let a=0;a<n.length;a++){let s=n[a];(i=t.onProgress)==null||i.call(t,a+1,n.length,s.game_object);try{let o=await nl(r,s);s.output_dataUrl=o,s.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${s.game_object}:`,o),s.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function nl(r,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&r.manifest){let o=r.manifest.assets.find(l=>l.id===e.reference_asset);if(o){let l=r.assetFiles.get(o.file);if(l){let c=await _e(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(r.flatDesignDataUrl){let o=Qr(r.flatDesignDataUrl);o&&t.push(o)}let n=Jr(e.game_object),i={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:r.manifest.brand_dna,needsTransparency:n},a=Kr(i);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${n})`);let s=await rt(r.apiKey,a,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await at(s)||s}function Qr(r){let[e,t]=r.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return t&&n?{base64:t,mimeType:n[1]}:null}async function es(r,e){let t=r.assets,n=[];Array.isArray(t)?n=t:t&&typeof t=="object"?n=Object.entries(t).map(([i,a])=>({id:i,file:String(a),role:"visual element"})):n=[],r.assets=n;for(let i of n){let a=e.get(i.file);if(a){let s=await _e(a);s&&(i.dataUrl=s.dataUrl)}}}var qn=class{constructor(){this.root=null;this.currentTab="upload";this.uploadMethod="individual";this.uploadedJsons=new Map;this.normalizedManifest=null;this.flatDesignDataUrl=null;this.assetFiles=new Map;this.zipFile=null;this.mappingResult=null;this.analysisRawResponse=null;this.analysisParsedOk=null;this.analysisParseError=null;this.isAnalyzing=!1;this.isGenerating=!1}get manifest(){return this.normalizedManifest}render(){return`
|
|
1203
1254
|
<div class="scene-panel brand-vision-panel panel-accent-violet" data-panel="brand-vision">
|
|
1204
1255
|
<div class="scene-panel-header" data-panel-handle>
|
|
1205
1256
|
<div class="panel-title">
|
|
@@ -1315,15 +1366,15 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1315
1366
|
</div>
|
|
1316
1367
|
<div class="panel-resize-handle" data-panel-resize></div>
|
|
1317
1368
|
</div>
|
|
1318
|
-
`}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,n,i,a,s,o,l,c,p,d,u,g,m;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let h="/dashboard";window.location.pathname!==h&&(window.location.href=h)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(h=>{h.addEventListener("click",()=>{let f=h.dataset.visionTab;this.switchTab(f)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",h=>{let f=h.target.value;this.switchUploadMethod(f)}),(i=this.root.querySelector("[data-vision-upload-manifest]"))==null||i.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-manifest-input]"))==null||f.click()}),(a=this.root.querySelector("[data-vision-upload-zip]"))==null||a.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-zip-input]"))==null||f.click()}),(s=this.root.querySelector("[data-vision-zip-input]"))==null||s.addEventListener("change",h=>{this.handleZipUpload(h)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",h=>{this.handleManifestUpload(h)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-assets-input]"))==null||f.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",h=>{this.handleAssetsUpload(h)}),(p=this.root.querySelector("[data-vision-upload-flat]"))==null||p.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-flat-input]"))==null||f.click()}),(d=this.root.querySelector("[data-vision-flat-input]"))==null||d.addEventListener("change",h=>{this.handleFlatDesignUpload(h)}),(u=this.root.querySelector("[data-vision-analyze]"))==null||u.addEventListener("click",()=>{this.runAnalysis()}),(g=this.root.querySelector("[data-vision-generate-all]"))==null||g.addEventListener("click",()=>{this.generateAllMissing()}),(m=this.root.querySelector("[data-vision-apply-all]"))==null||m.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",h=>{let f=h.target;if(!f)return;let b=f.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;y&&(f.closest("[data-mapping-apply-one]")&&this.applyOne(y),f.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(y),f.closest("[data-mapping-edit-one]")&&this.openEditorForOne(y),f.closest("[data-mapping-generate-one]")&&this.generateOne(y),f.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),e==null||e.addEventListener("change",h=>{let f=h.target;if(!f||!this.mappingResult)return;let b=f.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(
|
|
1369
|
+
`}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,n,i,a,s,o,l,c,p,d,u,g,m;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let h="/dashboard";window.location.pathname!==h&&(window.location.href=h)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(h=>{h.addEventListener("click",()=>{let f=h.dataset.visionTab;this.switchTab(f)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",h=>{let f=h.target.value;this.switchUploadMethod(f)}),(i=this.root.querySelector("[data-vision-upload-manifest]"))==null||i.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-manifest-input]"))==null||f.click()}),(a=this.root.querySelector("[data-vision-upload-zip]"))==null||a.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-zip-input]"))==null||f.click()}),(s=this.root.querySelector("[data-vision-zip-input]"))==null||s.addEventListener("change",h=>{this.handleZipUpload(h)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",h=>{this.handleManifestUpload(h)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-assets-input]"))==null||f.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",h=>{this.handleAssetsUpload(h)}),(p=this.root.querySelector("[data-vision-upload-flat]"))==null||p.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-flat-input]"))==null||f.click()}),(d=this.root.querySelector("[data-vision-flat-input]"))==null||d.addEventListener("change",h=>{this.handleFlatDesignUpload(h)}),(u=this.root.querySelector("[data-vision-analyze]"))==null||u.addEventListener("click",()=>{this.runAnalysis()}),(g=this.root.querySelector("[data-vision-generate-all]"))==null||g.addEventListener("click",()=>{this.generateAllMissing()}),(m=this.root.querySelector("[data-vision-apply-all]"))==null||m.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",h=>{let f=h.target;if(!f)return;let b=f.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;y&&(f.closest("[data-mapping-apply-one]")&&this.applyOne(y),f.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(y),f.closest("[data-mapping-edit-one]")&&this.openEditorForOne(y),f.closest("[data-mapping-generate-one]")&&this.generateOne(y),f.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),e==null||e.addEventListener("change",h=>{let f=h.target;if(!f||!this.mappingResult)return;let b=f.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(w=>w.game_object===y);v&&(f.matches("[data-mapping-action]")&&(v.action=String(f.value||"KEEP"),v.status="Edited",this.renderMappings()),f.matches("[data-mapping-brand-asset]")&&(v.brand_asset=String(f.value||""),v.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",h=>{let f=h.target;if(!f||!this.mappingResult||!f.matches("[data-mapping-prompt]"))return;let b=f.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(w=>w.game_object===y);v&&(v.generation_prompt=String(f.value||""),v.status="Edited")})}switchTab(e){var t,n;this.root&&(this.currentTab=e,this.root.querySelectorAll("[data-vision-tab]").forEach(i=>i.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(i=>i.classList.remove("active")),(t=this.root.querySelector(`[data-vision-tab="${e}"]`))==null||t.classList.add("active"),(n=this.root.querySelector(`[data-vision-content="${e}"]`))==null||n.classList.add("active"))}switchUploadMethod(e){var t;this.root&&(this.uploadMethod=e,this.root.querySelectorAll("[data-vision-upload-section]").forEach(n=>{n.classList.remove("active")}),(t=this.root.querySelector(`[data-vision-upload-section="${e}"]`))==null||t.classList.add("active"))}async handleZipUpload(e){var i;let n=(i=e.target.files)==null?void 0:i[0];if(n){this.zipFile=n,this.setStatus("zip",`Selected: ${n.name} (${(n.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(n)}catch(a){console.error("[BrandVision] ZIP processing failed:",a),this.setStatus("zip",`Error: ${a instanceof Error?a.message:"Unknown error"}`)}}}async processZipFile(e){var s,o;let t=await ts.loadAsync(e),n=[],i=[];t.forEach((l,c)=>{let p=l.toLowerCase();p.endsWith(".json")?n.push({name:l,content:null}):p.startsWith("assets/")&&p.endsWith(".png")&&i.push({name:l,file:c})});for(let l of n)try{let c=await((s=t.file(l.name))==null?void 0:s.async("text"));c&&(l.content=JSON.parse(c))}catch(c){console.warn(`Failed to parse ${l.name}:`,c)}let a=new Map;for(let l of i)try{let c=await l.file.async("uint8array"),p=new Blob([c],{type:"image/png"}),d=l.name.split("/").pop()||l.name;console.log(`Processing ${d}, uint8array length: ${c.length}, blob size: ${p.size}`);let u;try{u=await this.blobToDataUrl(p)}catch(f){console.warn(`FileReader failed for ${d}, using fallback:`,f),u=`data:image/png;base64,${btoa(String.fromCharCode.apply(null,Array.from(c)))}`}if(console.log(`Data URL length: ${u.length}, starts with: ${u.substring(0,50)}...`),!u.startsWith("data:image/png;base64,")){console.warn(`Invalid data URL format for ${d}:`,u.substring(0,100));continue}let g=this.inferAssetCategory(d.replace(".png",""));console.log(`Saving ${d} to category: ${g}`);let h=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:g,filename:d,data:u,overwrite:!0})})).json();if(console.log(`Save result for ${d}:`,h),h.success){console.log(`\u2705 Saved PNG to library: ${d} (${g}) at ${h.path}`);let f=new File([p],d,{type:"image/png"});a.set(d,f)}else console.warn(`\u274C Failed to save ${d}:`,h.error)}catch(c){console.warn(`Failed to extract ${l.name}:`,c)}this.uploadedJsons.clear(),n.forEach(({name:l,content:c})=>{c&&this.uploadedJsons.set(l,c)}),this.assetFiles=a;try{this.normalizedManifest=Qi(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let l=[];for(let[p,d]of a){let u=await this.fileToDataUrl(d);l.push({id:p.replace(".png",""),filename:p,dataUrl:u,category:this.inferAssetCategory(p.replace(".png",""))})}this.normalizedManifest&&(this.normalizedManifest.assets=l);let c=l.length;this.setStatus("zip",`\u2705 Processed: ${n.length} JSONs, ${c} PNGs
|
|
1319
1370
|
\u{1F3F7}\uFE0F Brand: ${((o=this.normalizedManifest)==null?void 0:o.brand_name)||"Imported Brand"}`),this.addAssetsToRegistry(l),this.refreshLibrary()}catch(l){console.error("[BrandVision] Failed to normalize ZIP manifest:",l),this.normalizedManifest=null,this.setStatus("zip","\u274C Failed to normalize manifest")}}async fileToDataUrl(e){return new Promise((t,n)=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=n,i.readAsDataURL(e)})}async blobToDataUrl(e){return new Promise((t,n)=>{let i=new FileReader;i.onload=()=>{let a=i.result;console.log("FileReader result type:",typeof a,"length:",a.length),console.log("Data URL prefix:",a.substring(0,30)),t(a)},i.onerror=a=>{console.error("FileReader error:",a),n(a)},i.readAsDataURL(e)})}inferAssetCategory(e){let t=e.toLowerCase();return t.includes("background")||t.includes("bg")?"backgrounds":t.includes("ui")||t.includes("button")||t.includes("cta")||t.includes("logo")||t.includes("text")?"ui":t.includes("sparkle")||t.includes("effect")||t.includes("particle")?"effects":t.includes("bottle")||t.includes("product")||t.includes("item")?"products":"misc"}addAssetsToRegistry(e){let t=window.getEditableAssets;if(typeof t!="function")return;let n=t();if(!(n!=null&&n.libraryAssets))return;let i={};for(let a of e){let s=a.category||"misc";i[s]||(i[s]=[]),n.libraryAssets[s]||(n.libraryAssets[s]=[]),n.libraryAssets[s].some(l=>l.filename===a.filename)||(n.libraryAssets[s].unshift({filename:a.filename,displayName:a.id.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase())}),console.log(`[BrandVision] Added ${a.filename} to registry category ${s}`))}}refreshLibrary(){let e=window.refreshAssetLibrary;typeof e=="function"&&e();let t=window.reRenderAssetLibrary;typeof t=="function"&&t()}async handleManifestUpload(e){var a;let t=e.target,n=t.files;if(!n||n.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let i="";for(let s of Array.from(n))try{let o=await s.text(),l=JSON.parse(o);this.uploadedJsons.set(s.name,l),l.layers?i+=`\u2705 Layers: ${s.name}
|
|
1320
1371
|
`:l.brand_dna||l.colors?i+=`\u2705 Brand: ${s.name}
|
|
1321
1372
|
`:i+=`\u2705 Loaded: ${s.name}
|
|
1322
1373
|
`}catch{i+=`\u274C Error in ${s.name}
|
|
1323
|
-
`}try{this.normalizedManifest=
|
|
1374
|
+
`}try{this.normalizedManifest=Qi(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let s=Array.isArray((a=this.normalizedManifest)==null?void 0:a.assets)?this.normalizedManifest.assets.length:0;i+=`
|
|
1324
1375
|
\u{1F4E6} Normalized manifest: ${s} assets`,i+=`
|
|
1325
1376
|
\u{1F3F7}\uFE0F Brand: ${this.normalizedManifest.brand_name||"Imported Brand"}`,console.info("[BrandVision] Normalized manifest",{jsonFiles:Array.from(this.uploadedJsons.keys()),assetsType:typeof this.normalizedManifest.assets,assetsCount:s,brandName:this.normalizedManifest.brand_name})}catch(s){console.error("[BrandVision] Failed to normalize manifest:",s),this.normalizedManifest=null,i+=`
|
|
1326
|
-
\u274C Failed to normalize manifest`}t.value="",this.setStatus("manifest",i.trim())}async handleAssetsUpload(e){let n=e.target.files;if(!(!n||n.length===0)){for(let i of Array.from(n))this.assetFiles.set(i.name,i);this.setStatus("assets",`${this.assetFiles.size} files loaded`)}}async handleFlatDesignUpload(e){var a,s;let n=(a=e.target.files)==null?void 0:a[0];if(!n)return;let i=await
|
|
1377
|
+
\u274C Failed to normalize manifest`}t.value="",this.setStatus("manifest",i.trim())}async handleAssetsUpload(e){let n=e.target.files;if(!(!n||n.length===0)){for(let i of Array.from(n))this.assetFiles.set(i.name,i);this.setStatus("assets",`${this.assetFiles.size} files loaded`)}}async handleFlatDesignUpload(e){var a,s;let n=(a=e.target.files)==null?void 0:a[0];if(!n)return;let i=await _e(n);if(i){this.flatDesignDataUrl=i.dataUrl,this.setStatus("flat",n.name);let o=(s=this.root)==null?void 0:s.querySelector("[data-vision-flat-preview]");o&&(o.innerHTML=`<img src="${i.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var n,i,a,s,o,l,c;if(this.isAnalyzing)return;let e=(a=(i=(n=this.root)==null?void 0:n.querySelector("[data-vision-api-key]"))==null?void 0:i.value)==null?void 0:a.trim();if(!e){this.setStatus("upload","Missing API key");return}let t=this.manifest;if(!t){this.setStatus("upload","Upload manifest first");return}Array.isArray(t.assets)||console.warn("[BrandVision] Manifest assets not array at analysis time; continuing with normalization fallback.",{assets:t.assets}),this.isAnalyzing=!0,this.setStatus("upload","Analyzing...");try{await es(t,this.assetFiles);let p={apiKey:e,manifest:t,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},d=await Zr(p);this.mappingResult=d.mappingResult,this.analysisRawResponse=d.rawResponse,this.analysisParsedOk=d.parsed,this.analysisParseError=(s=d.parseError)!=null?s:null,this.renderMappings(),d.parsed?(this.setStatus("upload","Analysis complete"),this.setStatus("mapping",`${(c=(l=(o=this.mappingResult)==null?void 0:o.mappings)==null?void 0:l.length)!=null?c:0} objects mapped`)):(this.setStatus("upload","Analysis response was not JSON"),this.setStatus("mapping",`Parse failed: ${d.parseError||"Unknown error"}`)),this.switchTab("mapping")}catch(p){console.error("[BrandVision] Analysis failed:",p),this.setStatus("upload","Analysis failed")}finally{this.isAnalyzing=!1}}async generateAllMissing(){var t,n,i;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let e=(i=(n=(t=this.root)==null?void 0:t.querySelector("[data-vision-api-key]"))==null?void 0:n.value)==null?void 0:i.trim();if(!e){this.setStatus("apply","Missing API key");return}this.isGenerating=!0;try{let a={apiKey:e,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await ea(a,this.mappingResult,{onProgress:(s,o,l)=>{this.setStatus("apply",`Generating ${s}/${o}: ${l}`),this.renderMappings()}}),this.setStatus("apply","Generation complete"),this.renderMappings()}catch(a){console.error("[BrandVision] Generation failed:",a),this.setStatus("apply","Generation failed")}finally{this.isGenerating=!1}}renderMappings(){var o;let e=(o=this.root)==null?void 0:o.querySelector("[data-vision-mappings]");if(!e||!this.mappingResult)return;let t=this.manifest,n=this.getEngineAssets(),i=!!this.analysisRawResponse&&this.analysisParsedOk===!1,a=((t==null?void 0:t.assets)||[]).map(l=>`<option value="${l.id}">${l.id}</option>`).join(""),s=i?`
|
|
1327
1378
|
<div class="vision-raw-block">
|
|
1328
1379
|
<div class="inspector-text-sm" style="white-space: pre-wrap;">
|
|
1329
1380
|
\u26A0\uFE0F AI response was not valid JSON (${this.analysisParseError||"unknown error"}).
|
|
@@ -1385,8 +1436,8 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1385
1436
|
</div>
|
|
1386
1437
|
</div>
|
|
1387
1438
|
`}).join("")}
|
|
1388
|
-
`}async applyAll(){let e=await this.stageOverridesFromMappings({saveToLibrary:!1});this.setStatus("apply",e>0?`Staged ${e} asset overrides`:"No assets to stage")}getEngineAssets(){let e=window.getEditableEngineConfig;if(typeof e!="function")return{};let t=e();return t!=null&&t.assets&&typeof t.assets=="object"?t.assets:{}}getPreviewValueForMapping(e){if(!this.mappingResult||!this.manifest)return{value:null,source:"none"};let t=this.mappingResult.mappings.find(n=>n.game_object===e);if(!t)return{value:null,source:"none"};if(t.action==="GENERATE"&&t.output_dataUrl)return{value:t.output_dataUrl,source:"generated"};if(t.action==="APPLY"&&t.brand_asset){let n=this.manifest.assets.find(i=>i.id===t.brand_asset);if(n!=null&&n.dataUrl)return{value:n.dataUrl,source:"brand"}}return{value:null,source:"none"}}async stageOverridesFromMappings(e){if(!this.mappingResult)return 0;let t=0;for(let n of this.mappingResult.mappings){if(n.action==="KEEP"||n.action==="APPLY"&&!n.brand_asset||n.action==="GENERATE"&&!n.output_dataUrl)continue;let i=n.game_object,a=this.getPreviewValueForMapping(i);if(!a.value)continue;let s=e.saveToLibrary?await this.saveToLibraryAndReturnPath(i,a.value):a.value;s&&(await this.stageEngineAssetOverride(i,s),n.status=e.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",t++)}return this.renderMappings(),t}async applyOne(e){var i;let t=this.getPreviewValueForMapping(e);if(!t.value){this.setStatus("apply",`No output to apply for ${e}`);return}await this.stageEngineAssetOverride(e,t.value);let n=(i=this.mappingResult)==null?void 0:i.mappings.find(a=>a.game_object===e);n&&(n.status="Staged \u2713"),this.renderMappings(),this.setStatus("apply",`Staged override for ${e}`)}async saveAndApplyOne(e){var a;let t=this.getPreviewValueForMapping(e);if(!t.value){this.setStatus("apply",`No output to save for ${e}`);return}let n=await this.saveToLibraryAndReturnPath(e,t.value);if(!n){this.setStatus("apply",`Save failed for ${e}`);return}await this.stageEngineAssetOverride(e,n);let i=(a=this.mappingResult)==null?void 0:a.mappings.find(s=>s.game_object===e);i&&(i.status="Saved + staged \u2713"),this.renderMappings(),this.setStatus("apply",`Saved + staged ${e}`)}openEditorForOne(e){if(!this.mappingResult)return;let t=this.mappingResult.mappings.find(s=>s.game_object===e);if(!t)return;let n=this.getPreviewValueForMapping(e),i=window.__openAiEditor;if(typeof i!="function"){this.setStatus("apply","AI editor not available");return}let a=t.action==="GENERATE"?t.generation_prompt:void 0;i(e,a,n.value||void 0,{path:`assets.${e}`})}async generateOne(e){var i,a,s;if(!this.mappingResult||this.isGenerating)return;let t=this.mappingResult.mappings.find(o=>o.game_object===e);if(!t)return;if(t.action="GENERATE",!t.generation_prompt){t.status="Missing prompt",this.renderMappings();return}let n=(s=(a=(i=this.root)==null?void 0:i.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:s.trim();if(!n||!this.manifest){this.setStatus("apply","Missing API key or manifest");return}this.isGenerating=!0,t.status="Generating\u2026",this.renderMappings();try{let o={apiKey:n,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await
|
|
1389
|
-
`)}var il=["background_color","text_color","cta_background","cta_text","warning_text_color","endgame_title_color","endgame_subtitle_color","endgame_cta_text_color","endgame_cta_hint_color","endgame_footer_color"],al=["cta_hint","cta_label_end"],is=[{key:"warning_text",objectId:"label.warning",property:"ui.text"},{key:"endgame_title",objectId:"ui.endgame.title",property:"ui.text"},{key:"endgame_subtitle",objectId:"ui.endgame.subtitle",property:"ui.text"},{key:"endgame_cta_text",objectId:"ui.endgame.cta",property:"ui.text"},{key:"endgame_cta_hint_text",objectId:"ui.endgame.cta.hint",property:"ui.text"},{key:"endgame_footer_text",objectId:"ui.endgame.footer",property:"ui.text"}],rl=["brand.primary","brand.heading","brand.body","brand.warning"],
|
|
1439
|
+
`}async applyAll(){let e=await this.stageOverridesFromMappings({saveToLibrary:!1});this.setStatus("apply",e>0?`Staged ${e} asset overrides`:"No assets to stage")}getEngineAssets(){let e=window.getEditableEngineConfig;if(typeof e!="function")return{};let t=e();return t!=null&&t.assets&&typeof t.assets=="object"?t.assets:{}}getPreviewValueForMapping(e){if(!this.mappingResult||!this.manifest)return{value:null,source:"none"};let t=this.mappingResult.mappings.find(n=>n.game_object===e);if(!t)return{value:null,source:"none"};if(t.action==="GENERATE"&&t.output_dataUrl)return{value:t.output_dataUrl,source:"generated"};if(t.action==="APPLY"&&t.brand_asset){let n=this.manifest.assets.find(i=>i.id===t.brand_asset);if(n!=null&&n.dataUrl)return{value:n.dataUrl,source:"brand"}}return{value:null,source:"none"}}async stageOverridesFromMappings(e){if(!this.mappingResult)return 0;let t=0;for(let n of this.mappingResult.mappings){if(n.action==="KEEP"||n.action==="APPLY"&&!n.brand_asset||n.action==="GENERATE"&&!n.output_dataUrl)continue;let i=n.game_object,a=this.getPreviewValueForMapping(i);if(!a.value)continue;let s=e.saveToLibrary?await this.saveToLibraryAndReturnPath(i,a.value):a.value;s&&(await this.stageEngineAssetOverride(i,s),n.status=e.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",t++)}return this.renderMappings(),t}async applyOne(e){var i;let t=this.getPreviewValueForMapping(e);if(!t.value){this.setStatus("apply",`No output to apply for ${e}`);return}await this.stageEngineAssetOverride(e,t.value);let n=(i=this.mappingResult)==null?void 0:i.mappings.find(a=>a.game_object===e);n&&(n.status="Staged \u2713"),this.renderMappings(),this.setStatus("apply",`Staged override for ${e}`)}async saveAndApplyOne(e){var a;let t=this.getPreviewValueForMapping(e);if(!t.value){this.setStatus("apply",`No output to save for ${e}`);return}let n=await this.saveToLibraryAndReturnPath(e,t.value);if(!n){this.setStatus("apply",`Save failed for ${e}`);return}await this.stageEngineAssetOverride(e,n);let i=(a=this.mappingResult)==null?void 0:a.mappings.find(s=>s.game_object===e);i&&(i.status="Saved + staged \u2713"),this.renderMappings(),this.setStatus("apply",`Saved + staged ${e}`)}openEditorForOne(e){if(!this.mappingResult)return;let t=this.mappingResult.mappings.find(s=>s.game_object===e);if(!t)return;let n=this.getPreviewValueForMapping(e),i=window.__openAiEditor;if(typeof i!="function"){this.setStatus("apply","AI editor not available");return}let a=t.action==="GENERATE"?t.generation_prompt:void 0;i(e,a,n.value||void 0,{path:`assets.${e}`})}async generateOne(e){var i,a,s;if(!this.mappingResult||this.isGenerating)return;let t=this.mappingResult.mappings.find(o=>o.game_object===e);if(!t)return;if(t.action="GENERATE",!t.generation_prompt){t.status="Missing prompt",this.renderMappings();return}let n=(s=(a=(i=this.root)==null?void 0:i.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:s.trim();if(!n||!this.manifest){this.setStatus("apply","Missing API key or manifest");return}this.isGenerating=!0,t.status="Generating\u2026",this.renderMappings();try{let o={apiKey:n,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await ea(o,{mappings:[t]}),t.status=t.output_dataUrl?"Generated \u2713":t.status||"Done"}catch(o){console.error("[BrandVision] generateOne failed:",o),t.status="Failed \u2717"}finally{this.isGenerating=!1,this.renderMappings()}}async stageEngineAssetOverride(e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(J(),Be));n({path:`assets.${e}`,value:t},{silent:!0});let i=window.applyEditableEngineConfig;typeof i=="function"&&i({assets:{[e]:t}})}async saveToLibraryAndReturnPath(e,t){if(!/^(data:|blob:)/.test(t))return t;let n=this.inferCategoryFromAssetKey(e),i=`${e.replace(/[^a-zA-Z0-9_-]/g,"_")}_vision_${Date.now()}.png`;try{let s=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:n,filename:i,data:t,overwrite:!0})})).json();if(!(s!=null&&s.success)||!(s!=null&&s.path))return console.error("[BrandVision] Save to library failed:",(s==null?void 0:s.error)||s),null;let o=window.addAssetToRegistry;typeof o=="function"&&o(n,i);let l=window.refreshAssetLibrary;return typeof l=="function"&&l(),String(s.path)}catch(a){return console.error("[BrandVision] Save to library error:",a),null}}inferCategoryFromAssetKey(e){let t=window.getEditableAssets;if(typeof t=="function"){let i=t();if(i!=null&&i.slots&&Array.isArray(i.slots)){let s=i.slots.find(o=>o.slotId===e||o.currentAsset===e);if(s!=null&&s.category)return String(s.category)}let a=i==null?void 0:i.categories;if(Array.isArray(a)&&a.length>0){let s=e.toLowerCase(),o=l=>a.find(c=>c.toLowerCase().includes(l));return s.includes("bg")||s.includes("background")?o("background")||a[0]:(s.includes("cta")||s.includes("button")||s.includes("ui")||s.includes("logo"))&&o("ui")||a[0]}}let n=e.toLowerCase();return n.includes("bg")||n.includes("background")?"backgrounds":n.includes("cta")||n.includes("button")||n.includes("ui")||n.includes("logo")?"ui":"misc"}async copyRawAnalysis(){if(this.analysisRawResponse)try{await navigator.clipboard.writeText(this.analysisRawResponse),this.setStatus("mapping","Copied raw analysis to clipboard")}catch{this.setStatus("mapping","Clipboard not available")}}setStatus(e,t){var a;let n={manifest:"[data-vision-manifest-status]",assets:"[data-vision-assets-status]",flat:"[data-vision-flat-status]",zip:"[data-vision-zip-status]",upload:"[data-vision-upload-status]",mapping:"[data-vision-mapping-status]",apply:"[data-vision-apply-status]"},i=(a=this.root)==null?void 0:a.querySelector(n[e]);i&&(i.textContent=t)}getGameObjects(){let e=window.getEditableObjectList;return typeof e=="function"?e():[]}async getGamePrompt(){try{let e=await fetch("./configs/engine/game.prompt.json");if(e.ok)return(await e.json()).game_prompt||""}catch{}return""}setupResizeHandle(){if(!this.root)return;let e=this.root.querySelector("[data-panel-resize]");e&&e.addEventListener("pointerdown",t=>{let n=t.clientX,i=this.root.getBoundingClientRect().width,a=o=>{let l=Math.max(300,i+(o.clientX-n));this.root.style.width=`${l}px`},s=()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",s)};window.addEventListener("pointermove",a),window.addEventListener("pointerup",s)})}refresh(){}};function ns(r,e={}){let{includeReference:t=!1,includeMagenta:n=!0,changeLevel:i=5}=e;return[`TASK: ${r}`,`CHANGE_STRENGTH: ${i}/10`,t?"REFERENCE: provided":"REFERENCE: none",n?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
|
|
1440
|
+
`)}var il=["background_color","text_color","cta_background","cta_text","warning_text_color","endgame_title_color","endgame_subtitle_color","endgame_cta_text_color","endgame_cta_hint_color","endgame_footer_color"],al=["cta_hint","cta_label_end"],is=[{key:"warning_text",objectId:"label.warning",property:"ui.text"},{key:"endgame_title",objectId:"ui.endgame.title",property:"ui.text"},{key:"endgame_subtitle",objectId:"ui.endgame.subtitle",property:"ui.text"},{key:"endgame_cta_text",objectId:"ui.endgame.cta",property:"ui.text"},{key:"endgame_cta_hint_text",objectId:"ui.endgame.cta.hint",property:"ui.text"},{key:"endgame_footer_text",objectId:"ui.endgame.footer",property:"ui.text"}],rl=["brand.primary","brand.heading","brand.body","brand.warning"],Vn=class{constructor(){this.root=null;this.assetsContainer=null;this.colorsContainer=null;this.fontsContainer=null;this.textsContainer=null;this.audioContainer=null;this.options=null;this.previewModal=null;this.autoApplyTimer=null;this.activePreviewKey=null;this.activePreviewValue=null;this.activePreviewFileInput=null;this.retryTimer=null;this.aiModal=null;this.aiTargetKey=null;this.aiKeyInput=null;this.aiPromptInput=null;this.aiStrengthInput=null;this.aiStrengthValue=null;this.aiModelSelect=null;this.aiModalSubtitle=null;this.aiGalleryToggle=null;this.aiGalleryEl=null;this.aiGalleryGrid=null;this.aiReferenceInput=null;this.aiReferenceName=null;this.aiReferenceFile=null;this.aiRemoveBgToggle=null;this.aiUseOutputToggle=null;this.aiGenerateBtn=null;this.aiApplyBtn=null;this.aiSaveLibraryBtn=null;this.aiCropBtn=null;this.aiDownloadBtn=null;this.aiPreviewImg=null;this.aiStatusEl=null;this.aiOutputDataUrl=null;this.aiBaseDataUrl=null;this.aiBaseValue=null;this.aiOutputKey=null;this.aiContext=null;this.aiBgToleranceInput=null;this.aiBgToleranceValue=null;this.aiRawOutputDataUrl=null;this.aiLoadingEl=null}render(){return`
|
|
1390
1441
|
<div class="scene-panel customize-panel panel-accent-blue" data-panel="customize-settings">
|
|
1391
1442
|
<div class="scene-panel-header" data-panel-handle>
|
|
1392
1443
|
<div class="panel-title">
|
|
@@ -1454,7 +1505,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1454
1505
|
<path d="M12 3l4 4h-3v6h-2V7H8l4-4z" />
|
|
1455
1506
|
<path d="M5 14v4h14v-4h2v6H3v-6h2z" />
|
|
1456
1507
|
</svg>
|
|
1457
|
-
`;let d=document.createElement("input");d.type="file",d.accept="image/*,audio/*,application/json",d.className="customize-file",d.addEventListener("change",()=>{var m;let g=(m=d.files)==null?void 0:m[0];g&&this.handleAssetUpload(g,o,n)}),p.addEventListener("click",()=>d.click()),l.appendChild(c),l.appendChild(p),l.appendChild(d),a.appendChild(s),a.appendChild(o),a.appendChild(l),(u=this.assetsContainer)==null||u.appendChild(a)})}renderColors(e){this.colorsContainer&&(this.colorsContainer.innerHTML="",il.forEach(t=>{var l,c,p;let n=(l=e==null?void 0:e[t])!=null?l:"#ffffff";if(t.includes("_text_color")||t.includes("_color")){let u={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[t];u&&(n=(c=this.getObjectPropertyValue(u.objectId,u.property))!=null?c:"#ffffff")}let i=document.createElement("label");i.className="customize-color-field";let a=document.createElement("span");a.textContent=t.replace(/_/g," ");let s=document.createElement("input");s.type="color",s.value=n,s.dataset.colorKey=t;let o=document.createElement("input");o.type="text",o.value=n,o.className="customize-color-text",o.dataset.colorTextKey=t,s.addEventListener("input",()=>{o.value=s.value}),o.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(o.value)&&(s.value=o.value)}),i.appendChild(a),i.appendChild(s),i.appendChild(o),(p=this.colorsContainer)==null||p.appendChild(i)}))}renderFonts(e){this.fontsContainer&&(this.fontsContainer.innerHTML="",rl.forEach(t=>{var s,o;let n=document.createElement("div");n.className="customize-row";let i=document.createElement("span");i.className="customize-key",i.textContent=t;let a=document.createElement("input");a.type="text",a.value=(s=e==null?void 0:e[t])!=null?s:t,a.className="customize-input",a.dataset.fontKey=t,n.appendChild(i),n.appendChild(a),(o=this.fontsContainer)==null||o.appendChild(n)}))}renderTexts(e){this.textsContainer&&(this.textsContainer.innerHTML="",al.forEach(t=>{var s,o;let n=document.createElement("div");n.className="customize-row";let i=document.createElement("span");i.className="customize-key",i.textContent=t;let a=document.createElement("input");a.type="text",a.value=(s=this.readUiValue(e,t))!=null?s:"",a.className="customize-input",a.dataset.textKey=t,n.appendChild(i),n.appendChild(a),(o=this.textsContainer)==null||o.appendChild(n)}),is.forEach(({key:t,objectId:n})=>{var o,l;let i=document.createElement("div");i.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=t;let s=document.createElement("input");s.type="text",s.value=(o=this.getObjectTextValue(n))!=null?o:"",s.className="customize-input",s.dataset.objectTextKey=t,i.appendChild(a),i.appendChild(s),(l=this.textsContainer)==null||l.appendChild(i)}))}renderAudio(e){if(!this.audioContainer)return;this.audioContainer.innerHTML="",["background_file","background_volume","click_file","click_volume","success_file","success_volume","complete_file","complete_volume"].forEach(n=>{var o,l;let i=document.createElement("div");i.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=n.replace("_"," ");let s=document.createElement("input");s.type=n.includes("volume")?"number":"text",s.min="0",s.max="1",s.step="0.1",s.value=String((o=e==null?void 0:e[n])!=null?o:""),s.className="customize-input",s.dataset.audioKey=n,n.includes("file")&&(s.placeholder="audio file path"),i.appendChild(a),i.appendChild(s),(l=this.audioContainer)==null||l.appendChild(i)})}readUiValue(e,t){if(t.includes(".")){let i=t.split("."),a=e;for(let s of i){if(a==null)return null;a=a[s]}return typeof a=="string"?a:null}let n=e==null?void 0:e[t];return typeof n=="string"?n:null}getObjectTextValue(e){var i,a;let t=window.getEditableObjectConfig;if(typeof t!="function")return null;let n=t(e);return(a=(i=n==null?void 0:n.ui)==null?void 0:i.text)!=null?a:null}getObjectPropertyValue(e,t){let n=window.getEditableObjectConfig;if(typeof n!="function")return null;let i=n(e);if(!i)return null;let a=t.split("."),s=i;for(let o of a){if(s==null)return null;s=s[o]}return typeof s=="string"?s:null}handleApply(){this.handleApplyWithSource("manual")}handleApplyWithSource(e){if(console.log(`[CustomizePanel] handleApplyWithSource called with source: ${e}`),!this.root||!this.options)return;let t={};this.root.querySelectorAll("[data-asset-key]").forEach(o=>{let l=o;l.dataset.assetKey&&(t[l.dataset.assetKey]=l.value)}),console.log("[CustomizePanel] Assets being applied:",Object.keys(t).length,"total"),console.log("[CustomizePanel] Asset values:",t);let n={};this.root.querySelectorAll("[data-color-text-key]").forEach(o=>{let l=o,c=l.dataset.colorTextKey;c&&(c.includes("_text_color")||c.includes("_color")?this.applyTextColorToObject(c,l.value):n[c]=l.value)});let i={};this.root.querySelectorAll("[data-font-key]").forEach(o=>{let l=o,c=l.dataset.fontKey;c&&(i[c]=l.value)});let a={};this.root.querySelectorAll("[data-text-key]").forEach(o=>{let l=o,c=l.dataset.textKey;c&&(a[c]=l.value)});let s={};this.root.querySelectorAll("[data-audio-key]").forEach(o=>{let l=o,c=l.dataset.audioKey;if(c)if(c.includes("volume")){let p=parseFloat(l.value);s[c]=isNaN(p)?0:p}else s[c]=l.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(o=>{let l=o,c=l.dataset.objectTextKey;if(!c)return;let p=is.find(d=>d.key===c);p&&this.applyObjectPropertyValue(p.objectId,p.property,l.value)}),console.log("[CustomizePanel] Calling onApply callback to restart game with source:",e),this.options.onApply({assets:t,runtime:{theme:n,ui:a,fonts:i,audio:s}},{source:e})}setupAiPanel(){}setAiStatus(e){this.aiStatusEl&&(this.aiStatusEl.textContent=e)}getSelectedAssetKey(){return this.aiTargetKey}getSelectedAssetInput(){let e=this.getSelectedAssetKey();return!this.root||!e?null:this.root.querySelector(`input[data-asset-key="${e}"]`)}async getImageDataFromAsset(e){let t=this.resolveAssetUrls(e);console.log("[CustomizePanel] Resolving asset urls for AI:",e,t);for(let n of t)try{let i=await
|
|
1508
|
+
`;let d=document.createElement("input");d.type="file",d.accept="image/*,audio/*,application/json",d.className="customize-file",d.addEventListener("change",()=>{var m;let g=(m=d.files)==null?void 0:m[0];g&&this.handleAssetUpload(g,o,n)}),p.addEventListener("click",()=>d.click()),l.appendChild(c),l.appendChild(p),l.appendChild(d),a.appendChild(s),a.appendChild(o),a.appendChild(l),(u=this.assetsContainer)==null||u.appendChild(a)})}renderColors(e){this.colorsContainer&&(this.colorsContainer.innerHTML="",il.forEach(t=>{var l,c,p;let n=(l=e==null?void 0:e[t])!=null?l:"#ffffff";if(t.includes("_text_color")||t.includes("_color")){let u={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[t];u&&(n=(c=this.getObjectPropertyValue(u.objectId,u.property))!=null?c:"#ffffff")}let i=document.createElement("label");i.className="customize-color-field";let a=document.createElement("span");a.textContent=t.replace(/_/g," ");let s=document.createElement("input");s.type="color",s.value=n,s.dataset.colorKey=t;let o=document.createElement("input");o.type="text",o.value=n,o.className="customize-color-text",o.dataset.colorTextKey=t,s.addEventListener("input",()=>{o.value=s.value}),o.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(o.value)&&(s.value=o.value)}),i.appendChild(a),i.appendChild(s),i.appendChild(o),(p=this.colorsContainer)==null||p.appendChild(i)}))}renderFonts(e){this.fontsContainer&&(this.fontsContainer.innerHTML="",rl.forEach(t=>{var s,o;let n=document.createElement("div");n.className="customize-row";let i=document.createElement("span");i.className="customize-key",i.textContent=t;let a=document.createElement("input");a.type="text",a.value=(s=e==null?void 0:e[t])!=null?s:t,a.className="customize-input",a.dataset.fontKey=t,n.appendChild(i),n.appendChild(a),(o=this.fontsContainer)==null||o.appendChild(n)}))}renderTexts(e){this.textsContainer&&(this.textsContainer.innerHTML="",al.forEach(t=>{var s,o;let n=document.createElement("div");n.className="customize-row";let i=document.createElement("span");i.className="customize-key",i.textContent=t;let a=document.createElement("input");a.type="text",a.value=(s=this.readUiValue(e,t))!=null?s:"",a.className="customize-input",a.dataset.textKey=t,n.appendChild(i),n.appendChild(a),(o=this.textsContainer)==null||o.appendChild(n)}),is.forEach(({key:t,objectId:n})=>{var o,l;let i=document.createElement("div");i.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=t;let s=document.createElement("input");s.type="text",s.value=(o=this.getObjectTextValue(n))!=null?o:"",s.className="customize-input",s.dataset.objectTextKey=t,i.appendChild(a),i.appendChild(s),(l=this.textsContainer)==null||l.appendChild(i)}))}renderAudio(e){if(!this.audioContainer)return;this.audioContainer.innerHTML="",["background_file","background_volume","click_file","click_volume","success_file","success_volume","complete_file","complete_volume"].forEach(n=>{var o,l;let i=document.createElement("div");i.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=n.replace("_"," ");let s=document.createElement("input");s.type=n.includes("volume")?"number":"text",s.min="0",s.max="1",s.step="0.1",s.value=String((o=e==null?void 0:e[n])!=null?o:""),s.className="customize-input",s.dataset.audioKey=n,n.includes("file")&&(s.placeholder="audio file path"),i.appendChild(a),i.appendChild(s),(l=this.audioContainer)==null||l.appendChild(i)})}readUiValue(e,t){if(t.includes(".")){let i=t.split("."),a=e;for(let s of i){if(a==null)return null;a=a[s]}return typeof a=="string"?a:null}let n=e==null?void 0:e[t];return typeof n=="string"?n:null}getObjectTextValue(e){var i,a;let t=window.getEditableObjectConfig;if(typeof t!="function")return null;let n=t(e);return(a=(i=n==null?void 0:n.ui)==null?void 0:i.text)!=null?a:null}getObjectPropertyValue(e,t){let n=window.getEditableObjectConfig;if(typeof n!="function")return null;let i=n(e);if(!i)return null;let a=t.split("."),s=i;for(let o of a){if(s==null)return null;s=s[o]}return typeof s=="string"?s:null}handleApply(){this.handleApplyWithSource("manual")}handleApplyWithSource(e){if(console.log(`[CustomizePanel] handleApplyWithSource called with source: ${e}`),!this.root||!this.options)return;let t={};this.root.querySelectorAll("[data-asset-key]").forEach(o=>{let l=o;l.dataset.assetKey&&(t[l.dataset.assetKey]=l.value)}),console.log("[CustomizePanel] Assets being applied:",Object.keys(t).length,"total"),console.log("[CustomizePanel] Asset values:",t);let n={};this.root.querySelectorAll("[data-color-text-key]").forEach(o=>{let l=o,c=l.dataset.colorTextKey;c&&(c.includes("_text_color")||c.includes("_color")?this.applyTextColorToObject(c,l.value):n[c]=l.value)});let i={};this.root.querySelectorAll("[data-font-key]").forEach(o=>{let l=o,c=l.dataset.fontKey;c&&(i[c]=l.value)});let a={};this.root.querySelectorAll("[data-text-key]").forEach(o=>{let l=o,c=l.dataset.textKey;c&&(a[c]=l.value)});let s={};this.root.querySelectorAll("[data-audio-key]").forEach(o=>{let l=o,c=l.dataset.audioKey;if(c)if(c.includes("volume")){let p=parseFloat(l.value);s[c]=isNaN(p)?0:p}else s[c]=l.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(o=>{let l=o,c=l.dataset.objectTextKey;if(!c)return;let p=is.find(d=>d.key===c);p&&this.applyObjectPropertyValue(p.objectId,p.property,l.value)}),console.log("[CustomizePanel] Calling onApply callback to restart game with source:",e),this.options.onApply({assets:t,runtime:{theme:n,ui:a,fonts:i,audio:s}},{source:e})}setupAiPanel(){}setAiStatus(e){this.aiStatusEl&&(this.aiStatusEl.textContent=e)}getSelectedAssetKey(){return this.aiTargetKey}getSelectedAssetInput(){let e=this.getSelectedAssetKey();return!this.root||!e?null:this.root.querySelector(`input[data-asset-key="${e}"]`)}async getImageDataFromAsset(e){let t=this.resolveAssetUrls(e);console.log("[CustomizePanel] Resolving asset urls for AI:",e,t);for(let n of t)try{let i=await Un(n);if(i)return console.log("[CustomizePanel] Successfully fetched image data for AI"),{input:{base64:i.base64,mimeType:i.mimeType},dataUrl:i.dataUrl,width:i.width,height:i.height}}catch(i){console.warn("[CustomizePanel] Failed to fetch image data from:",n,i)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(e){var i,a,s;let t=(e==null?void 0:e.trim())||"";if(!t){let o=this.getSelectedAssetInput();t=(a=(i=o==null?void 0:o.value)==null?void 0:i.trim())!=null?a:""}if(console.log("[CustomizePanel] updateAiBasePreview using value:",t),!t){this.aiBaseDataUrl=null,this.updateAiPreview();return}let n=await this.getImageDataFromAsset(t);this.aiBaseDataUrl=(s=n==null?void 0:n.dataUrl)!=null?s:null,this.updateAiPreview()}updateAiPreview(){if(!this.aiPreviewImg)return;let e=this.aiOutputDataUrl||this.aiBaseDataUrl||"";if(!e){this.aiPreviewImg.removeAttribute("src");return}this.aiPreviewImg.src=e}updateAiModalPreview(e,t){if(!e)return;let n=t!=null?t:this.activePreviewKey;if(!n||!this.aiOutputDataUrl||this.aiOutputKey!==n){e.classList.add("hidden");return}let i=e.querySelector(".asset-preview-ai-image");i&&(i.src=this.aiOutputDataUrl),e.classList.remove("hidden")}setAiLoading(e){this.aiLoadingEl&&this.aiLoadingEl.classList.toggle("active",e),this.aiGenerateBtn&&(this.aiGenerateBtn.disabled=e)}toggleAiGallery(){if(!this.aiGalleryEl||!this.aiGalleryToggle)return;let e=this.aiGalleryEl.classList.toggle("hidden");this.aiGalleryToggle.textContent=e?"Gallery":"Hide Gallery",e||this.renderAiGallery()}renderAiGallery(){if(!this.aiGalleryGrid)return;let e=this.getAiGalleryEntries();if(!e.length){this.aiGalleryGrid.innerHTML='<div class="ai-gallery-empty">No image assets found.</div>';return}this.aiGalleryGrid.innerHTML="",e.forEach(({key:t,value:n})=>{var l;let i=document.createElement("button");i.type="button",i.className="ai-gallery-item",t===this.aiTargetKey&&i.classList.add("active");let a=document.createElement("img");a.className="ai-gallery-thumb",a.alt=t;let s=this.resolveAssetUrls(n);s[0]&&(a.src=s[0]);let o=document.createElement("span");o.className="ai-gallery-label",o.textContent=t,i.appendChild(a),i.appendChild(o),i.addEventListener("click",()=>this.selectAiGalleryAsset(t)),(l=this.aiGalleryGrid)==null||l.appendChild(i)})}getAiGalleryEntries(){if(!this.root)return[];let e=[];return this.root.querySelectorAll("[data-asset-key]").forEach(t=>{var s,o;let n=t,i=n.dataset.assetKey,a=(o=(s=n.value)==null?void 0:s.trim())!=null?o:"";!i||!a||this.isAiGalleryImage(a)&&e.push({key:i,value:a})}),e}isAiGalleryImage(e){let t=e.trim();if(!t)return!1;if(/^(data:image|blob:)/.test(t))return!0;let n=t.split("?")[0].toLowerCase();return![".mp3",".wav",".ogg",".json"].some(i=>n.endsWith(i))}selectAiGalleryAsset(e){this.aiTargetKey!==e&&(this.aiTargetKey=e,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null,this.aiReferenceInput&&(this.aiReferenceInput.value=""),this.aiReferenceName&&(this.aiReferenceName.textContent="Optional"),this.aiModalSubtitle&&(this.aiModalSubtitle.textContent=e),this.setAiOutputButtonsEnabled(!1),this.updateAiBasePreview(),this.updateAiPreview(),this.renderAiGallery())}openAiModal(e,t,n){var o,l,c,p,d,u,g,m,h,f;this.closeAiModal(),this.aiTargetKey=e,this.aiBaseValue=t||null,this.aiContext=n||null,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null;let i=document.createElement("div");i.className="ai-modal",i.innerHTML=`
|
|
1458
1509
|
<div class="ai-modal-card">
|
|
1459
1510
|
<div class="ai-modal-header">
|
|
1460
1511
|
<div>
|
|
@@ -1525,7 +1576,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1525
1576
|
</div>
|
|
1526
1577
|
</div>
|
|
1527
1578
|
</div>
|
|
1528
|
-
`;let a=i.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),i.addEventListener("click",b=>{b.target===i&&this.closeAiModal()}),this.aiModal=i,this.aiKeyInput=i.querySelector("[data-ai-key]"),this.aiModelSelect=i.querySelector("[data-ai-model]"),this.aiPromptInput=i.querySelector("[data-ai-prompt]"),this.aiStrengthInput=i.querySelector("[data-ai-strength]"),this.aiStrengthValue=i.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=i.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=i.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=i.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=i.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=i.querySelector("[data-ai-ref-input]"),this.aiReferenceName=i.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=i.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=i.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=i.querySelector("[data-ai-generate]"),this.aiApplyBtn=i.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=i.querySelector("[data-ai-save-library]"),this.aiCropBtn=i.querySelector("[data-ai-crop]"),this.aiDownloadBtn=i.querySelector("[data-ai-download]"),this.aiPreviewImg=i.querySelector("[data-ai-preview]"),this.aiStatusEl=i.querySelector("[data-ai-status]"),this.aiLoadingEl=i.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=i.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=i.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let s=i.querySelector("[data-ai-ref-button]");s==null||s.addEventListener("click",()=>{var b;return(b=this.aiReferenceInput)==null?void 0:b.click()}),(l=this.aiGalleryToggle)==null||l.addEventListener("click",()=>this.toggleAiGallery()),(c=this.aiStrengthInput)==null||c.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiStrengthInput)==null?void 0:y.value)!=null?v:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=b)}),(p=this.aiBgToleranceInput)==null||p.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiBgToleranceInput)==null?void 0:y.value)!=null?v:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=b),this.refreshAiOutputFromRaw()}),(d=this.aiReferenceInput)==null||d.addEventListener("change",()=>{var y,v,S;let b=(S=(v=(y=this.aiReferenceInput)==null?void 0:y.files)==null?void 0:v[0])!=null?S:null;this.aiReferenceFile=b,this.aiReferenceName&&(this.aiReferenceName.textContent=b?`${b.name} (loaded)`:"Optional"),b&&this.setAiStatus(`Reference attached: ${b.name}`)}),(u=this.aiGenerateBtn)==null||u.addEventListener("click",()=>{this.handleAiGenerate()}),(g=this.aiApplyBtn)==null||g.addEventListener("click",()=>this.handleAiApply()),(m=this.aiSaveLibraryBtn)==null||m.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(h=this.aiCropBtn)==null||h.addEventListener("click",()=>{this.handleAiCrop()}),(f=this.aiDownloadBtn)==null||f.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(i),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(t),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var p,d,u,g,m,h,f,b,y,v,S,C,k,z,w,x,M,A,E,I;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let e=(u=(d=(p=this.aiKeyInput)==null?void 0:p.value)==null?void 0:d.trim())!=null?u:"",t=(m=(g=this.aiModelSelect)==null?void 0:g.value)!=null?m:"gemini-2.5-flash-image",n=(b=(f=(h=this.aiPromptInput)==null?void 0:h.value)==null?void 0:f.trim())!=null?b:"",i=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,a=i,s=i,o=Number((C=(S=this.aiStrengthInput)==null?void 0:S.value)!=null?C:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((k=l==null?void 0:l.value)==null?void 0:k.trim())||((z=this.aiBaseValue)==null?void 0:z.trim())||"";if(!c&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let L=null,_=(w=this.getSelectedAssetKey())!=null?w:"unknown",P=(x=this.aiUseOutputToggle)!=null&&x.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((M=this.aiUseOutputToggle)!=null&&M.checked&&this.aiOutputDataUrl){let W=Xi(this.aiOutputDataUrl,"ai-output.png");if(W){let J=await Ie(W);J&&(L={input:{base64:J.base64,mimeType:J.mimeType},dataUrl:J.dataUrl,width:J.width,height:J.height})}}if(L||(L=await this.getImageDataFromAsset(c)),!L){this.setAiStatus("Unable to load the base image.");return}let R=[L.input],T=!1;if(this.aiReferenceFile){let W=await Ie(this.aiReferenceFile);W?(R.push({base64:W.base64,mimeType:W.mimeType}),T=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let j=ns(n,{includeReference:T,includeMagenta:a,changeLevel:o}),O=(E=(A=this.aiReferenceFile)==null?void 0:A.name)!=null?E:"none";console.info("[AI] Final prompt:",j),console.info("[AI] Image sources:",{assetKey:_,base:P,reference:O});let H=Gr(L.width,L.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let F=await it(e,j,R,{aspectRatio:H,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",F==null?void 0:F.length),this.aiRawOutputDataUrl=F,await this.refreshAiOutputFromRaw()}catch(L){console.error("[CustomizePanel] AI Generate Error:",L),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((I=this.aiStatusEl)==null?void 0:I.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var i,a,s,o;if(!this.aiRawOutputDataUrl)return;let e=(a=(i=this.aiRemoveBgToggle)==null?void 0:i.checked)!=null?a:!1,t=Number((o=(s=this.aiBgToleranceInput)==null?void 0:s.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(e){let l=await nt(this.aiRawOutputDataUrl,t);l&&(n=l)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(e){var n,i;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(n=this.previewModal)==null?void 0:n.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(i=this.activePreviewKey)!=null?i:void 0)}setAiOutputButtonsEnabled(e){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!e),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!e),this.aiCropBtn&&(this.aiCropBtn.disabled=!e),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!e)}handleAiApply(){var t,n,i;let e=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(e)console.log("[CustomizePanel] Applying AI output to brand asset:",e.dataset.assetKey),e.value=this.aiOutputDataUrl,this.handleAssetValueChange((t=e.dataset.assetKey)!=null?t:"",e),this.setAiStatus("Applied. Restarting game...");else{let a=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),s=((i=this.aiContext)==null?void 0:i.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&s)console.log("[CustomizePanel] Applying AI output directly to object:",a,s),this.applyObjectPropertyValue(a,s,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var a,s,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let n=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,i=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let c=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:i,filename:`${n}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${n}.png. Refreshing library...`);let p=window.addAssetToRegistry;typeof p=="function"&&(console.log("[CustomizePanel] Adding to registry category:",i),p(i,`${n}.png`));try{console.log("[CustomizePanel] Triggering setup-library..."),(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok?console.log("[CustomizePanel] \u2705 Library setup completed"):console.warn("[CustomizePanel] Setup-library returned non-OK status")}catch(b){console.warn("[CustomizePanel] Setup-library endpoint not available:",b)}let d=window.refreshAssetLibrary;typeof d=="function"&&(console.log("[CustomizePanel] Refreshing library panel..."),await d());let u=window.__wizardAssetPicker;if(u!=null&&u.onPick){u.onPick(c.path),window.__wizardAssetPicker=null,this.setAiStatus("Saved to library and applied to wizard.");return}let g=((a=this.aiContext)==null?void 0:a.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),m=((s=this.aiContext)==null?void 0:s.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),h=this.getSelectedAssetInput();if(h&&(h.value=c.path,this.handleAssetValueChange((o=h.dataset.assetKey)!=null?o:"",h)),g&&m){console.log("[CustomizePanel] Applying saved asset to object:",g,m);let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(m)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof b=="function"&&y){let v=this.getFilenameFromPath(c.path);await b(g,v,i)}else this.applyObjectPropertyValue(g,m,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let f=window.__highlightLibrarySlot;typeof f=="function"&&g&&(console.log("[CustomizePanel] Highlighting slot in library:",g,i),setTimeout(()=>{f(g,i)},500)),this.setAiStatus(`\u2705 Saved and applied ${n}.png`),setTimeout(()=>{this.closeAiModal()},1500)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(e){var s;let t=(s=this.aiContext)==null?void 0:s.objectId,n=e||this.aiTargetKey||"",i=window.getEditableAssets;if(typeof i=="function"){let o=i();if(o!=null&&o.slots){let l=o.slots.find(c=>t&&c.objectId===t||c.currentAsset===n||c.slotId===n||c.currentAsset&&c.currentAsset.includes(n)||n.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let a=n.toLowerCase();return a.includes("background")?"backgrounds":a.includes("character")?"characters":a.includes("key")?"collectedkeys":a.includes("draggable")?"draggables":a.includes("environment")||a.includes("env")||a.includes("hand")||a.includes("prop")||a.includes("item")||a.includes("decor")||a.includes("object")?"environment":a.includes("machine")?"machines":a.includes("tutorial")?"tutorial":a.includes("ui")||a.includes("button")||a.includes("label")||a.includes("icon")||a.includes("logo")||a.includes("cta")||a.includes("menu")||a.includes("overlay")?"ui":a.includes("effect")||a.includes("confetti")||a.includes("particle")?"effects":"ui"}inferObjectIdFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(a=>a.currentAsset===e||a.slotId===e);return(i==null?void 0:i.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(s=>s.currentAsset===e||s.slotId===e);if(!i)return null;let a=i.category;return a==="render"||a==="backgrounds"||a==="characters"?"render.texture":a==="ui"?"ui.image":a==="audio"?"audio.src":"render.texture"}getFilenameFromPath(e){if(!e)return"";let t=e.split("/");return t[t.length-1]}async handleAiCrop(){var o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let e=this.getSelectedAssetInput(),t=(o=e==null?void 0:e.value)!=null?o:"",n=await this.getImageDimensions(t);if(!n){this.setAiStatus("Unable to read target dimensions.");return}let i=Xi(this.aiOutputDataUrl,"ai-output.png");if(!i)return;let a=await this.showManualCropModal(i,n,t);if(!a)return;let s=await Ki(a);s&&this.setAiOutput(s)}handleAiDownload(){var n;if(!this.aiOutputDataUrl)return;let e=(n=this.getSelectedAssetKey())!=null?n:"ai-image",t=document.createElement("a");t.href=this.aiOutputDataUrl,t.download=`${e}-ai.png`,t.click()}handleAssetValueChange(e,t){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(e,t.value,t.dataset.assetType)}async handleAssetUpload(e,t,n){console.log("[CustomizePanel] Handling asset upload for:",n);let i=t.value,a=e;if(e.type.startsWith("image/")){let p=await this.getImageDimensions(i);if(p){let d=await this.showManualCropModal(e,p,i);if(!d)return;a=d}}let s=await Ki(a);if(!s){console.error("[CustomizePanel] Failed to convert file to data URL");return}let l=`${n.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,c=this.inferCategoryFromAssetKey(n);console.log("[CustomizePanel] Saving uploaded file to library:",l,"category:",c);try{let d=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:c,filename:`${l}.png`,data:s,overwrite:!0})})).json();if(d.success){console.log("[CustomizePanel] \u2705 Uploaded file saved to library:",d.path);let u=window.addAssetToRegistry;typeof u=="function"&&u(c,`${l}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(b){console.warn("[CustomizePanel] Setup-library not available:",b)}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),t.value=d.path,this.handleAssetValueChange(n,t);let m=this.inferObjectIdFromAssetKey(n),h=this.inferPathFromAssetKey(n);if(m&&h){let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(h)||/\\.(png|jpg|jpeg)$/i.test(String(d.path||""));if(typeof b=="function"&&y){let v=this.getFilenameFromPath(d.path);await b(m,v,c)}else this.applyObjectPropertyValue(m,h,d.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let f=window.__highlightLibrarySlot;typeof f=="function"&&m&&setTimeout(()=>{f(m,c)},500),console.log("[CustomizePanel] \u2705 Upload complete:",l)}else console.error("[CustomizePanel] \u274C Upload save failed:",d.error),alert(`Failed to save uploaded file: ${d.error}`)}catch(p){console.error("[CustomizePanel] \u274C Upload error:",p),alert("Failed to save uploaded file. Check console for details.")}}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(e,t,n,i){if(!t)return;let a=this.resolveAssetUrls(t);if(a.length===0)return;let s=n||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=i!=null?i:null,this.openPreviewModal(e,t,a,s)}resolveAssetUrls(e){let t=e.trim();if(!t)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",t),/^(blob:|data:|https?:|\/)/.test(t))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[t];let n=t.replace(/^\.?\//,""),i=[];return n.startsWith("raw/")?i=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?i=[`/${n}`]:i=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",i),i}guessMimeType(e){let t=e.toLowerCase();return t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif")||t.endsWith(".webp")||t.endsWith(".svg")?"image":t.endsWith(".mp3")||t.endsWith(".wav")||t.endsWith(".ogg")?"audio":t.endsWith(".json")?"json":"file"}openPreviewModal(e,t,n,i){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
|
|
1579
|
+
`;let a=i.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),i.addEventListener("click",b=>{b.target===i&&this.closeAiModal()}),this.aiModal=i,this.aiKeyInput=i.querySelector("[data-ai-key]"),this.aiModelSelect=i.querySelector("[data-ai-model]"),this.aiPromptInput=i.querySelector("[data-ai-prompt]"),this.aiStrengthInput=i.querySelector("[data-ai-strength]"),this.aiStrengthValue=i.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=i.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=i.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=i.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=i.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=i.querySelector("[data-ai-ref-input]"),this.aiReferenceName=i.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=i.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=i.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=i.querySelector("[data-ai-generate]"),this.aiApplyBtn=i.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=i.querySelector("[data-ai-save-library]"),this.aiCropBtn=i.querySelector("[data-ai-crop]"),this.aiDownloadBtn=i.querySelector("[data-ai-download]"),this.aiPreviewImg=i.querySelector("[data-ai-preview]"),this.aiStatusEl=i.querySelector("[data-ai-status]"),this.aiLoadingEl=i.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=i.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=i.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let s=i.querySelector("[data-ai-ref-button]");s==null||s.addEventListener("click",()=>{var b;return(b=this.aiReferenceInput)==null?void 0:b.click()}),(l=this.aiGalleryToggle)==null||l.addEventListener("click",()=>this.toggleAiGallery()),(c=this.aiStrengthInput)==null||c.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiStrengthInput)==null?void 0:y.value)!=null?v:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=b)}),(p=this.aiBgToleranceInput)==null||p.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiBgToleranceInput)==null?void 0:y.value)!=null?v:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=b),this.refreshAiOutputFromRaw()}),(d=this.aiReferenceInput)==null||d.addEventListener("change",()=>{var y,v,w;let b=(w=(v=(y=this.aiReferenceInput)==null?void 0:y.files)==null?void 0:v[0])!=null?w:null;this.aiReferenceFile=b,this.aiReferenceName&&(this.aiReferenceName.textContent=b?`${b.name} (loaded)`:"Optional"),b&&this.setAiStatus(`Reference attached: ${b.name}`)}),(u=this.aiGenerateBtn)==null||u.addEventListener("click",()=>{this.handleAiGenerate()}),(g=this.aiApplyBtn)==null||g.addEventListener("click",()=>this.handleAiApply()),(m=this.aiSaveLibraryBtn)==null||m.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(h=this.aiCropBtn)==null||h.addEventListener("click",()=>{this.handleAiCrop()}),(f=this.aiDownloadBtn)==null||f.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(i),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(t),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var p,d,u,g,m,h,f,b,y,v,w,E,j,z,S,_,R,T,C,M;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let e=(u=(d=(p=this.aiKeyInput)==null?void 0:p.value)==null?void 0:d.trim())!=null?u:"",t=(m=(g=this.aiModelSelect)==null?void 0:g.value)!=null?m:"gemini-2.5-flash-image",n=(b=(f=(h=this.aiPromptInput)==null?void 0:h.value)==null?void 0:f.trim())!=null?b:"",i=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,a=i,s=i,o=Number((E=(w=this.aiStrengthInput)==null?void 0:w.value)!=null?E:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((j=l==null?void 0:l.value)==null?void 0:j.trim())||((z=this.aiBaseValue)==null?void 0:z.trim())||"";if(!c&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let k=null,A=(S=this.getSelectedAssetKey())!=null?S:"unknown",x=(_=this.aiUseOutputToggle)!=null&&_.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((R=this.aiUseOutputToggle)!=null&&R.checked&&this.aiOutputDataUrl){let G=Ji(this.aiOutputDataUrl,"ai-output.png");if(G){let K=await _e(G);K&&(k={input:{base64:K.base64,mimeType:K.mimeType},dataUrl:K.dataUrl,width:K.width,height:K.height})}}if(k||(k=await this.getImageDataFromAsset(c)),!k){this.setAiStatus("Unable to load the base image.");return}let I=[k.input],L=!1;if(this.aiReferenceFile){let G=await _e(this.aiReferenceFile);G?(I.push({base64:G.base64,mimeType:G.mimeType}),L=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let P=ns(n,{includeReference:L,includeMagenta:a,changeLevel:o}),O=(C=(T=this.aiReferenceFile)==null?void 0:T.name)!=null?C:"none";console.info("[AI] Final prompt:",P),console.info("[AI] Image sources:",{assetKey:A,base:x,reference:O});let H=Gr(k.width,k.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let N=await rt(e,P,I,{aspectRatio:H,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",N==null?void 0:N.length),this.aiRawOutputDataUrl=N,await this.refreshAiOutputFromRaw()}catch(k){console.error("[CustomizePanel] AI Generate Error:",k),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((M=this.aiStatusEl)==null?void 0:M.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var i,a,s,o;if(!this.aiRawOutputDataUrl)return;let e=(a=(i=this.aiRemoveBgToggle)==null?void 0:i.checked)!=null?a:!1,t=Number((o=(s=this.aiBgToleranceInput)==null?void 0:s.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(e){let l=await at(this.aiRawOutputDataUrl,t);l&&(n=l)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(e){var n,i;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(n=this.previewModal)==null?void 0:n.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(i=this.activePreviewKey)!=null?i:void 0)}setAiOutputButtonsEnabled(e){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!e),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!e),this.aiCropBtn&&(this.aiCropBtn.disabled=!e),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!e)}handleAiApply(){var t,n,i;let e=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(e)console.log("[CustomizePanel] Applying AI output to brand asset:",e.dataset.assetKey),e.value=this.aiOutputDataUrl,this.handleAssetValueChange((t=e.dataset.assetKey)!=null?t:"",e),this.setAiStatus("Applied. Restarting game...");else{let a=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),s=((i=this.aiContext)==null?void 0:i.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&s)console.log("[CustomizePanel] Applying AI output directly to object:",a,s),this.applyObjectPropertyValue(a,s,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var a,s,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let n=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,i=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let c=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:i,filename:`${n}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${n}.png. Refreshing library...`);let p=window.addAssetToRegistry;typeof p=="function"&&(console.log("[CustomizePanel] Adding to registry category:",i),p(i,`${n}.png`));try{console.log("[CustomizePanel] Triggering setup-library..."),(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok?console.log("[CustomizePanel] \u2705 Library setup completed"):console.warn("[CustomizePanel] Setup-library returned non-OK status")}catch(b){console.warn("[CustomizePanel] Setup-library endpoint not available:",b)}let d=window.refreshAssetLibrary;typeof d=="function"&&(console.log("[CustomizePanel] Refreshing library panel..."),await d());let u=window.__wizardAssetPicker;if(u!=null&&u.onPick){u.onPick(c.path),window.__wizardAssetPicker=null,this.setAiStatus("Saved to library and applied to wizard.");return}let g=((a=this.aiContext)==null?void 0:a.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),m=((s=this.aiContext)==null?void 0:s.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),h=this.getSelectedAssetInput();if(h&&(h.value=c.path,this.handleAssetValueChange((o=h.dataset.assetKey)!=null?o:"",h)),g&&m){console.log("[CustomizePanel] Applying saved asset to object:",g,m);let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(m)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof b=="function"&&y){let v=this.getFilenameFromPath(c.path);await b(g,v,i)}else this.applyObjectPropertyValue(g,m,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let f=window.__highlightLibrarySlot;typeof f=="function"&&g&&(console.log("[CustomizePanel] Highlighting slot in library:",g,i),setTimeout(()=>{f(g,i)},500)),this.setAiStatus(`\u2705 Saved and applied ${n}.png`),setTimeout(()=>{this.closeAiModal()},1500)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(e){var s;let t=(s=this.aiContext)==null?void 0:s.objectId,n=e||this.aiTargetKey||"",i=window.getEditableAssets;if(typeof i=="function"){let o=i();if(o!=null&&o.slots){let l=o.slots.find(c=>t&&c.objectId===t||c.currentAsset===n||c.slotId===n||c.currentAsset&&c.currentAsset.includes(n)||n.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let a=n.toLowerCase();return a.includes("background")?"backgrounds":a.includes("character")?"characters":a.includes("key")?"collectedkeys":a.includes("draggable")?"draggables":a.includes("environment")||a.includes("env")||a.includes("hand")||a.includes("prop")||a.includes("item")||a.includes("decor")||a.includes("object")?"environment":a.includes("machine")?"machines":a.includes("tutorial")?"tutorial":a.includes("ui")||a.includes("button")||a.includes("label")||a.includes("icon")||a.includes("logo")||a.includes("cta")||a.includes("menu")||a.includes("overlay")?"ui":a.includes("effect")||a.includes("confetti")||a.includes("particle")?"effects":"ui"}inferObjectIdFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(a=>a.currentAsset===e||a.slotId===e);return(i==null?void 0:i.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(s=>s.currentAsset===e||s.slotId===e);if(!i)return null;let a=i.category;return a==="render"||a==="backgrounds"||a==="characters"?"render.texture":a==="ui"?"ui.image":a==="audio"?"audio.src":"render.texture"}getFilenameFromPath(e){if(!e)return"";let t=e.split("/");return t[t.length-1]}async handleAiCrop(){var o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let e=this.getSelectedAssetInput(),t=(o=e==null?void 0:e.value)!=null?o:"",n=await this.getImageDimensions(t);if(!n){this.setAiStatus("Unable to read target dimensions.");return}let i=Ji(this.aiOutputDataUrl,"ai-output.png");if(!i)return;let a=await this.showManualCropModal(i,n,t);if(!a)return;let s=await Xi(a);s&&this.setAiOutput(s)}handleAiDownload(){var n;if(!this.aiOutputDataUrl)return;let e=(n=this.getSelectedAssetKey())!=null?n:"ai-image",t=document.createElement("a");t.href=this.aiOutputDataUrl,t.download=`${e}-ai.png`,t.click()}handleAssetValueChange(e,t){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(e,t.value,t.dataset.assetType)}async handleAssetUpload(e,t,n){console.log("[CustomizePanel] Handling asset upload for:",n);let i=t.value,a=e;if(e.type.startsWith("image/")){let p=await this.getImageDimensions(i);if(p){let d=await this.showManualCropModal(e,p,i);if(!d)return;a=d}}let s=await Xi(a);if(!s){console.error("[CustomizePanel] Failed to convert file to data URL");return}let l=`${n.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,c=this.inferCategoryFromAssetKey(n);console.log("[CustomizePanel] Saving uploaded file to library:",l,"category:",c);try{let d=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:c,filename:`${l}.png`,data:s,overwrite:!0})})).json();if(d.success){console.log("[CustomizePanel] \u2705 Uploaded file saved to library:",d.path);let u=window.addAssetToRegistry;typeof u=="function"&&u(c,`${l}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(b){console.warn("[CustomizePanel] Setup-library not available:",b)}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),t.value=d.path,this.handleAssetValueChange(n,t);let m=this.inferObjectIdFromAssetKey(n),h=this.inferPathFromAssetKey(n);if(m&&h){let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(h)||/\\.(png|jpg|jpeg)$/i.test(String(d.path||""));if(typeof b=="function"&&y){let v=this.getFilenameFromPath(d.path);await b(m,v,c)}else this.applyObjectPropertyValue(m,h,d.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let f=window.__highlightLibrarySlot;typeof f=="function"&&m&&setTimeout(()=>{f(m,c)},500),console.log("[CustomizePanel] \u2705 Upload complete:",l)}else console.error("[CustomizePanel] \u274C Upload save failed:",d.error),alert(`Failed to save uploaded file: ${d.error}`)}catch(p){console.error("[CustomizePanel] \u274C Upload error:",p),alert("Failed to save uploaded file. Check console for details.")}}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(e,t,n,i){if(!t)return;let a=this.resolveAssetUrls(t);if(a.length===0)return;let s=n||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=i!=null?i:null,this.openPreviewModal(e,t,a,s)}resolveAssetUrls(e){let t=e.trim();if(!t)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",t),/^(blob:|data:|https?:|\/)/.test(t))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[t];let n=t.replace(/^\.?\//,""),i=[];return n.startsWith("raw/")?i=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?i=[`/${n}`]:i=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",i),i}guessMimeType(e){let t=e.toLowerCase();return t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif")||t.endsWith(".webp")||t.endsWith(".svg")?"image":t.endsWith(".mp3")||t.endsWith(".wav")||t.endsWith(".ogg")?"audio":t.endsWith(".json")?"json":"file"}openPreviewModal(e,t,n,i){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
|
|
1529
1580
|
<div class="asset-preview-card">
|
|
1530
1581
|
<div class="asset-preview-header">
|
|
1531
1582
|
<div class="asset-preview-title">${e}</div>
|
|
@@ -1571,7 +1622,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1571
1622
|
<button class="asset-crop-apply" type="button">Apply Crop</button>
|
|
1572
1623
|
</div>
|
|
1573
1624
|
</div>
|
|
1574
|
-
`;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),
|
|
1625
|
+
`;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),w=c.querySelector(".asset-crop-zoom"),E=c.querySelector(".asset-crop-zoom-value"),j=c.querySelector(".asset-crop-close"),z=c.querySelector(".asset-crop-cancel"),S=c.querySelector(".asset-crop-apply"),_=c.querySelector(".asset-crop-reset");if(!y||!v||!w||!E){l(null);return}let R=y.getContext("2d"),T=v.getContext("2d");if(!R||!T){l(null);return}let C=s.naturalWidth,M=s.naturalHeight,k=Math.max(y.width/C,y.height/M),A=1,x=0,I=0,L=!1,P=0,O=0,H=0,N=0,G=()=>{let D=k*A,Z=Math.max(0,(C*D-y.width)/2),Ke=Math.max(0,(M*D-y.height)/2);x=Math.min(Z,Math.max(-Z,x)),I=Math.min(Ke,Math.max(-Ke,I))},K=()=>{let D=k*A;R.clearRect(0,0,y.width,y.height);let Z=y.width/2-C*D/2+x,Ke=y.height/2-M*D/2+I;if(R.drawImage(s,Z,Ke,C*D,M*D),T.clearRect(0,0,v.width,v.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let Je=Math.max(v.width/o.naturalWidth,v.height/o.naturalHeight),ui=v.width/2-o.naturalWidth*Je/2,yt=v.height/2-o.naturalHeight*Je/2;T.drawImage(o,ui,yt,o.naturalWidth*Je,o.naturalHeight*Je)}else T.fillStyle="rgba(255, 255, 255, 0.04)",T.fillRect(0,0,v.width,v.height),T.strokeStyle="rgba(255, 255, 255, 0.08)",T.strokeRect(4,4,v.width-8,v.height-8);let bt=v.width/y.width*(k*A),Xe=x*(v.width/y.width),Yt=I*(v.height/y.height),di=v.width/2-C*bt/2+Xe,pi=v.height/2-M*bt/2+Yt;T.save(),T.globalAlpha=.7,T.drawImage(s,di,pi,C*bt,M*bt),T.restore()},ze=()=>{x=0,I=0,G(),K()};w.addEventListener("input",()=>{A=Number(w.value),E.textContent=`${A.toFixed(2)}\xD7`,G(),K()}),y.addEventListener("pointerdown",D=>{L=!0,P=D.clientX,O=D.clientY,H=x,N=I,y.setPointerCapture(D.pointerId)}),y.addEventListener("pointermove",D=>{L&&(x=H+(D.clientX-P),I=N+(D.clientY-O),G(),K())}),y.addEventListener("pointerup",D=>{L=!1,y.releasePointerCapture(D.pointerId)}),y.addEventListener("pointerleave",()=>{L=!1});let ue=()=>{c.remove()},ge=()=>{ue(),l(null)},Ye=async()=>{let D=document.createElement("canvas");D.width=t.width,D.height=t.height;let Z=D.getContext("2d");if(!Z){ue(),l(null);return}let Ke=A,Xe=Math.max(D.width/C,D.height/M)*Ke,Yt=D.width/y.width,di=x*Yt,pi=I*Yt,Je=D.width/2-C*Xe/2+di,ui=D.height/2-M*Xe/2+pi;Z.drawImage(s,Je,ui,C*Xe,M*Xe);let yt=await new Promise(Vs=>{D.toBlob(Ws=>Vs(Ws),e.type||"image/png")});if(ue(),!yt){l(null);return}l(new File([yt],e.name,{type:yt.type}))};j==null||j.addEventListener("click",ge),z==null||z.addEventListener("click",ge),_==null||_.addEventListener("click",ze),S==null||S.addEventListener("click",()=>{Ye()}),c.addEventListener("click",D=>{D.target===c&&ge()}),document.body.appendChild(c),ze()})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let n of t){let i=await this.loadImage(n);if(i)return i}return null}};var Wn=class{constructor(){this.root=null;this.options=null}render(){return`
|
|
1575
1626
|
<div class="scene-panel loading-screen-panel panel-accent-purple" data-panel="loading-screen">
|
|
1576
1627
|
<div class="scene-panel-header" data-panel-handle>
|
|
1577
1628
|
<div class="panel-title">
|
|
@@ -1637,10 +1688,10 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1637
1688
|
</div>
|
|
1638
1689
|
</div>
|
|
1639
1690
|
</div>
|
|
1640
|
-
`}initialize(e,t){var y,v,S,C,k,z,w,x,M,A,E,I,L,_,P,R;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let i=(()=>{var j;let T=window.getEditableEngineConfig;if(typeof T=="function"){let O=T();return(j=O==null?void 0:O.loading)!=null?j:{}}return{}})(),a=(y=this.root)==null?void 0:y.querySelector("#loading-screen-type");a&&(a.value=i.type==="image"?"image":"color",a.addEventListener("change",()=>{var T,j;(j=(T=this.options)==null?void 0:T.onUpdateLoading)==null||j.call(T,{type:a.value}),this.updateFieldVisibility(a.value)}));let s=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");s&&(s.value=i.background_color||"#160a17",s.addEventListener("input",()=>{var T,j;(j=(T=this.options)==null?void 0:T.onUpdateLoading)==null||j.call(T,{background_color:s.value})}));let o=(S=this.root)==null?void 0:S.querySelector("#loading-overlay-alpha"),l=(C=this.root)==null?void 0:C.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((k=i.overlay_alpha)!=null?k:1),l&&(l.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var j,O;let T=Number(o.value);l&&(l.textContent=T.toFixed(2)),(O=(j=this.options)==null?void 0:j.onUpdateLoading)==null||O.call(j,{overlay_alpha:T})}));let c=(z=this.root)==null?void 0:z.querySelector("#loading-text");c&&(c.value=i.text||"",c.addEventListener("input",()=>{var T,j;(j=(T=this.options)==null?void 0:T.onUpdateLoading)==null||j.call(T,{text:c.value})}));let p=(w=this.root)==null?void 0:w.querySelector("#loading-text-scale"),d=(x=this.root)==null?void 0:x.querySelector("#loading-text-scale-value");p&&(p.value=String((M=i.text_scale)!=null?M:.6),d&&(d.textContent=Number(p.value).toFixed(2)),p.addEventListener("input",()=>{var j,O;let T=Number(p.value);d&&(d.textContent=T.toFixed(2)),(O=(j=this.options)==null?void 0:j.onUpdateLoading)==null||O.call(j,{text_scale:T})}));let u=(A=this.root)==null?void 0:A.querySelector("#loading-enabled");u&&(u.checked=i.enabled!==!1,u.addEventListener("change",()=>{var T,j;(j=(T=this.options)==null?void 0:T.onUpdateLoading)==null||j.call(T,{enabled:u.checked})}));let g=(E=this.root)==null?void 0:E.querySelector("#loading-blur-enabled");g&&(g.checked=i.blur_enabled!==!1,g.addEventListener("change",()=>{var T,j;(j=(T=this.options)==null?void 0:T.onUpdateLoading)==null||j.call(T,{blur_enabled:g.checked})}));let m=(I=this.root)==null?void 0:I.querySelector("#loading-blur-strength"),h=(L=this.root)==null?void 0:L.querySelector("#loading-blur-strength-value");m&&(m.value=String((_=i.blur_strength)!=null?_:8),h&&(h.textContent=m.value),m.addEventListener("input",()=>{var T,j;h&&(h.textContent=m.value),(j=(T=this.options)==null?void 0:T.onUpdateLoading)==null||j.call(T,{blur_strength:Number(m.value)})}));let f=(P=this.root)==null?void 0:P.querySelector("#loading-show-btn"),b=(R=this.root)==null?void 0:R.querySelector("#loading-hide-btn");f==null||f.addEventListener("click",()=>{var T,j;(j=(T=this.options)==null?void 0:T.onShowLoadingScreen)==null||j.call(T)}),b==null||b.addEventListener("click",()=>{var T,j;(j=(T=this.options)==null?void 0:T.onHideLoadingScreen)==null||j.call(T)}),this.updateFieldVisibility(i.type==="image"?"image":"color")}updateFieldVisibility(e){var i,a;let t=(i=this.root)==null?void 0:i.querySelector("#loading-color-field"),n=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),n&&(n.style.display="none")):(t&&(t.style.display=""),n&&(n.style.display=""))}refresh(){}};var Mt=require("pixi.js");et();X();async function as(r,e,t){var n,i;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let a=Date.now(),o=`/${`raw/library/${e}/${t}`}?t=${a}`;console.log("[LIBRARY] Loading texture from:",o);let l=await Mt.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load texture:",o);return}let c=window.CustomAssets,p=Object.keys(c||{}).filter(u=>{let g=e.replace(/s$/,"");return u.startsWith(g)||u.includes(g)});for(let u of p)oe[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(n=c[u])!=null&&n.texture&&(c[u].texture=l,console.log("[LIBRARY] \u2705 Updated CustomAssets."+u+".texture"));let d=window.gameObjectManager;if(d)for(let u of p){let g=d.get(u);if(g){let m=((i=g.getDisplayObject)==null?void 0:i.call(g))||g.pixiObject||g;m!=null&&m.texture&&(m.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(a){console.error("[LIBRARY] Error applying asset change:",a)}}async function rs(r,e){var t,n,i;console.log("[LIBRARY] resetAsset called for:",e);try{let a=window.getEditableAssets,s=typeof a=="function"?a():null,o=(t=s==null?void 0:s.slots)==null?void 0:t.find(f=>f.category===e),l=o==null?void 0:o.defaultAsset;if(!l){console.warn("[LIBRARY] Could not find default asset for:",e);return}let c=Date.now(),p=`/raw/${l}?t=${c}`;console.log("[LIBRARY] Loading default texture from:",p);let d=await Mt.Assets.load(p);if(!d){console.error("[LIBRARY] Failed to load default texture:",p);return}let u=window.CustomAssets,g=e.replace(/s$/,""),m=Object.keys(u||{}).filter(f=>f.startsWith(g)||f.includes(g));for(let f of m)oe[f]=d,console.log("[LIBRARY] \u2705 Reset AssetTextures."+f),(n=u[f])!=null&&n.texture&&(u[f].texture=d,console.log("[LIBRARY] \u2705 Reset CustomAssets."+f+" to default"));let h=window.gameObjectManager;if(h)for(let f of m){let b=h.get(f);if(b){let y=((i=b.getDisplayObject)==null?void 0:i.call(b))||b.pixiObject||b;y!=null&&y.texture&&(y.texture=d,console.log("[LIBRARY] \u2705 Reset display object:",f))}}}catch(a){console.error("[LIBRARY] Error resetting asset:",a)}}async function ss(r,e,t,n){var i,a,s,o,l,c,p,d,u,g,m,h,f,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:n});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let S=Date.now(),C=`/raw/library/${n}/${t}?t=${S}`;console.log("[LIBRARY] Loading texture from:",C);let k=await Mt.Assets.load(C);if(!k){console.error("[LIBRARY] Failed to load texture:",C);return}console.log("[LIBRARY] \u2705 Texture loaded"),oe[v]=k,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let z=window.CustomAssets;z!=null&&z[v]&&(z[v].texture=k,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let w=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!w),w){let M=Array.from(((i=w.keys)==null?void 0:i.call(w))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",M);let A=w.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!A),A){let E=((a=A.getDisplayObject)==null?void 0:a.call(A))||A.pixiObject||A.pixi||A,I=(s=E==null?void 0:E.constructor)==null?void 0:s.name;if(console.log("[LIBRARY] displayObject:",E),console.log("[LIBRARY] displayObject type:",I),console.log("[LIBRARY] has texture?",!!(E!=null&&E.texture)),E!=null&&E.texture)E.texture=k,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(I==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:L}=await import("pixi.js"),_=E.parent,P=(l=(o=_==null?void 0:_.getChildIndex)==null?void 0:o.call(_,E))!=null?l:0,R={x:E.x,y:E.y},T={x:(p=(c=E.anchor)==null?void 0:c.x)!=null?p:.5,y:(u=(d=E.anchor)==null?void 0:d.y)!=null?u:.5},j={x:(m=(g=E.scale)==null?void 0:g.x)!=null?m:1,y:(f=(h=E.scale)==null?void 0:h.y)!=null?f:1},O=(b=E.alpha)!=null?b:1,H=(y=E.visible)!=null?y:!0,F=new L(k);F.anchor.set(T.x,T.y),F.position.set(R.x,R.y),F.scale.set(j.x,j.y),F.alpha=O,F.visible=H,_&&(_.removeChild(E),_.addChildAt(F,P),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),A.pixiObject&&(A.pixiObject=F),A.pixi&&(A.pixi=F),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(E!=null&&E.children){let L=E.children.find(_=>_.texture);L?(L.texture=k,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let x=`raw/library/${n}/${t}`;le({objectId:v,path:"render.asset.path",value:x}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",x)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function os(r,e,t,n){var i;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:n});try{let a=e.startsWith("json.")?e.replace("json.",""):e,s=Date.now(),o=`/raw/${t}?t=${s}`;console.log("[LIBRARY] Loading default texture from:",o);let l=await Mt.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load default texture:",o);return}oe[a]=l,console.log("[LIBRARY] \u2705 Reset AssetTextures."+a);let c=window.CustomAssets;c!=null&&c[a]&&(c[a].texture=l,console.log("[LIBRARY] \u2705 Reset CustomAssets."+a+" to default"));let p=window.gameObjectManager;if(p){let d=p.get(a);if(d){let u=((i=d.getDisplayObject)==null?void 0:i.call(d))||d.pixiObject||d;u!=null&&u.texture&&(u.texture=l,console.log("[LIBRARY] \u2705 Reset display object:",a))}}le({objectId:a,path:"render.asset.path",value:t}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}var jt=require("pixi.js");var ea=require("pixi.js"),Me=()=>window.debugConfig||{},ls=()=>window.resolveAnchorVec2||(r=>({x:.5,y:.5})),cs=()=>window.resolveScreenAnchorPoint||(()=>new ea.Point),ds=()=>window.resolveScreenRatioPoint||(()=>new ea.Point);function ps(r){Vn(r)&&(r.objectDebugRaf||(r.objectDebugRaf=window.requestAnimationFrame(()=>Wn(r))))}function us(r){r.objectDebugRaf&&(window.cancelAnimationFrame(r.objectDebugRaf),r.objectDebugRaf=null),_t(r)}function Vn(r){return r.isDebugOpen}function Wn(r){var a,s,o;if(!Vn(r)){r.objectDebugRaf=null;return}r.objectDebugRaf=window.requestAnimationFrame(()=>Wn(r));let e=ta(r);if(!e){Pt(r,null),_t(r);return}let t=na(r,e);if(!t){Pt(r,null),_t(r);return}let n=new jt.Point;(a=t.getGlobalPosition)==null||a.call(t,n);let i=ia(r,t);Pt(r,{instanceId:e,worldX:n.x,worldY:n.y,configX:(s=i==null?void 0:i.x)!=null?s:null,configY:(o=i==null?void 0:i.y)!=null?o:null}),r.highlightObject?oa(r,t):ca(r),r.highlightAnchor&&i?la(r,i):da(r)}function ta(r){var i;let e=r.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return Array.isArray(n)&&n.length>0?n[0]:e}function na(r,e){var i,a;let t=window.gameObjectManager,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return n?((a=n.getDisplayObject)==null?void 0:a.call(n))||n.pixiObject||n:null}function Ot(r){let e=r.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function ia(r,e){var s,o;let t=Ot(r);if(!t)return null;let n=(s=t.transform)!=null?s:{},i=aa(r);if(!i)return null;if(n.position_ratio!=null)return ds()(i.width,i.height,n.position_ratio);let a=(o=n.anchor)!=null?o:"center";return cs()(i.width,i.height,a)}function aa(r){var a;let e=(a=r.container)==null?void 0:a.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),n=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(n)&&n>0)return{width:t,height:n};let i=window.gameApp;return i!=null&&i.renderer?{width:i.renderer.width,height:i.renderer.height}:null}function ra(r){let e=window.gameApp;return e!=null&&e.stage?(r.objectBoundsGfx&&r.objectBoundsGfx.parent!==e.stage&&(r.objectBoundsGfx.destroy(),r.objectBoundsGfx=null),r.objectBoundsGfx||(r.objectBoundsGfx=new jt.Graphics,r.objectBoundsGfx.zIndex=999999,e.stage.addChild(r.objectBoundsGfx)),r.objectBoundsGfx):null}function sa(r){let e=window.gameApp;return e!=null&&e.stage?(r.objectAnchorGfx&&r.objectAnchorGfx.parent!==e.stage&&(r.objectAnchorGfx.destroy(),r.objectAnchorGfx=null),r.objectAnchorGfx||(r.objectAnchorGfx=new jt.Graphics,r.objectAnchorGfx.zIndex=1e6,e.stage.addChild(r.objectAnchorGfx)),r.objectAnchorGfx):null}function oa(r,e){var i;let t=ra(r);if(!t)return;let n=(i=e.getBounds)==null?void 0:i.call(e);n&&(t.clear(),t.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function la(r,e){let t=sa(r);if(!t)return;let n=6;t.clear(),t.moveTo(e.x-n,e.y),t.lineTo(e.x+n,e.y),t.moveTo(e.x,e.y-n),t.lineTo(e.x,e.y+n),t.stroke({width:2,color:3066993,alpha:.9})}function ca(r){r.objectBoundsGfx&&r.objectBoundsGfx.clear()}function da(r){r.objectAnchorGfx&&r.objectAnchorGfx.clear()}function _t(r){r.objectBoundsGfx&&(r.objectBoundsGfx.destroy(),r.objectBoundsGfx=null),r.objectAnchorGfx&&(r.objectAnchorGfx.destroy(),r.objectAnchorGfx=null)}function Pt(r,e){r.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function gs(r,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,r)}function hs(r,e,t){var s;let n=e.split("."),i=n.pop(),a=r;for(let o of n)a[o]=(s=a[o])!=null?s:{},a=a[o];a[i]=t}function pa(r){var n,i,a,s,o;if(!r)return!1;if((n=r.transform)!=null&&n.offset)return!0;let e=((a=(i=r.identity)==null?void 0:i.category)!=null?a:"").toString().toLowerCase(),t=((o=(s=r.identity)==null?void 0:s.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function Kn(r){let e=Me();e.layout&&(e.layout.scale_multiplier=1,e.layout.position_offset={x:0,y:0},e.layout.debug_rect_visible=!0,e.layout.debug_rect_color=16711680,e.layout.debug_rect_thickness=4),e.engine&&(e.engine.scale=1,e.engine.background_scale=1.05,e.engine.label_pulse_speed=3,e.engine.label_pulse_intensity=.03),e.physics&&(e.physics.rope_length=420),window.location.reload()}function fs(r){window.location.reload()}function Xn(r){let e=JSON.stringify(Me(),null,2);navigator.clipboard.writeText(e).then(()=>{alert("Debug config copied to clipboard!")}).catch(()=>{console.log(e),alert("Config logged to console (clipboard not available)")})}async function ms(r,e){var t,n,i;if(!(!r.configViewer||!r.container))try{let a=window.getEditableObjectConfig,s=typeof a=="function"?a(e):null;if(!s){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(yn(),Hr)),d=(((t=(await o("scene.main")).scene)==null?void 0:t.objects)||[]).find(g=>g.object_config===e||g.instance_id===e);if(!d)return;let u=await l(d.object_config);console.log("[PREVIEW] Loaded object config (fallback)",e,u),Yn(r,u),(n=r.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,s),Yn(r,s),(i=r.configViewer)==null||i.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function Yn(r,e){var d,u,g,m,h,f,b,y,v,S;if(!r.container)return;let t=r.container.querySelector("#config-pos-x"),n=r.container.querySelector("#config-pos-y"),i=r.container.querySelector("#config-scale"),a=r.container.querySelector("#config-anchor-x"),s=r.container.querySelector("#config-anchor-y"),l=pa(e)?(d=e.transform)==null?void 0:d.offset:(u=e.transform)==null?void 0:u.position;t&&(t.value=String((g=l==null?void 0:l.x)!=null?g:0)),n&&(n.value=String((m=l==null?void 0:l.y)!=null?m:0)),i&&(i.value=String((f=(h=e.transform)==null?void 0:h.scale)!=null?f:1));let c=(S=(v=(b=e.transform)==null?void 0:b.anchor)!=null?v:(y=e.render)==null?void 0:y.anchor)!=null?S:{x:.5,y:.5},p=ls()(c);a&&(a.value=String(p.x)),s&&(s.value=String(p.y))}function bs(r){var l,c,p,d,u,g,m,h,f,b;let e=r.selectedObjectId;if(!e||!r.container)return;let t=(c=(l=r.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",n=(d=(p=r.container.querySelector("#config-pos-y"))==null?void 0:p.value)!=null?d:"0",i=(g=(u=r.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",a=(h=(m=r.container.querySelector("#config-anchor-x"))==null?void 0:m.value)!=null?h:"0.5",s=(b=(f=r.container.querySelector("#config-anchor-y"))==null?void 0:f.value)!=null?b:"0.5",o=`${e}:
|
|
1691
|
+
`}initialize(e,t){var y,v,w,E,j,z,S,_,R,T,C,M,k,A,x,I;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let i=(()=>{var P;let L=window.getEditableEngineConfig;if(typeof L=="function"){let O=L();return(P=O==null?void 0:O.loading)!=null?P:{}}return{}})(),a=(y=this.root)==null?void 0:y.querySelector("#loading-screen-type");a&&(a.value=i.type==="image"?"image":"color",a.addEventListener("change",()=>{var L,P;(P=(L=this.options)==null?void 0:L.onUpdateLoading)==null||P.call(L,{type:a.value}),this.updateFieldVisibility(a.value)}));let s=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");s&&(s.value=i.background_color||"#160a17",s.addEventListener("input",()=>{var L,P;(P=(L=this.options)==null?void 0:L.onUpdateLoading)==null||P.call(L,{background_color:s.value})}));let o=(w=this.root)==null?void 0:w.querySelector("#loading-overlay-alpha"),l=(E=this.root)==null?void 0:E.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((j=i.overlay_alpha)!=null?j:1),l&&(l.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var P,O;let L=Number(o.value);l&&(l.textContent=L.toFixed(2)),(O=(P=this.options)==null?void 0:P.onUpdateLoading)==null||O.call(P,{overlay_alpha:L})}));let c=(z=this.root)==null?void 0:z.querySelector("#loading-text");c&&(c.value=i.text||"",c.addEventListener("input",()=>{var L,P;(P=(L=this.options)==null?void 0:L.onUpdateLoading)==null||P.call(L,{text:c.value})}));let p=(S=this.root)==null?void 0:S.querySelector("#loading-text-scale"),d=(_=this.root)==null?void 0:_.querySelector("#loading-text-scale-value");p&&(p.value=String((R=i.text_scale)!=null?R:.6),d&&(d.textContent=Number(p.value).toFixed(2)),p.addEventListener("input",()=>{var P,O;let L=Number(p.value);d&&(d.textContent=L.toFixed(2)),(O=(P=this.options)==null?void 0:P.onUpdateLoading)==null||O.call(P,{text_scale:L})}));let u=(T=this.root)==null?void 0:T.querySelector("#loading-enabled");u&&(u.checked=i.enabled!==!1,u.addEventListener("change",()=>{var L,P;(P=(L=this.options)==null?void 0:L.onUpdateLoading)==null||P.call(L,{enabled:u.checked})}));let g=(C=this.root)==null?void 0:C.querySelector("#loading-blur-enabled");g&&(g.checked=i.blur_enabled!==!1,g.addEventListener("change",()=>{var L,P;(P=(L=this.options)==null?void 0:L.onUpdateLoading)==null||P.call(L,{blur_enabled:g.checked})}));let m=(M=this.root)==null?void 0:M.querySelector("#loading-blur-strength"),h=(k=this.root)==null?void 0:k.querySelector("#loading-blur-strength-value");m&&(m.value=String((A=i.blur_strength)!=null?A:8),h&&(h.textContent=m.value),m.addEventListener("input",()=>{var L,P;h&&(h.textContent=m.value),(P=(L=this.options)==null?void 0:L.onUpdateLoading)==null||P.call(L,{blur_strength:Number(m.value)})}));let f=(x=this.root)==null?void 0:x.querySelector("#loading-show-btn"),b=(I=this.root)==null?void 0:I.querySelector("#loading-hide-btn");f==null||f.addEventListener("click",()=>{var L,P;(P=(L=this.options)==null?void 0:L.onShowLoadingScreen)==null||P.call(L)}),b==null||b.addEventListener("click",()=>{var L,P;(P=(L=this.options)==null?void 0:L.onHideLoadingScreen)==null||P.call(L)}),this.updateFieldVisibility(i.type==="image"?"image":"color")}updateFieldVisibility(e){var i,a;let t=(i=this.root)==null?void 0:i.querySelector("#loading-color-field"),n=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),n&&(n.style.display="none")):(t&&(t.style.display=""),n&&(n.style.display=""))}refresh(){}};var Pt=require("pixi.js");nt();J();async function as(r,e,t){var n,i;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let a=Date.now(),o=`/${`raw/library/${e}/${t}`}?t=${a}`;console.log("[LIBRARY] Loading texture from:",o);let l=await Pt.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load texture:",o);return}let c=window.CustomAssets,p=Object.keys(c||{}).filter(u=>{let g=e.replace(/s$/,"");return u.startsWith(g)||u.includes(g)});for(let u of p)le[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(n=c[u])!=null&&n.texture&&(c[u].texture=l,console.log("[LIBRARY] \u2705 Updated CustomAssets."+u+".texture"));let d=window.gameObjectManager;if(d)for(let u of p){let g=d.get(u);if(g){let m=((i=g.getDisplayObject)==null?void 0:i.call(g))||g.pixiObject||g;m!=null&&m.texture&&(m.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(a){console.error("[LIBRARY] Error applying asset change:",a)}}async function rs(r,e){var t,n,i;console.log("[LIBRARY] resetAsset called for:",e);try{let a=window.getEditableAssets,s=typeof a=="function"?a():null,o=(t=s==null?void 0:s.slots)==null?void 0:t.find(f=>f.category===e),l=o==null?void 0:o.defaultAsset;if(!l){console.warn("[LIBRARY] Could not find default asset for:",e);return}let c=Date.now(),p=`/raw/${l}?t=${c}`;console.log("[LIBRARY] Loading default texture from:",p);let d=await Pt.Assets.load(p);if(!d){console.error("[LIBRARY] Failed to load default texture:",p);return}let u=window.CustomAssets,g=e.replace(/s$/,""),m=Object.keys(u||{}).filter(f=>f.startsWith(g)||f.includes(g));for(let f of m)le[f]=d,console.log("[LIBRARY] \u2705 Reset AssetTextures."+f),(n=u[f])!=null&&n.texture&&(u[f].texture=d,console.log("[LIBRARY] \u2705 Reset CustomAssets."+f+" to default"));let h=window.gameObjectManager;if(h)for(let f of m){let b=h.get(f);if(b){let y=((i=b.getDisplayObject)==null?void 0:i.call(b))||b.pixiObject||b;y!=null&&y.texture&&(y.texture=d,console.log("[LIBRARY] \u2705 Reset display object:",f))}}}catch(a){console.error("[LIBRARY] Error resetting asset:",a)}}async function ss(r,e,t,n){var i,a,s,o,l,c,p,d,u,g,m,h,f,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:n});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let w=Date.now(),E=`/raw/library/${n}/${t}?t=${w}`;console.log("[LIBRARY] Loading texture from:",E);let j=await Pt.Assets.load(E);if(!j){console.error("[LIBRARY] Failed to load texture:",E);return}console.log("[LIBRARY] \u2705 Texture loaded"),le[v]=j,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let z=window.CustomAssets;z!=null&&z[v]&&(z[v].texture=j,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let S=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!S),S){let R=Array.from(((i=S.keys)==null?void 0:i.call(S))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",R);let T=S.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!T),T){let C=((a=T.getDisplayObject)==null?void 0:a.call(T))||T.pixiObject||T.pixi||T,M=(s=C==null?void 0:C.constructor)==null?void 0:s.name;if(console.log("[LIBRARY] displayObject:",C),console.log("[LIBRARY] displayObject type:",M),console.log("[LIBRARY] has texture?",!!(C!=null&&C.texture)),C!=null&&C.texture)C.texture=j,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(M==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:k}=await import("pixi.js"),A=C.parent,x=(l=(o=A==null?void 0:A.getChildIndex)==null?void 0:o.call(A,C))!=null?l:0,I={x:C.x,y:C.y},L={x:(p=(c=C.anchor)==null?void 0:c.x)!=null?p:.5,y:(u=(d=C.anchor)==null?void 0:d.y)!=null?u:.5},P={x:(m=(g=C.scale)==null?void 0:g.x)!=null?m:1,y:(f=(h=C.scale)==null?void 0:h.y)!=null?f:1},O=(b=C.alpha)!=null?b:1,H=(y=C.visible)!=null?y:!0,N=new k(j);N.anchor.set(L.x,L.y),N.position.set(I.x,I.y),N.scale.set(P.x,P.y),N.alpha=O,N.visible=H,A&&(A.removeChild(C),A.addChildAt(N,x),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),T.pixiObject&&(T.pixiObject=N),T.pixi&&(T.pixi=N),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(C!=null&&C.children){let k=C.children.find(A=>A.texture);k?(k.texture=j,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let _=`raw/library/${n}/${t}`;ce({objectId:v,path:"render.asset.path",value:_}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",_)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function os(r,e,t,n){var i;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:n});try{let a=e.startsWith("json.")?e.replace("json.",""):e,s=Date.now(),o=`/raw/${t}?t=${s}`;console.log("[LIBRARY] Loading default texture from:",o);let l=await Pt.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load default texture:",o);return}le[a]=l,console.log("[LIBRARY] \u2705 Reset AssetTextures."+a);let c=window.CustomAssets;c!=null&&c[a]&&(c[a].texture=l,console.log("[LIBRARY] \u2705 Reset CustomAssets."+a+" to default"));let p=window.gameObjectManager;if(p){let d=p.get(a);if(d){let u=((i=d.getDisplayObject)==null?void 0:i.call(d))||d.pixiObject||d;u!=null&&u.texture&&(u.texture=l,console.log("[LIBRARY] \u2705 Reset display object:",a))}}ce({objectId:a,path:"render.asset.path",value:t}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}var zt=require("pixi.js");var ta=require("pixi.js"),Pe=()=>window.debugConfig||{},ls=()=>window.resolveAnchorVec2||(r=>({x:.5,y:.5})),cs=()=>window.resolveScreenAnchorPoint||(()=>new ta.Point),ds=()=>window.resolveScreenRatioPoint||(()=>new ta.Point);function ps(r){Yn(r)&&(r.objectDebugRaf||(r.objectDebugRaf=window.requestAnimationFrame(()=>Kn(r))))}function us(r){r.objectDebugRaf&&(window.cancelAnimationFrame(r.objectDebugRaf),r.objectDebugRaf=null),Rt(r)}function Yn(r){return r.isDebugOpen}function Kn(r){var a,s,o;if(!Yn(r)){r.objectDebugRaf=null;return}r.objectDebugRaf=window.requestAnimationFrame(()=>Kn(r));let e=na(r);if(!e){Ot(r,null),Rt(r);return}let t=ia(r,e);if(!t){Ot(r,null),Rt(r);return}let n=new zt.Point;(a=t.getGlobalPosition)==null||a.call(t,n);let i=aa(r,t);Ot(r,{instanceId:e,worldX:n.x,worldY:n.y,configX:(s=i==null?void 0:i.x)!=null?s:null,configY:(o=i==null?void 0:i.y)!=null?o:null}),r.highlightObject?la(r,t):da(r),r.highlightAnchor&&i?ca(r,i):pa(r)}function na(r){var i;let e=r.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return Array.isArray(n)&&n.length>0?n[0]:e}function ia(r,e){var i,a;let t=window.gameObjectManager,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return n?((a=n.getDisplayObject)==null?void 0:a.call(n))||n.pixiObject||n:null}function $t(r){let e=r.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function aa(r,e){var s,o;let t=$t(r);if(!t)return null;let n=(s=t.transform)!=null?s:{},i=ra(r);if(!i)return null;if(n.position_ratio!=null)return ds()(i.width,i.height,n.position_ratio);let a=(o=n.anchor)!=null?o:"center";return cs()(i.width,i.height,a)}function ra(r){var a;let e=(a=r.container)==null?void 0:a.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),n=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(n)&&n>0)return{width:t,height:n};let i=window.gameApp;return i!=null&&i.renderer?{width:i.renderer.width,height:i.renderer.height}:null}function sa(r){let e=window.gameApp;return e!=null&&e.stage?(r.objectBoundsGfx&&r.objectBoundsGfx.parent!==e.stage&&(r.objectBoundsGfx.destroy(),r.objectBoundsGfx=null),r.objectBoundsGfx||(r.objectBoundsGfx=new zt.Graphics,r.objectBoundsGfx.zIndex=999999,e.stage.addChild(r.objectBoundsGfx)),r.objectBoundsGfx):null}function oa(r){let e=window.gameApp;return e!=null&&e.stage?(r.objectAnchorGfx&&r.objectAnchorGfx.parent!==e.stage&&(r.objectAnchorGfx.destroy(),r.objectAnchorGfx=null),r.objectAnchorGfx||(r.objectAnchorGfx=new zt.Graphics,r.objectAnchorGfx.zIndex=1e6,e.stage.addChild(r.objectAnchorGfx)),r.objectAnchorGfx):null}function la(r,e){var i;let t=sa(r);if(!t)return;let n=(i=e.getBounds)==null?void 0:i.call(e);n&&(t.clear(),t.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function ca(r,e){let t=oa(r);if(!t)return;let n=6;t.clear(),t.moveTo(e.x-n,e.y),t.lineTo(e.x+n,e.y),t.moveTo(e.x,e.y-n),t.lineTo(e.x,e.y+n),t.stroke({width:2,color:3066993,alpha:.9})}function da(r){r.objectBoundsGfx&&r.objectBoundsGfx.clear()}function pa(r){r.objectAnchorGfx&&r.objectAnchorGfx.clear()}function Rt(r){r.objectBoundsGfx&&(r.objectBoundsGfx.destroy(),r.objectBoundsGfx=null),r.objectAnchorGfx&&(r.objectAnchorGfx.destroy(),r.objectAnchorGfx=null)}function Ot(r,e){r.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function gs(r,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,r)}function hs(r,e,t){var s;let n=e.split("."),i=n.pop(),a=r;for(let o of n)a[o]=(s=a[o])!=null?s:{},a=a[o];a[i]=t}function ua(r){var n,i,a,s,o;if(!r)return!1;if((n=r.transform)!=null&&n.offset)return!0;let e=((a=(i=r.identity)==null?void 0:i.category)!=null?a:"").toString().toLowerCase(),t=((o=(s=r.identity)==null?void 0:s.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function Jn(r){let e=Pe();e.layout&&(e.layout.scale_multiplier=1,e.layout.position_offset={x:0,y:0},e.layout.debug_rect_visible=!0,e.layout.debug_rect_color=16711680,e.layout.debug_rect_thickness=4),e.engine&&(e.engine.scale=1,e.engine.background_scale=1.05,e.engine.label_pulse_speed=3,e.engine.label_pulse_intensity=.03),e.physics&&(e.physics.rope_length=420),window.location.reload()}function fs(r){window.location.reload()}function Zn(r){let e=JSON.stringify(Pe(),null,2);navigator.clipboard.writeText(e).then(()=>{alert("Debug config copied to clipboard!")}).catch(()=>{console.log(e),alert("Config logged to console (clipboard not available)")})}async function ms(r,e){var t,n,i;if(!(!r.configViewer||!r.container))try{let a=window.getEditableObjectConfig,s=typeof a=="function"?a(e):null;if(!s){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(wn(),Nr)),d=(((t=(await o("scene.main")).scene)==null?void 0:t.objects)||[]).find(g=>g.object_config===e||g.instance_id===e);if(!d)return;let u=await l(d.object_config);console.log("[PREVIEW] Loaded object config (fallback)",e,u),Xn(r,u),(n=r.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,s),Xn(r,s),(i=r.configViewer)==null||i.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function Xn(r,e){var d,u,g,m,h,f,b,y,v,w;if(!r.container)return;let t=r.container.querySelector("#config-pos-x"),n=r.container.querySelector("#config-pos-y"),i=r.container.querySelector("#config-scale"),a=r.container.querySelector("#config-anchor-x"),s=r.container.querySelector("#config-anchor-y"),l=ua(e)?(d=e.transform)==null?void 0:d.offset:(u=e.transform)==null?void 0:u.position;t&&(t.value=String((g=l==null?void 0:l.x)!=null?g:0)),n&&(n.value=String((m=l==null?void 0:l.y)!=null?m:0)),i&&(i.value=String((f=(h=e.transform)==null?void 0:h.scale)!=null?f:1));let c=(w=(v=(b=e.transform)==null?void 0:b.anchor)!=null?v:(y=e.render)==null?void 0:y.anchor)!=null?w:{x:.5,y:.5},p=ls()(c);a&&(a.value=String(p.x)),s&&(s.value=String(p.y))}function bs(r){var l,c,p,d,u,g,m,h,f,b;let e=r.selectedObjectId;if(!e||!r.container)return;let t=(c=(l=r.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",n=(d=(p=r.container.querySelector("#config-pos-y"))==null?void 0:p.value)!=null?d:"0",i=(g=(u=r.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",a=(h=(m=r.container.querySelector("#config-anchor-x"))==null?void 0:m.value)!=null?h:"0.5",s=(b=(f=r.container.querySelector("#config-anchor-y"))==null?void 0:f.value)!=null?b:"0.5",o=`${e}:
|
|
1641
1692
|
position: (${t}, ${n})
|
|
1642
1693
|
scale: ${i}
|
|
1643
|
-
anchor: (${a}, ${s})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(y=>console.error("[DEBUG] Failed to copy config values:",y))}async function ua(r,e){var d,u,g,m,h,f,b,y,v,S,C;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!r.container)return;let t=r.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((u=(d=r.container.querySelector("#config-pos-x"))==null?void 0:d.value)!=null?u:0),i=Number((m=(g=r.container.querySelector("#config-pos-y"))==null?void 0:g.value)!=null?m:0),a=Number((f=(h=r.container.querySelector("#config-scale"))==null?void 0:h.value)!=null?f:1),s=Number((y=(b=r.container.querySelector("#config-anchor-x"))==null?void 0:b.value)!=null?y:.5),o=Number((S=(v=r.container.querySelector("#config-anchor-y"))==null?void 0:v.value)!=null?S:.5);console.log("[INSPECTOR] Applying config for:",t,{posX:n,posY:i,scale:a,anchorX:s,anchorY:o});let{applyConfigOverride:l}=await Promise.resolve().then(()=>(X(),He));l({objectId:t,path:"transform.position",value:{x:n,y:i}},{silent:e==null?void 0:e.silent}),l({objectId:t,path:"transform.scale",value:a},{silent:e==null?void 0:e.silent}),l({objectId:t,path:"transform.anchor",value:{x:s,y:o}},{silent:e==null?void 0:e.silent});let c=Ot(r);pa(c)&&l({objectId:t,path:"transform.offset",value:{x:n,y:i}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let p=window.applyEditableObjectConfig;if(typeof p=="function"){let k=(C=window.getEditableObjectConfig)==null?void 0:C.call(window,t);k?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",t),p(t,k)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",t)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function ys(r,e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(X(),He));Object.entries(e.assets).forEach(([l,c])=>{n({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{n({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{n({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{n({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{n({path:`runtime.audio.${l}`,value:c},{silent:!0})});let i=window.applyEditableEngineConfig;if(typeof i=="function"){let l={theme:e.runtime.theme,fonts:e.runtime.fonts,audio:e.runtime.audio},c={};Object.entries(e.runtime.ui).forEach(([p,d])=>{var u;if(p)if(p.includes(".")){let g=p.split("."),m=c;for(let h=0;h<g.length-1;h++){let f=g[h];m[f]=(u=m[f])!=null?u:{},m=m[f]}m[g[g.length-1]]=d}else c[p]=d}),l.ui=c,i({runtime:l,assets:e.assets})}let a=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),s=(t==null?void 0:t.source)!=="auto"&&!a,o=window.__previewShell;s&&(o!=null&&o.refresh)&&o.refresh()}function vs(r){r.selectedObjectId&&(r.objectAutoApplyTimer&&window.clearTimeout(r.objectAutoApplyTimer),r.objectAutoApplyTimer=window.setTimeout(()=>{r.objectAutoApplyTimer=null,ua(r,{silent:!0})},150))}var sl=3e3;function Rt(r,e,t){let n=t!=null?t:r.offsetParent;if(!n)return;e.style.cursor="move";let i=!1,a=0,s=0,o=0,l=0,c=0,p=0,d=g=>{if(!i)return;let m=n.getBoundingClientRect();r.style.left=`${g.clientX-m.left-c}px`,r.style.top=`${g.clientY-m.top-p}px`},u=()=>{i&&(i=!1,r.classList.remove("dragging"),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",u))};e.addEventListener("pointerdown",g=>{if(g.button!==0)return;let m=g.target;if(m!=null&&m.closest("button, input, select, textarea"))return;g.preventDefault();let h=r.getBoundingClientRect(),f=n.getBoundingClientRect();console.log("[DRAG] Panel:",r.className),console.log("[DRAG] Container:",n.className),console.log("[DRAG] panelRect:",{left:h.left,top:h.top,width:h.width,height:h.height}),console.log("[DRAG] containerRect:",{left:f.left,top:f.top,width:f.width,height:f.height}),console.log("[DRAG] mouse:",{x:g.clientX,y:g.clientY}),c=g.clientX-h.left,p=g.clientY-h.top,console.log("[DRAG] offset:",{x:c,y:p});let b=h.left-f.left,y=h.top-f.top;console.log("[DRAG] targetPosition:",{left:b,top:y}),r.style.left=`${b}px`,r.style.top=`${y}px`,r.style.right="auto",r.style.bottom="auto",r.style.zIndex=String(++sl),i=!0,r.classList.add("dragging"),window.addEventListener("pointermove",d),window.addEventListener("pointerup",u)})}function ws(r,e,t,n=280,i=200){e.style.cursor="nwse-resize";let a=0,s=0,o=0,l=0,c=!1,p=u=>{var y;if(!c)return;let g=u.clientX-o,m=u.clientY-l,h=Math.max(n,a+g),f=Math.max(i,s+m);r.style.width=`${h}px`,(y=r.closest(".preview-shell"))!=null&&y.classList.contains("layout-fixed")||(r.style.height=`${f}px`),t==null||t(h,f)},d=()=>{c&&(c=!1,window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d))};e.addEventListener("pointerdown",u=>{if(u.button!==0)return;u.preventDefault(),u.stopPropagation();let g=r.getBoundingClientRect();a=g.width,s=g.height,o=u.clientX,l=u.clientY,c=!0,window.addEventListener("pointermove",p),window.addEventListener("pointerup",d)})}function ga(r,e){var h,f,b,y;let t=(b=(f=(h=r.container)==null?void 0:h.querySelector("#debug-overlay"))!=null?f:r.debugOverlay)!=null?b:e.offsetParent;if(!t||(y=r.container)!=null&&y.classList.contains("layout-fixed"))return;let n=t.getBoundingClientRect(),i=e.getBoundingClientRect(),a=12,s=Math.max(250,Math.floor(n.width-a*2)),o=Math.max(200,Math.floor(n.height-a*2));i.width>s&&(e.style.width=`${s}px`),i.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-n.left,p=l.top-n.top,d=Math.max(a,n.width-l.width-a),u=Math.max(a,n.height-l.height-a),g=Math.min(Math.max(c,a),d),m=Math.min(Math.max(p,a),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(m)}px`,e.style.right="auto",e.style.bottom="auto"}function at(r){var n,i;if(!r.container)return;let e=r.container.querySelector("#debug-workbench");if(!e)return;if(ga(r,e),(n=r.container)!=null&&n.classList.contains("layout-fixed")){let a=localStorage.getItem("preview_workbench_state"),s={activeTab:r.activeTab};if(a)try{s={...JSON.parse(a),activeTab:r.activeTab}}catch{}localStorage.setItem("preview_workbench_state",JSON.stringify(s));return}let t={activeTab:r.activeTab,width:e.style.width,height:(i=r.container)!=null&&i.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function Jn(r){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(r.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var i,a;let n=(i=r.container)==null?void 0:i.querySelector("#debug-workbench");if(n){let s=(a=r.container)==null?void 0:a.classList.contains("layout-fixed");t.width&&(n.style.width=t.width),t.height&&!s?n.style.height=t.height:s&&(n.style.height=""),t.left&&(n.style.left=t.left,n.style.right="auto"),t.top&&(n.style.top=t.top,n.style.bottom="auto"),ga(r,n)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function ha(r,e){let t=e.getBoundingClientRect();(t.left<0||t.top<0||t.right>window.innerWidth||t.bottom>window.innerHeight)&&(console.warn("[Workbench] Workbench positioned outside viewport, repositioning..."),e.style.left="16px",e.style.top="72px",e.style.right="auto",e.style.bottom="auto",ga(r,e),at(r))}function xs(r){var i,a,s;if(!r.container)return;let e=r.container,t=e.querySelector("#debug-toggle");t||console.warn("[PREVIEW] Debug toggle not found in DOM"),t==null||t.addEventListener("click",()=>{var o;console.log("[PREVIEW] Debug toggle clicked"),(o=r.toggleDebug)==null||o.call(r)}),(i=e.querySelector("#debug-close"))==null||i.addEventListener("click",()=>{var o;return(o=r.toggleDebug)==null?void 0:o.call(r,!1)}),(a=e.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>Kn(r)),(s=e.querySelector("#debug-export"))==null||s.addEventListener("click",()=>Xn(r)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;r.activeTab=l,fa(r),at(r)})}),ba(r,e),ma(r,e)}function fa(r){if(!r.container)return;let e=r.container;e.querySelectorAll(".workbench-tab").forEach(i=>{let a=i.dataset.tab;i.classList.toggle("active",a===r.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(i=>{let a=i.dataset.tabPanel;i.classList.toggle("active",a===r.activeTab)})}function ma(r,e){ae(r,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),ae(r,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),ae(r,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),ae(r,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),ae(r,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),ae(r,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),ae(r,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),ae(r,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),ae(r,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let i=Me();i.layout&&(i.layout.debug_rect_visible=!!t.checked)});let n=e.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let i=n.value.replace("#",""),a=parseInt(i,16),s=Me();s.layout&&(s.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function Es(r){if(!r.container||!r.debugOverlay)return;let e=r.container.querySelector("#debug-workbench"),t=r.container.querySelector("#workbench-handle");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),Rt(e,t,r.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{at(r),ha(r,e)},10)}));let n=r.container.querySelector('[data-panel="scene-objects"]'),i=n==null?void 0:n.querySelector("[data-panel-handle]"),a=n==null?void 0:n.querySelector("[data-panel-resize-v]");n&&i&&(!n.style.left&&!n.style.right&&!n.style.top&&!n.style.bottom&&(n.style.left="16px",n.style.top="72px"),Rt(n,i,r.debugOverlay),i.addEventListener("pointerup",()=>{setTimeout(()=>{ha(r,n)},10)})),n&&a&&ws(n,a);let s=r.container.querySelector('[data-panel="scene-tools-corner"]'),o=s==null?void 0:s.querySelector("[data-panel-handle]");s&&o&&Rt(s,o,r.debugOverlay);let l=r.container.querySelector('[data-panel="nudge-panel"]'),c=l==null?void 0:l.querySelector("[data-panel-handle]");l&&c&&Rt(l,c,r.debugOverlay),Jn(r)}function ba(r,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let i=n.closest(".scene-panel");i&&i.classList.toggle("collapsed")})})}function ae(r,e,t,n,i){let a=e.querySelector(`#${t}`),s=e.querySelector(i);if(!a||!s)return;let o=gs(Me(),n);typeof o=="number"&&(a.value=String(o),s.textContent=String(o)),a.addEventListener("input",()=>{let l=Number(a.value);s.textContent=String(l),hs(Me(),n,l)})}X();var Zn=class{constructor(){this.container=null;this.currentVersion=null;this.availableVersions=[];this.isDevelopmentMode=!1}async initialize(e){this.container=e,this.isDevelopmentMode=typeof window!="undefined"&&document.querySelector('script[type="module"][src*="/@vite/"]')!==null,await this.loadVersionsList(),window.addEventListener("config:changed",()=>{this.refreshPanel()}),this.refreshPanel()}render(){let e=Te(),{hasChanges:t,overrideCount:n,overrides:i}=e,a={};for(let p of i){let d=p.objectId||"Engine";a[d]||(a[d]=[]),a[d].push(p)}let s=localStorage.getItem("handler_last_applied"),o=s?new Date(parseInt(s)).toLocaleString():"Never",l=this.currentVersion?`Version: ${this.currentVersion} (Active)`:"Original",c=this.currentVersion?`Versioned (${this.currentVersion})`:"Global";return`
|
|
1694
|
+
anchor: (${a}, ${s})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(y=>console.error("[DEBUG] Failed to copy config values:",y))}async function ga(r,e){var d,u,g,m,h,f,b,y,v,w,E;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!r.container)return;let t=r.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((u=(d=r.container.querySelector("#config-pos-x"))==null?void 0:d.value)!=null?u:0),i=Number((m=(g=r.container.querySelector("#config-pos-y"))==null?void 0:g.value)!=null?m:0),a=Number((f=(h=r.container.querySelector("#config-scale"))==null?void 0:h.value)!=null?f:1),s=Number((y=(b=r.container.querySelector("#config-anchor-x"))==null?void 0:b.value)!=null?y:.5),o=Number((w=(v=r.container.querySelector("#config-anchor-y"))==null?void 0:v.value)!=null?w:.5);console.log("[INSPECTOR] Applying config for:",t,{posX:n,posY:i,scale:a,anchorX:s,anchorY:o});let{applyConfigOverride:l}=await Promise.resolve().then(()=>(J(),Be));l({objectId:t,path:"transform.position",value:{x:n,y:i}},{silent:e==null?void 0:e.silent}),l({objectId:t,path:"transform.scale",value:a},{silent:e==null?void 0:e.silent}),l({objectId:t,path:"transform.anchor",value:{x:s,y:o}},{silent:e==null?void 0:e.silent});let c=$t(r);ua(c)&&l({objectId:t,path:"transform.offset",value:{x:n,y:i}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let p=window.applyEditableObjectConfig;if(typeof p=="function"){let j=(E=window.getEditableObjectConfig)==null?void 0:E.call(window,t);j?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",t),p(t,j)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",t)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function ys(r,e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(J(),Be));Object.entries(e.assets).forEach(([l,c])=>{n({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{n({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{n({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{n({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{n({path:`runtime.audio.${l}`,value:c},{silent:!0})});let i=window.applyEditableEngineConfig;if(typeof i=="function"){let l={theme:e.runtime.theme,fonts:e.runtime.fonts,audio:e.runtime.audio},c={};Object.entries(e.runtime.ui).forEach(([p,d])=>{var u;if(p)if(p.includes(".")){let g=p.split("."),m=c;for(let h=0;h<g.length-1;h++){let f=g[h];m[f]=(u=m[f])!=null?u:{},m=m[f]}m[g[g.length-1]]=d}else c[p]=d}),l.ui=c,i({runtime:l,assets:e.assets})}let a=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),s=(t==null?void 0:t.source)!=="auto"&&!a,o=window.__previewShell;s&&(o!=null&&o.refresh)&&o.refresh()}function vs(r){r.selectedObjectId&&(r.objectAutoApplyTimer&&window.clearTimeout(r.objectAutoApplyTimer),r.objectAutoApplyTimer=window.setTimeout(()=>{r.objectAutoApplyTimer=null,ga(r,{silent:!0})},150))}var sl=3e3;function Dt(r,e,t){let n=t!=null?t:r.offsetParent;if(!n)return;e.style.cursor="move";let i=!1,a=0,s=0,o=0,l=0,c=0,p=0,d=g=>{if(!i)return;let m=n.getBoundingClientRect();r.style.left=`${g.clientX-m.left-c}px`,r.style.top=`${g.clientY-m.top-p}px`},u=()=>{i&&(i=!1,r.classList.remove("dragging"),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",u))};e.addEventListener("pointerdown",g=>{if(g.button!==0)return;let m=g.target;if(m!=null&&m.closest("button, input, select, textarea"))return;g.preventDefault();let h=r.getBoundingClientRect(),f=n.getBoundingClientRect();console.log("[DRAG] Panel:",r.className),console.log("[DRAG] Container:",n.className),console.log("[DRAG] panelRect:",{left:h.left,top:h.top,width:h.width,height:h.height}),console.log("[DRAG] containerRect:",{left:f.left,top:f.top,width:f.width,height:f.height}),console.log("[DRAG] mouse:",{x:g.clientX,y:g.clientY}),c=g.clientX-h.left,p=g.clientY-h.top,console.log("[DRAG] offset:",{x:c,y:p});let b=h.left-f.left,y=h.top-f.top;console.log("[DRAG] targetPosition:",{left:b,top:y}),r.style.left=`${b}px`,r.style.top=`${y}px`,r.style.right="auto",r.style.bottom="auto",r.style.zIndex=String(++sl),i=!0,r.classList.add("dragging"),window.addEventListener("pointermove",d),window.addEventListener("pointerup",u)})}function ws(r,e,t,n=280,i=200){e.style.cursor="nwse-resize";let a=0,s=0,o=0,l=0,c=!1,p=u=>{var y;if(!c)return;let g=u.clientX-o,m=u.clientY-l,h=Math.max(n,a+g),f=Math.max(i,s+m);r.style.width=`${h}px`,(y=r.closest(".preview-shell"))!=null&&y.classList.contains("layout-fixed")||(r.style.height=`${f}px`),t==null||t(h,f)},d=()=>{c&&(c=!1,window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d))};e.addEventListener("pointerdown",u=>{if(u.button!==0)return;u.preventDefault(),u.stopPropagation();let g=r.getBoundingClientRect();a=g.width,s=g.height,o=u.clientX,l=u.clientY,c=!0,window.addEventListener("pointermove",p),window.addEventListener("pointerup",d)})}function ha(r,e){var h,f,b,y;let t=(b=(f=(h=r.container)==null?void 0:h.querySelector("#debug-overlay"))!=null?f:r.debugOverlay)!=null?b:e.offsetParent;if(!t||(y=r.container)!=null&&y.classList.contains("layout-fixed"))return;let n=t.getBoundingClientRect(),i=e.getBoundingClientRect(),a=12,s=Math.max(250,Math.floor(n.width-a*2)),o=Math.max(200,Math.floor(n.height-a*2));i.width>s&&(e.style.width=`${s}px`),i.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-n.left,p=l.top-n.top,d=Math.max(a,n.width-l.width-a),u=Math.max(a,n.height-l.height-a),g=Math.min(Math.max(c,a),d),m=Math.min(Math.max(p,a),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(m)}px`,e.style.right="auto",e.style.bottom="auto"}function st(r){var n,i;if(!r.container)return;let e=r.container.querySelector("#debug-workbench");if(!e)return;if(ha(r,e),(n=r.container)!=null&&n.classList.contains("layout-fixed")){let a=localStorage.getItem("preview_workbench_state"),s={activeTab:r.activeTab};if(a)try{s={...JSON.parse(a),activeTab:r.activeTab}}catch{}localStorage.setItem("preview_workbench_state",JSON.stringify(s));return}let t={activeTab:r.activeTab,width:e.style.width,height:(i=r.container)!=null&&i.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function Qn(r){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(r.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var i,a;let n=(i=r.container)==null?void 0:i.querySelector("#debug-workbench");if(n){let s=(a=r.container)==null?void 0:a.classList.contains("layout-fixed");t.width&&(n.style.width=t.width),t.height&&!s?n.style.height=t.height:s&&(n.style.height=""),t.left&&(n.style.left=t.left,n.style.right="auto"),t.top&&(n.style.top=t.top,n.style.bottom="auto"),ha(r,n)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function fa(r,e){let t=e.getBoundingClientRect();(t.left<0||t.top<0||t.right>window.innerWidth||t.bottom>window.innerHeight)&&(console.warn("[Workbench] Workbench positioned outside viewport, repositioning..."),e.style.left="16px",e.style.top="72px",e.style.right="auto",e.style.bottom="auto",ha(r,e),st(r))}function xs(r){var i,a,s;if(!r.container)return;let e=r.container,t=e.querySelector("#debug-toggle");t||console.warn("[PREVIEW] Debug toggle not found in DOM"),t==null||t.addEventListener("click",()=>{var o;console.log("[PREVIEW] Debug toggle clicked"),(o=r.toggleDebug)==null||o.call(r)}),(i=e.querySelector("#debug-close"))==null||i.addEventListener("click",()=>{var o;return(o=r.toggleDebug)==null?void 0:o.call(r,!1)}),(a=e.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>Jn(r)),(s=e.querySelector("#debug-export"))==null||s.addEventListener("click",()=>Zn(r)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;r.activeTab=l,ma(r),st(r)})}),ya(r,e),ba(r,e)}function ma(r){if(!r.container)return;let e=r.container;e.querySelectorAll(".workbench-tab").forEach(i=>{let a=i.dataset.tab;i.classList.toggle("active",a===r.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(i=>{let a=i.dataset.tabPanel;i.classList.toggle("active",a===r.activeTab)})}function ba(r,e){re(r,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),re(r,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),re(r,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),re(r,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),re(r,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),re(r,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),re(r,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),re(r,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),re(r,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let i=Pe();i.layout&&(i.layout.debug_rect_visible=!!t.checked)});let n=e.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let i=n.value.replace("#",""),a=parseInt(i,16),s=Pe();s.layout&&(s.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function Es(r){if(!r.container||!r.debugOverlay)return;let e=r.container.querySelector("#debug-workbench"),t=r.container.querySelector("#workbench-handle");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),Dt(e,t,r.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{st(r),fa(r,e)},10)}));let n=r.container.querySelector('[data-panel="scene-objects"]'),i=n==null?void 0:n.querySelector("[data-panel-handle]"),a=n==null?void 0:n.querySelector("[data-panel-resize-v]");n&&i&&(!n.style.left&&!n.style.right&&!n.style.top&&!n.style.bottom&&(n.style.left="16px",n.style.top="72px"),Dt(n,i,r.debugOverlay),i.addEventListener("pointerup",()=>{setTimeout(()=>{fa(r,n)},10)})),n&&a&&ws(n,a);let s=r.container.querySelector('[data-panel="scene-tools-corner"]'),o=s==null?void 0:s.querySelector("[data-panel-handle]");s&&o&&Dt(s,o,r.debugOverlay);let l=r.container.querySelector('[data-panel="nudge-panel"]'),c=l==null?void 0:l.querySelector("[data-panel-handle]");l&&c&&Dt(l,c,r.debugOverlay),Qn(r)}function ya(r,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let i=n.closest(".scene-panel");i&&i.classList.toggle("collapsed")})})}function re(r,e,t,n,i){let a=e.querySelector(`#${t}`),s=e.querySelector(i);if(!a||!s)return;let o=gs(Pe(),n);typeof o=="number"&&(a.value=String(o),s.textContent=String(o)),a.addEventListener("input",()=>{let l=Number(a.value);s.textContent=String(l),hs(Pe(),n,l)})}J();var ei=class{constructor(){this.container=null;this.currentVersion=null;this.availableVersions=[];this.isDevelopmentMode=!1}async initialize(e){this.container=e,this.isDevelopmentMode=typeof window!="undefined"&&document.querySelector('script[type="module"][src*="/@vite/"]')!==null,await this.loadVersionsList(),window.addEventListener("config:changed",()=>{this.refreshPanel()}),this.refreshPanel()}render(){let e=Ie(),{hasChanges:t,overrideCount:n,overrides:i}=e,a={};for(let p of i){let d=p.objectId||"Engine";a[d]||(a[d]=[]),a[d].push(p)}let s=localStorage.getItem("handler_last_applied"),o=s?new Date(parseInt(s)).toLocaleString():"Never",l=this.currentVersion?`Version: ${this.currentVersion} (Active)`:"Original",c=this.currentVersion?`Versioned (${this.currentVersion})`:"Global";return`
|
|
1644
1695
|
<div class="config-persistence-panel">
|
|
1645
1696
|
<!-- Status Footer (Always Visible) -->
|
|
1646
1697
|
<div class="persistence-status-footer">
|
|
@@ -1792,17 +1843,17 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1792
1843
|
<p class="info-hint"><strong>Version Switching:</strong> Always clears overrides and reloads from selected Source.</p>
|
|
1793
1844
|
</div>
|
|
1794
1845
|
</div>
|
|
1795
|
-
`}formatValue(e){return e===null?"null":typeof e=="string"?e.length>25?e.substring(0,22)+"...":e:typeof e=="object"?"{...}":String(e)}setupEventListeners(){if(!this.container)return;let e=this.container.querySelector("#create-version-btn");e==null||e.addEventListener("click",async()=>{var g;if(e.getAttribute("disabled")!==null)return;if(!
|
|
1846
|
+
`}formatValue(e){return e===null?"null":typeof e=="string"?e.length>25?e.substring(0,22)+"...":e:typeof e=="object"?"{...}":String(e)}setupEventListeners(){if(!this.container)return;let e=this.container.querySelector("#create-version-btn");e==null||e.addEventListener("click",async()=>{var g;if(e.getAttribute("disabled")!==null)return;if(!Ie().hasChanges){alert("No changes to save. Make some edits first.");return}if(confirm(`Save As New Version?
|
|
1796
1847
|
|
|
1797
1848
|
This will:
|
|
1798
1849
|
\u2022 Create a new version snapshot
|
|
1799
1850
|
\u2022 Include all current changes
|
|
1800
1851
|
\u2022 Clear staged overrides after save
|
|
1801
|
-
\u2022 Set the new version as active`))try{let m=localStorage.getItem("handler_last_version_name")||"",f=((g=prompt("Version name (e.g. v1.2.0, test_2024):",m))!=null?g:"").trim();if(!f){alert("Version name is required.");return}localStorage.setItem("handler_last_version_name",f),e.textContent="\u23F3 Creating version...",e.setAttribute("disabled","true"),await
|
|
1852
|
+
\u2022 Set the new version as active`))try{let m=localStorage.getItem("handler_last_version_name")||"",f=((g=prompt("Version name (e.g. v1.2.0, test_2024):",m))!=null?g:"").trim();if(!f){alert("Version name is required.");return}localStorage.setItem("handler_last_version_name",f),e.textContent="\u23F3 Creating version...",e.setAttribute("disabled","true"),await hn(f),ne(),this.showSuccessNotification("Version created and set as active"),await this.loadVersionsList(),this.refreshPanel()}catch(m){console.error("[ConfigPersistence] Create version failed:",m),alert(`\u274C Failed to create version: ${m.message}`),e.textContent="\u{1F4DD} SAVE AS NEW VERSION",e.removeAttribute("disabled")}});let t=this.container.querySelector("#apply-current-btn");t==null||t.addEventListener("click",async()=>{if(t.getAttribute("disabled")!==null)return;let d=this.currentVersion?`version "${this.currentVersion}"`:"Original configs";if(confirm(`Apply to Current Source?
|
|
1802
1853
|
|
|
1803
1854
|
This will write all staged changes to ${d}.
|
|
1804
1855
|
|
|
1805
|
-
After applying, staged overrides will be cleared.`))try{t.textContent="\u23F3 Applying...",t.setAttribute("disabled","true");let g=
|
|
1856
|
+
After applying, staged overrides will be cleared.`))try{t.textContent="\u23F3 Applying...",t.setAttribute("disabled","true");let g=Fe(),m={};for(let[b,y]of Object.entries(g.objects)){let v=y,w=b;/^(json\.|ui\.|effects\.|engine\.)/.test(w)||(w=`json.${b}`),v&&typeof v=="object"&&(v.identity||(v.identity={}),v.identity.id=w),m[`objects/${w}.json`]=v}g.engine&&(g.engine.runtime&&(m["engine/engine.runtime.json"]=g.engine.runtime),g.engine.assets&&(m["engine/engine.assets.json"]=g.engine.assets),g.engine.splash&&(m["engine/engine.splash.json"]=g.engine.splash),g.engine.loading&&(m["engine/engine.loading.json"]=g.engine.loading),g.engine.start&&(m["engine/engine.start.json"]=g.engine.start),g.engine.tutorial&&(m["engine/engine.tutorial.json"]=g.engine.tutorial),g.engine.endgame&&(m["engine/engine.endgame.json"]=g.engine.endgame),!g.engine.runtime&&!g.engine.assets&&(m["engine/engine.json"]=g.engine));for(let[b,y]of Object.entries(g.scenes)){let v=b.startsWith("scene.")?b:`scene.${b}`;m[`scenes/${v}.json`]=y}let h=this.currentVersion?"/api/apply-current":"/api/apply-direct",f=await fetch(h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:m,assets:{},hadCacheAtApply:!0})});if(!f.ok){let b=await f.json();throw new Error(b.error||"Apply to current source failed")}ne(),this.showSuccessNotification("Applied to current source"),await this.loadVersionsList(),this.refreshPanel()}catch(g){console.error("[ConfigPersistence] Apply current failed:",g),alert(`\u274C Apply to current source failed: ${g.message}`),t.textContent="\u{1F4BE} APPLY TO CURRENT SOURCE",t.removeAttribute("disabled")}});let n=this.container.querySelector("#apply-base-btn");n==null||n.addEventListener("click",async()=>{if(confirm(`\u26A0\uFE0F DANGER: APPLY TO BASE
|
|
1806
1857
|
|
|
1807
1858
|
This will DIRECTLY MODIFY base configuration files.
|
|
1808
1859
|
|
|
@@ -1812,25 +1863,25 @@ This is ONLY for active development.
|
|
|
1812
1863
|
|
|
1813
1864
|
Make sure your project is under Git version control.
|
|
1814
1865
|
|
|
1815
|
-
Continue?`))try{n.textContent="\u23F3 Writing to base...",n.setAttribute("disabled","true");let u=
|
|
1866
|
+
Continue?`))try{n.textContent="\u23F3 Writing to base...",n.setAttribute("disabled","true");let u=Fe(),g={};for(let[h,f]of Object.entries(u.objects)){let b=f,y=h;/^(json\.|ui\.|effects\.|engine\.)/.test(y)||(y=`json.${h}`),b&&typeof b=="object"&&(b.identity||(b.identity={}),b.identity.id=y),g[`objects/${y}.json`]=b}u.engine&&(u.engine.runtime&&(g["engine/engine.runtime.json"]=u.engine.runtime),u.engine.assets&&(g["engine/engine.assets.json"]=u.engine.assets),u.engine.splash&&(g["engine/engine.splash.json"]=u.engine.splash),u.engine.loading&&(g["engine/engine.loading.json"]=u.engine.loading),u.engine.start&&(g["engine/engine.start.json"]=u.engine.start),u.engine.tutorial&&(g["engine/engine.tutorial.json"]=u.engine.tutorial),u.engine.endgame&&(g["engine/engine.endgame.json"]=u.engine.endgame),!u.engine.runtime&&!u.engine.assets&&(g["engine/engine.json"]=u.engine));for(let[h,f]of Object.entries(u.scenes)){let b=h.startsWith("scene.")?h:`scene.${h}`;g[`scenes/${b}.json`]=f}let m=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:g,assets:{}})});if(!m.ok){let h=await m.json();throw new Error(h.error||"Apply to base failed")}ne(),this.showSuccessNotification(),this.refreshPanel()}catch(u){console.error("[ConfigPersistence] Apply to base failed:",u),alert(`\u274C Apply to base failed: ${u.message}`),n.textContent="\u{1F527} APPLY TO BASE (No Version)",n.removeAttribute("disabled")}});let i=this.container.querySelector("#version-selector");i==null||i.addEventListener("change",async d=>{let g=d.target.value;await this.switchVersion(g)}),this.container.querySelectorAll(".item-remove").forEach(d=>{d.addEventListener("click",()=>{let u=d.dataset.removePath,g=d.dataset.removeId;Lt(g||void 0,u)})});let s=this.container.querySelector("#clear-all-overrides"),o=this.container.querySelector("#discard-all-overrides-btn"),l=()=>{confirm("Discard all staged changes? This will clear all overrides and reload from current Source.")&&(ne(),kt(),this.refreshPanel())};s==null||s.addEventListener("click",l),o==null||o.addEventListener("click",l);let c=this.container.querySelector("#reset-to-applied-btn");c==null||c.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&kt()});let p=this.container.querySelector("#reset-to-original-btn");p==null||p.addEventListener("click",async()=>{await fn()})}showSuccessNotification(e){let t=document.createElement("div");t.className="persistence-notification success";let n=e&&e.trim().length>0?e.trim():"Changes Applied!";t.innerHTML=`
|
|
1816
1867
|
<div class="notify-icon">\u2705</div>
|
|
1817
1868
|
<div class="notify-content">
|
|
1818
1869
|
<strong>${n}</strong>
|
|
1819
1870
|
<span>Project files updated.</span>
|
|
1820
1871
|
</div>
|
|
1821
|
-
`,document.body.appendChild(t),setTimeout(()=>{t.classList.add("out"),setTimeout(()=>t.remove(),500)},3e3)}refreshPanel(){if(!this.container)return;let e=this.container.querySelector(".config-persistence-panel");e?e.outerHTML=this.render():this.container.innerHTML=this.render(),this.setupEventListeners()}async loadVersionsList(){try{let e=await fetch("/api/versions");if(!e.ok)throw new Error("Failed to fetch versions");let t=await e.json();this.availableVersions=t.versions||[],this.currentVersion=t.current||null}catch(e){console.error("[ConfigPersistence] Failed to load versions:",e),this.availableVersions=[],this.currentVersion=null}}async switchVersion(e){var i,a,s;let t=
|
|
1872
|
+
`,document.body.appendChild(t),setTimeout(()=>{t.classList.add("out"),setTimeout(()=>t.remove(),500)},3e3)}refreshPanel(){if(!this.container)return;let e=this.container.querySelector(".config-persistence-panel");e?e.outerHTML=this.render():this.container.innerHTML=this.render(),this.setupEventListeners()}async loadVersionsList(){try{let e=await fetch("/api/versions");if(!e.ok)throw new Error("Failed to fetch versions");let t=await e.json();this.availableVersions=t.versions||[],this.currentVersion=t.current||null}catch(e){console.error("[ConfigPersistence] Failed to load versions:",e),this.availableVersions=[],this.currentVersion=null}}async switchVersion(e){var i,a,s;let t=Ie();if(t.hasChanges){if(!confirm(`Switch to version "${e||"original"}"?
|
|
1822
1873
|
|
|
1823
1874
|
You have ${t.overrideCount} staged changes that will be discarded.
|
|
1824
1875
|
|
|
1825
1876
|
Options:
|
|
1826
1877
|
OK = Discard staged overrides and switch
|
|
1827
|
-
Cancel = Stay on current version`)){let l=(i=this.container)==null?void 0:i.querySelector("#version-selector");l&&(l.value=this.currentVersion||"");return}}else if(!confirm(`Switch to version "${e||"original"}"?`)){let l=(a=this.container)==null?void 0:a.querySelector("#version-selector");l&&(l.value=this.currentVersion||"");return}try{let o=await fetch("/api/switch-version",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({versionName:e||null})});if(!o.ok){let l=await o.json();throw new Error(l.error||"Failed to switch version")}
|
|
1878
|
+
Cancel = Stay on current version`)){let l=(i=this.container)==null?void 0:i.querySelector("#version-selector");l&&(l.value=this.currentVersion||"");return}}else if(!confirm(`Switch to version "${e||"original"}"?`)){let l=(a=this.container)==null?void 0:a.querySelector("#version-selector");l&&(l.value=this.currentVersion||"");return}try{let o=await fetch("/api/switch-version",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({versionName:e||null})});if(!o.ok){let l=await o.json();throw new Error(l.error||"Failed to switch version")}ne(),localStorage.removeItem("handler_config_overrides"),localStorage.setItem("handler_preview_override_mode","false"),window.location.reload()}catch(o){alert(`\u274C Failed to switch version: ${o.message}`);let l=(s=this.container)==null?void 0:s.querySelector("#version-selector");l&&(l.value=this.currentVersion||"")}}async directApply(){if(!this.isDevelopmentMode){alert("Direct Apply is only available in development mode.");return}if(confirm(`\u26A0\uFE0F WARNING: Direct Apply
|
|
1828
1879
|
|
|
1829
1880
|
This will DIRECTLY MODIFY your base configuration files WITHOUT creating a snapshot.
|
|
1830
1881
|
|
|
1831
1882
|
This cannot be undone unless you have git commits or backups.
|
|
1832
1883
|
|
|
1833
|
-
Are you absolutely sure?`))try{let t=
|
|
1884
|
+
Are you absolutely sure?`))try{let t=Fe(),n={};for(let[a,s]of Object.entries(t.objects)){let o=s,l=a;/^(json\.|ui\.|effects\.|engine\.)/.test(l)||(l=`json.${a}`),o&&typeof o=="object"&&(o.identity||(o.identity={}),o.identity.id=l),n[`objects/${l}.json`]=o}t.engine&&(t.engine.runtime&&(n["engine/engine.runtime.json"]=t.engine.runtime),t.engine.assets&&(n["engine/engine.assets.json"]=t.engine.assets),t.engine.splash&&(n["engine/engine.splash.json"]=t.engine.splash),t.engine.loading&&(n["engine/engine.loading.json"]=t.engine.loading),t.engine.start&&(n["engine/engine.start.json"]=t.engine.start),t.engine.tutorial&&(n["engine/engine.tutorial.json"]=t.engine.tutorial),t.engine.endgame&&(n["engine/engine.endgame.json"]=t.engine.endgame),!t.engine.runtime&&!t.engine.assets&&(n["engine/engine.json"]=t.engine));for(let[a,s]of Object.entries(t.scenes)){let o=a.startsWith("scene.")?a:`scene.${a}`;n[`scenes/${o}.json`]=s}let i=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n,assets:{}})});if(!i.ok){let a=await i.json();throw new Error(a.error||"Direct apply failed")}ne(),this.showSuccessNotification(),this.refreshPanel()}catch(t){console.error("[ConfigPersistence] Direct apply failed:",t),alert(`\u274C Direct apply failed: ${t.message}`)}}};var Ht=class{constructor(){this.debugOverlay=null;this.isDebugOpen=!1;this.selectedObjectId=null;this.configViewer=null;this.container=null;this.objectAutoApplyTimer=null;this.objectDebugRaf=null;this.objectBoundsGfx=null;this.objectAnchorGfx=null;this.highlightObject=!1;this.highlightAnchor=!1;this.activeTab="hierarchy";this.sceneObjectsPanel=new Tn;this.sceneToolsPanel=new Ln;this.nudgePanel=new kn;this.inspectorPanel=new Bn;this.libraryPanel=new _t;this.libraryPanelDocked=new _t;this.brandVisionPanel=new qn;this.customizeSettingsPanel=new Vn;this.configPersistencePanel=new ei;this.loadingScreenPanel=new Wn}applyAssetChange(e,t){return as(this,e,t)}resetAsset(e){return rs(this,e)}applySlotAsset(e,t,n){return ss(this,e,t,n)}resetSlotAsset(e,t,n){return os(this,e,t,n)}startObjectVisuals(){return ps(this)}stopObjectVisuals(){return us(this)}shouldRunObjectVisuals(){return Yn(this)}updateObjectVisuals(){return Kn(this)}getSelectedInstanceId(){return na(this)}getDisplayObjectById(e){return ia(this,e)}getSelectedObjectConfig(){return $t(this)}getConfigAnchorWorldPoint(e){return aa(this,e)}getScreenSize(){return ra(this)}ensureBoundsGfx(){return sa(this)}ensureAnchorGfx(){return oa(this)}drawBounds(e){return la(this,e)}drawAnchor(e){return ca(this,e)}clearBounds(){return da(this)}clearAnchor(){return pa(this)}clearObjectVisuals(){return Rt(this)}updateObjectInfo(e){return Ot(this,e)}resetDebugConfig(){return Jn(this)}applyDebugConfig(){return fs(this)}exportDebugConfig(){return Zn(this)}loadObjectConfig(e){return ms(this,e)}fillConfigViewer(e){return Xn(this,e)}copyConfigValues(){return bs(this)}applyObjectConfig(e){return ga(this,e)}applyCustomizeSettings(e,t){return ys(this,e,t)}scheduleObjectAutoApply(){return vs(this)}setupDebugEventListeners(){return xs(this)}setupDebugInputListeners(e){return ba(this,e)}setupPanelLayout(){return Es(this)}setupCollapsiblePanels(e){return ya(this,e)}setupRangeInput(e,t,n,i){return re(this,e,t,n,i)}updateWorkbenchTabs(){return ma(this)}saveWorkbenchState(){return st(this)}loadWorkbenchState(){return Qn(this)}initialize(e){var i;this.container=e,this.debugOverlay=e.querySelector(".debug-overlay"),this.configViewer=e.querySelector("#config-viewer");try{let a=localStorage.getItem("preview_workbench_state");if(a){let s=JSON.parse(a);s.activeTab&&(this.activeTab=s.activeTab)}}catch(a){console.warn("[PREVIEW] Failed to load workbench tab state",a)}this.sceneObjectsPanel.initialize(e,{onSelect:a=>this.handleObjectSelect(a)}),this.libraryPanel.initialize(e,{onApply:(a,s,o)=>this.applySlotAsset(a,s,o),onReset:(a,s,o)=>this.resetSlotAsset(a,s,o)});let t=e.querySelector("#dock-library-content");t&&(t.innerHTML=this.libraryPanelDocked.render(),this.libraryPanelDocked.initialize(t,{onApply:(a,s,o)=>this.applySlotAsset(a,s,o),onReset:(a,s,o)=>this.resetSlotAsset(a,s,o)})),this.inspectorPanel.initialize(e,{onPropertyChange:(a,s,o)=>{console.log("[Inspector] Property changed:",a,s,o)}}),this.brandVisionPanel.initialize(e,()=>{this.toggleDebug(!1);let a="/dashboard";window.location.pathname!==a&&(window.location.href=a)}),this.customizeSettingsPanel.initialize(e,{onApply:(a,s)=>this.applyCustomizeSettings(a,s)}),this.sceneToolsPanel.initialize(e,{onHighlightObject:a=>{this.highlightObject=a,a?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onHighlightAnchor:a=>{this.highlightAnchor=a,a?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onNudge:(a,s)=>this.nudgeSelectedObject(a,s),onShowSplash:()=>{let a=window;typeof a.__previewShowSplash=="function"&&a.__previewShowSplash()},onUpdateSplash:a=>{let s=window;typeof s.applyEditableEngineConfig=="function"&&s.applyEditableEngineConfig({splash:a})}}),this.nudgePanel.initialize(e,{onNudge:async(a,s)=>{var g,m,h,f,b,y;if(!this.selectedObjectId)return;let o=this.getSelectedObjectConfig();if(!o)return;let l=(g=o.transform)==null?void 0:g.position,c=((m=l==null?void 0:l.x)!=null?m:0)+a,p=((h=l==null?void 0:l.y)!=null?h:0)+s,{applyConfigOverride:d}=await Promise.resolve().then(()=>(J(),Be));d({objectId:this.selectedObjectId,path:"transform.position",value:{x:c,y:p}},{silent:!0,emitEvent:!0});let u=window.applyEditableObjectConfig;if(typeof u=="function"){let v=window.__editableConfig,w=(y=(b=(f=v==null?void 0:v.objects)==null?void 0:f.get)==null?void 0:b.call(f,this.selectedObjectId))!=null?y:o;await u(this.selectedObjectId,w)}window.dispatchEvent(new CustomEvent("inspector:refresh"))},onScale:async a=>{var d,u,g,m,h;if(!this.selectedObjectId)return;let s=this.getSelectedObjectConfig();if(!s)return;let o=(u=(d=s.transform)==null?void 0:d.scale)!=null?u:1,l=Math.max(.1,o+a),{applyConfigOverride:c}=await Promise.resolve().then(()=>(J(),Be));c({objectId:this.selectedObjectId,path:"transform.scale",value:l},{silent:!0,emitEvent:!0});let p=window.applyEditableObjectConfig;if(typeof p=="function"){let f=window.__editableConfig,b=(h=(m=(g=f==null?void 0:f.objects)==null?void 0:g.get)==null?void 0:m.call(g,this.selectedObjectId))!=null?h:s;await p(this.selectedObjectId,b)}window.dispatchEvent(new CustomEvent("inspector:refresh"))}});let n=e.querySelector("#debug-nudge-enabled");n==null||n.addEventListener("change",()=>{n.checked?this.nudgePanel.show():this.nudgePanel.hide()}),this.configPersistencePanel.initialize(e),this.loadingScreenPanel.initialize(e,{onShowLoadingScreen:()=>{let a=window;typeof a.__previewShowLoading=="function"?a.__previewShowLoading():console.warn("[DEBUG] __previewShowLoading not available")},onHideLoadingScreen:()=>{let a=window;typeof a.__previewHideLoading=="function"?a.__previewHideLoading():console.warn("[DEBUG] __previewHideLoading not available")},onUpdateLoading:a=>{let s=window;typeof s.applyEditableEngineConfig=="function"&&s.applyEditableEngineConfig({loading:a}),typeof s.__previewUpdateLoading=="function"?s.__previewUpdateLoading(a):console.warn("[DEBUG] __previewUpdateLoading not available")}}),window.__openAiEditor=(a,s,o,l)=>{this.customizeSettingsPanel.openAiEditor(a,s,o,l)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(i=this.debugOverlay)==null||i.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=a=>this.selectObject(a),window.addEventListener("config:changed",a=>{var s,o;((s=a.detail)==null?void 0:s.action)!=="remove"&&((o=a.detail)==null?void 0:o.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(a,s,o)=>this.applySlotAsset(a,s,o),window.refreshAssetLibrary=()=>this.libraryPanel.refresh(),window.reRenderAssetLibrary=()=>this.libraryPanel.reRender(),window.getEngineSplashConfig=()=>{var s;let a=window.getActiveConfig;if(typeof a=="function"){let o=a();return((s=o==null?void 0:o.engine)==null?void 0:s.splash)||null}return null},window.addAssetToRegistry=(a,s)=>{let o=window.getEditableAssets;if(typeof o=="function"){let l=o();if(l!=null&&l.libraryAssets&&(l.libraryAssets[a]||(l.libraryAssets[a]=[]),!l.libraryAssets[a].some(p=>p.filename===s))){let p=s.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");l.libraryAssets[a].unshift({filename:s,displayName:p}),console.log(`[DEBUG] Added ${s} to registry category ${a}`)}}},window.__highlightLibrarySlot=(a,s)=>{this.libraryPanel.highlightSlot(a,s)}}selectObject(e){this.handleObjectSelect(e),this.activeTab!=="inspector"&&this.activeTab!=="ai"&&this.setActiveTab("inspector")}setActiveTab(e){this.activeTab=e,this.updateWorkbenchTabs(),this.saveWorkbenchState()}highlightChangesTab(){var t;let e=(t=this.container)==null?void 0:t.querySelector('[data-tab="changes"]');e&&e.classList.add("has-pending-changes")}getDebugOverlayHTML(){return`
|
|
1834
1885
|
<div class="debug-overlay hidden" id="debug-overlay">
|
|
1835
1886
|
<div class="debug-workbench" id="debug-workbench">
|
|
1836
1887
|
<div class="workbench-header" id="workbench-handle">
|
|
@@ -1877,7 +1928,7 @@ Are you absolutely sure?`))try{let t=De(),n={};for(let[a,s]of Object.entries(t.o
|
|
|
1877
1928
|
${this.sceneToolsPanel.render()}
|
|
1878
1929
|
${this.nudgePanel.render()}
|
|
1879
1930
|
</div>
|
|
1880
|
-
`}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.refresh(),this.libraryPanelDocked.refresh(),this.brandVisionPanel.refresh(),this.selectedObjectId&&this.handleObjectSelect(this.selectedObjectId))}toggleDebug(e){var t;this.isDebugOpen=e!=null?e:!this.isDebugOpen,(t=this.debugOverlay)==null||t.classList.toggle("hidden",!this.isDebugOpen),this.updateDebugBadge(),this.isDebugOpen?this.refresh():this.stopObjectVisuals()}updateDebugBadge(){if(!this.container)return;let e=this.container.querySelector("#debug-badge");e&&e.classList.toggle("active",this.isDebugOpen)}handleObjectSelect(e){this.selectedObjectId=e,this.sceneObjectsPanel.setSelected(e),this.inspectorPanel.loadObject(e),this.loadObjectConfig(e),this.startObjectVisuals()}async nudgeSelectedObject(e,t){var o,l,c,p;let n=this.sceneObjectsPanel.getSelectedIds();if(n.length===0)return;let i=this.nudgePanel.getNudgeStep();if(n.length===1&&this.container){let d=this.container.querySelector("#config-pos-x"),u=this.container.querySelector("#config-pos-y");if(d&&u){let g=Number((o=d.value)!=null?o:0),m=Number((l=u.value)!=null?l:0),h=g+e*i,f=m+t*i;d.value=String(h),u.value=String(f),(c=this.configViewer)==null||c.style.setProperty("display","block"),this.scheduleObjectAutoApply();return}}let a=window.getEditableObjectConfig;if(typeof a!="function")return;let s=new
|
|
1931
|
+
`}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.refresh(),this.libraryPanelDocked.refresh(),this.brandVisionPanel.refresh(),this.selectedObjectId&&this.handleObjectSelect(this.selectedObjectId))}toggleDebug(e){var t;this.isDebugOpen=e!=null?e:!this.isDebugOpen,(t=this.debugOverlay)==null||t.classList.toggle("hidden",!this.isDebugOpen),this.updateDebugBadge(),this.isDebugOpen?this.refresh():this.stopObjectVisuals()}updateDebugBadge(){if(!this.container)return;let e=this.container.querySelector("#debug-badge");e&&e.classList.toggle("active",this.isDebugOpen)}handleObjectSelect(e){this.selectedObjectId=e,this.sceneObjectsPanel.setSelected(e),this.inspectorPanel.loadObject(e),this.loadObjectConfig(e),this.startObjectVisuals()}async nudgeSelectedObject(e,t){var o,l,c,p;let n=this.sceneObjectsPanel.getSelectedIds();if(n.length===0)return;let i=this.nudgePanel.getNudgeStep();if(n.length===1&&this.container){let d=this.container.querySelector("#config-pos-x"),u=this.container.querySelector("#config-pos-y");if(d&&u){let g=Number((o=d.value)!=null?o:0),m=Number((l=u.value)!=null?l:0),h=g+e*i,f=m+t*i;d.value=String(h),u.value=String(f),(c=this.configViewer)==null||c.style.setProperty("display","block"),this.scheduleObjectAutoApply();return}}let a=window.getEditableObjectConfig;if(typeof a!="function")return;let s=new Me;for(let d of n){let u=a(d);if(!u)continue;let g=((p=u.transform)==null?void 0:p.position)||[0,0],m=Array.isArray(g)?g[0]:g.x||0,h=Array.isArray(g)?g[1]:g.y||0,f=m+e*i,b=h+t*i;await s.updateProperty(d,"transform.position",[f,b])}n.length===1&&this.selectedObjectId===n[0]&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}};function ol(r){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(r)})}function ll(r){var i;let[e,t]=r.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(i=n==null?void 0:n[1])!=null?i:"image/png"}}function cl(r){return`
|
|
1881
1932
|
Analyze these screenshots of a brand or game and extract its "Brand DNA".
|
|
1882
1933
|
|
|
1883
1934
|
Provide a concise summary (2-3 sentences) covering:
|
|
@@ -1894,9 +1945,9 @@ Palette: [#RRGGBB, #RRGGBB, ...]
|
|
|
1894
1945
|
${r?`
|
|
1895
1946
|
ADDITIONAL RULES/NOTES:
|
|
1896
1947
|
${r}`:""}
|
|
1897
|
-
`.trim()}function Ss(){let r=[],e="",t=null;return{async addSources(n){let i=[];for(let a of n){let s=await ol(a),o=ll(s),l={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:a.name,base64:o.base64,mimeType:o.mimeType,dataUrl:s};r.push(l),i.push(l)}return i},getSources(){return r.slice()},async analyze(n,i,a){if(r.length===0)throw new Error("No screenshots to analyze.");let s=cl(i),o=r.map(u=>({base64:u.base64,mimeType:u.mimeType})),l=await
|
|
1948
|
+
`.trim()}function Ss(){let r=[],e="",t=null;return{async addSources(n){let i=[];for(let a of n){let s=await ol(a),o=ll(s),l={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:a.name,base64:o.base64,mimeType:o.mimeType,dataUrl:s};r.push(l),i.push(l)}return i},getSources(){return r.slice()},async analyze(n,i,a){if(r.length===0)throw new Error("No screenshots to analyze.");let s=cl(i),o=r.map(u=>({base64:u.base64,mimeType:u.mimeType})),l=await Gn(n,s,o,{model:a}),c=e,p=[],d=l.split(`
|
|
1898
1949
|
`);for(let u of d)if(u.toLowerCase().startsWith("summary:"))c=u.slice(8).trim();else if(u.toLowerCase().includes("palette:")){let g=u.match(/#[0-9A-Fa-f]{6}/g);g&&g.forEach(m=>{p.includes(m.toUpperCase())||p.push(m.toUpperCase())})}return(!c||c===e)&&(c=l.split(`
|
|
1899
|
-
Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0,10)},t},setSummary(n){e=n,t&&(t={...t,summary:n})},getResult(){return t}}}var
|
|
1950
|
+
Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0,10)},t},setSummary(n){e=n,t&&(t={...t,summary:n})},getResult(){return t}}}var Ve="handler_api_key_";var ot=class{static setKey(e,t,n){try{let i={key:this.encryptKey(t),created:Date.now(),lastUsed:Date.now(),label:n||e},a=`${Ve}${e}`;localStorage.setItem(a,JSON.stringify(i))}catch(i){console.error("[ApiKeyStorage] Failed to store API key:",i)}}static getKey(e){try{let t=`${Ve}${e}`,n=localStorage.getItem(t);if(!n)return null;let i=JSON.parse(n);return i.lastUsed=Date.now(),localStorage.setItem(t,JSON.stringify(i)),this.decryptKey(i.key)}catch(t){return console.error("[ApiKeyStorage] Failed to retrieve API key:",t),null}}static hasKey(e){let t=`${Ve}${e}`;return localStorage.getItem(t)!==null}static removeKey(e){try{let t=`${Ve}${e}`;localStorage.removeItem(t)}catch(t){console.error("[ApiKeyStorage] Failed to remove API key:",t)}}static getStoredServices(){let e=[];try{for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);if(n&&n.startsWith(Ve)){let i=n.substring(Ve.length),a=localStorage.getItem(n);if(a){let s=JSON.parse(a);e.push({service:i,label:s.label,created:s.created,lastUsed:s.lastUsed})}}}}catch(t){console.error("[ApiKeyStorage] Failed to get stored services:",t)}return e.sort((t,n)=>n.lastUsed-t.lastUsed)}static clearAll(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&n.startsWith(Ve)&&e.push(n)}e.forEach(t=>localStorage.removeItem(t))}catch(e){console.error("[ApiKeyStorage] Failed to clear API keys:",e)}}static encryptKey(e){try{let n="handler_preview_salt_2024"+e;return btoa(n)}catch(t){return console.warn("[ApiKeyStorage] Encryption failed, storing as-is:",t),e}}static decryptKey(e){try{let t=atob(e),n="handler_preview_salt_2024";return t.startsWith(n)?t.substring(n.length):t}catch(t){return console.warn("[ApiKeyStorage] Decryption failed, returning as-is:",t),e}}},va=()=>ot.getKey("gemini"),wa=(r,e)=>ot.setKey("gemini",r,e),dl=()=>ot.hasKey("gemini");window.ApiKeyStorage=ot;window.getGeminiApiKey=va;window.setGeminiApiKey=wa;window.hasGeminiApiKey=dl;var Ea=class{constructor(){this.modal=null;this.options=null;this.analyzer=Ss();this.currentPrompt="";this.isGenerating=!1;this.generatedImages=[];this.selectedImageIndex=-1;this.promptInput=null;this.generateBtn=null;this.loadingEl=null;this.galleryEl=null;this.previewEl=null}open(e){this.options=e,this.currentPrompt=e.initialPrompt||"",this.generatedImages=[],this.selectedImageIndex=-1,this.isGenerating=!1,this.createModal(),document.body.appendChild(this.modal),setTimeout(()=>{var t,n;(t=this.promptInput)==null||t.focus(),(n=this.promptInput)==null||n.select()},100)}createModal(){var t;let e=document.createElement("div");e.className="ai-modal",e.innerHTML=`
|
|
1900
1951
|
<div class="ai-modal-card">
|
|
1901
1952
|
<div class="ai-modal-header">
|
|
1902
1953
|
<div class="ai-modal-actions">
|
|
@@ -1977,12 +2028,12 @@ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0
|
|
|
1977
2028
|
</div>
|
|
1978
2029
|
`,this.modal=e,this.attachEventListeners(),this.updatePromptFromDna()}attachEventListeners(){var n;if(!this.modal)return;this.promptInput=this.modal.querySelector(".ai-textarea"),this.generateBtn=this.modal.querySelector('[data-action="generate"]'),this.loadingEl=this.modal.querySelector("[data-loading]"),this.galleryEl=this.modal.querySelector("[data-gallery]"),this.previewEl=this.modal.querySelector("[data-preview]"),(n=this.promptInput)==null||n.addEventListener("input",()=>{var i;this.currentPrompt=((i=this.promptInput)==null?void 0:i.value)||"",this.updateGenerateButton()});let e=this.modal.querySelector('[data-strength="creativity"]'),t=this.modal.querySelector(".ai-strength-value");e==null||e.addEventListener("input",()=>{t.textContent=e.value}),this.modal.addEventListener("click",i=>{var o;let a=i.target;switch(a.dataset.action||((o=a.closest("[data-action]"))==null?void 0:o.getAttribute("data-action"))){case"generate":this.generateImage();break;case"apply":this.applySelectedImage();break;case"gallery":this.toggleGallery();break;case"close":case"cancel":this.close();break}}),this.modal.addEventListener("click",i=>{let a=i.target;if(a.classList.contains("ai-gallery-item")||a.closest(".ai-gallery-item")){let s=a.closest(".ai-gallery-item"),o=parseInt(s.dataset.index||"-1");o>=0&&this.selectImage(o)}}),this.modal.addEventListener("click",i=>{i.target===this.modal&&this.close()}),this.updateGenerateButton()}updateGenerateButton(){if(!this.generateBtn)return;let e=this.currentPrompt.trim().length>0;this.generateBtn.disabled=!e||this.isGenerating}async updatePromptFromDna(){var t;let e=(t=this.modal)==null?void 0:t.querySelector("#ai-use-dna");if(e!=null&&e.checked)try{let n=this.analyzer.getResult();if(n!=null&&n.summary&&this.promptInput){let i=`${this.currentPrompt}
|
|
1979
2030
|
|
|
1980
|
-
Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}catch(n){console.warn("[AiEditorModal] Failed to apply brand DNA:",n)}}async generateImage(){var e,t,n,i;if(!(!this.options||this.isGenerating)){this.isGenerating=!0,this.updateGenerateButton(),(e=this.loadingEl)==null||e.classList.remove("hidden"),(t=this.previewEl)==null||t.classList.add("hidden");try{let a=this.getApiKey();if(!a){alert("Please set your Gemini API key first. You can do this in the AI Creative Suite panel.");return}let s=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let c=await
|
|
2031
|
+
Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}catch(n){console.warn("[AiEditorModal] Failed to apply brand DNA:",n)}}async generateImage(){var e,t,n,i;if(!(!this.options||this.isGenerating)){this.isGenerating=!0,this.updateGenerateButton(),(e=this.loadingEl)==null||e.classList.remove("hidden"),(t=this.previewEl)==null||t.classList.add("hidden");try{let a=this.getApiKey();if(!a){alert("Please set your Gemini API key first. You can do this in the AI Creative Suite panel.");return}let s=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let c=await Un(this.options.currentValue);c&&(s=[{base64:c.base64,mimeType:c.mimeType}])}catch(c){console.warn("[AiEditorModal] Failed to load current image:",c)}let o=await rt(a,this.currentPrompt,s,{aspectRatio:"1:1"}),l=await at(o);this.generatedImages.push(l||o),this.selectedImageIndex=this.generatedImages.length-1,this.updateGallery(),this.updatePreview(),this.updateApplyButton()}catch(a){console.error("[AiEditorModal] Generation failed:",a),alert(`Generation failed: ${a instanceof Error?a.message:"Unknown error"}`)}finally{this.isGenerating=!1,(n=this.loadingEl)==null||n.classList.add("hidden"),(i=this.previewEl)==null||i.classList.remove("hidden"),this.updateGenerateButton()}}}updateGallery(){if(!this.galleryEl)return;let e=this.galleryEl.querySelector("[data-gallery-grid]");e&&(e.innerHTML=this.generatedImages.map((t,n)=>`
|
|
1981
2032
|
<div class="ai-gallery-item ${n===this.selectedImageIndex?"active":""}" data-index="${n}">
|
|
1982
2033
|
<img class="ai-gallery-thumb" src="${t}" alt="Generated ${n+1}" />
|
|
1983
2034
|
<div class="ai-gallery-label">#${n+1}</div>
|
|
1984
2035
|
</div>
|
|
1985
|
-
`).join(""))}updatePreview(){if(!this.previewEl||this.selectedImageIndex<0)return;let e=this.generatedImages[this.selectedImageIndex];this.previewEl.innerHTML=`<img src="${e}" alt="Selected image" />`}selectImage(e){e<0||e>=this.generatedImages.length||(this.selectedImageIndex=e,this.updateGallery(),this.updatePreview(),this.updateApplyButton())}toggleGallery(){this.galleryEl&&this.galleryEl.classList.toggle("hidden")}updateApplyButton(){var t;let e=(t=this.modal)==null?void 0:t.querySelector('[data-action="apply"]');e&&(e.disabled=this.selectedImageIndex<0)}applySelectedImage(){var t;if(this.selectedImageIndex<0||!((t=this.options)!=null&&t.onApply))return;let e=this.generatedImages[this.selectedImageIndex];this.options.onApply(e),this.close()}getApiKey(){let e=
|
|
2036
|
+
`).join(""))}updatePreview(){if(!this.previewEl||this.selectedImageIndex<0)return;let e=this.generatedImages[this.selectedImageIndex];this.previewEl.innerHTML=`<img src="${e}" alt="Selected image" />`}selectImage(e){e<0||e>=this.generatedImages.length||(this.selectedImageIndex=e,this.updateGallery(),this.updatePreview(),this.updateApplyButton())}toggleGallery(){this.galleryEl&&this.galleryEl.classList.toggle("hidden")}updateApplyButton(){var t;let e=(t=this.modal)==null?void 0:t.querySelector('[data-action="apply"]');e&&(e.disabled=this.selectedImageIndex<0)}applySelectedImage(){var t;if(this.selectedImageIndex<0||!((t=this.options)!=null&&t.onApply))return;let e=this.generatedImages[this.selectedImageIndex];this.options.onApply(e),this.close()}getApiKey(){let e=va();if(e)return e;try{let t=this.analyzer.getResult();if(t&&t.apiKey)return wa(t.apiKey,"From Brand DNA"),t.apiKey}catch(t){console.warn("[AiEditorModal] Failed to get API key from brand DNA:",t)}return null}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}},xa=null;window.__openAiEditor=function(r,e,t,n){xa||(xa=new Ea),xa.open({objectId:r,initialPrompt:e,currentValue:t,path:n==null?void 0:n.path,onApply:i=>{if(n!=null&&n.path){let a=window.updateManager;if(a)a.updateProperty(r,n.path,i);else{let s=window.getEditableObjectConfig,o=s==null?void 0:s(r);if(o){let l=n.path.split("."),c=o;for(let p=0;p<l.length-1;p++)c[l[p]]||(c[l[p]]={}),c=c[l[p]];c[l[l.length-1]]=i}}}window.dispatchEvent(new CustomEvent("inspector:refresh"))}})};Aa();var Ca=class{constructor(){this.modal=null;this.options=null}open(e){this.options=e,this.createModal(),document.body.appendChild(this.modal)}createModal(){if(!this.options)return;let{assetPath:e,assetType:t,objectId:n}=this.options,i=n||"Asset Preview",a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
|
|
1986
2037
|
<div class="asset-preview-card">
|
|
1987
2038
|
<div class="asset-preview-header">
|
|
1988
2039
|
<div class="asset-preview-title">${i}</div>
|
|
@@ -2009,7 +2060,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2009
2060
|
<source src="${i}" type="audio/wav">
|
|
2010
2061
|
Your browser does not support the audio element.
|
|
2011
2062
|
</audio>
|
|
2012
|
-
`;case"text":return`<pre style="background: rgba(0,0,0,0.2); padding: 16px; border-radius: 8px; max-height: 300px; overflow-y: auto; white-space: pre-wrap;">${e}</pre>`;default:return`<div class="asset-preview-placeholder">Cannot preview ${t} assets</div>`}}resolveAssetUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("/")?e:`/raw/${e}`}attachEventListeners(){if(!this.modal)return;this.modal.addEventListener("click",n=>{let i=n.target;(i.dataset.action==="close"||i===this.modal)&&this.close()});let e=this.modal.querySelector('[data-action="change"]');e&&e.addEventListener("click",()=>{this.openAssetEditor()});let t=this.modal.querySelector('[data-action="edit"]');t&&t.addEventListener("click",()=>{this.openAiEditor(),this.close()})}openAssetEditor(){this.options&&Promise.resolve().then(()=>(
|
|
2063
|
+
`;case"text":return`<pre style="background: rgba(0,0,0,0.2); padding: 16px; border-radius: 8px; max-height: 300px; overflow-y: auto; white-space: pre-wrap;">${e}</pre>`;default:return`<div class="asset-preview-placeholder">Cannot preview ${t} assets</div>`}}resolveAssetUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("/")?e:`/raw/${e}`}attachEventListeners(){if(!this.modal)return;this.modal.addEventListener("click",n=>{let i=n.target;(i.dataset.action==="close"||i===this.modal)&&this.close()});let e=this.modal.querySelector('[data-action="change"]');e&&e.addEventListener("click",()=>{this.openAssetEditor()});let t=this.modal.querySelector('[data-action="edit"]');t&&t.addEventListener("click",()=>{this.openAiEditor(),this.close()})}openAssetEditor(){this.options&&Promise.resolve().then(()=>(Aa(),As)).then(({AssetEditorModal:e})=>{new e().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,n=>{var i;(i=this.options)!=null&&i.onChange&&this.options.onChange(n),this.close()})})}openAiEditor(){if(!this.options||this.options.assetType!=="image")return;let e=window.__openAiEditor;typeof e=="function"&&e(this.options.objectId||"asset","Edit this image asset",this.options.assetPath,{path:this.options.propertyPath,onApply:t=>{var n;(n=this.options)!=null&&n.onChange&&this.options.onChange(t)}})}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}};window.openAssetPreview=function(r){new Ca().open(r)};var Ta=class{constructor(){this.modal=null;this.canvas=null;this.ctx=null;this.image=null;this.options=null;this.cropX=0;this.cropY=0;this.cropWidth=100;this.cropHeight=100;this.scale=1;this.panX=0;this.panY=0;this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.lastPanX=0;this.lastPanY=0}open(e){this.options=e,this.createModal(),this.loadImage(),document.body.appendChild(this.modal)}createModal(){let e=document.createElement("div");e.className="asset-crop-modal",e.innerHTML=`
|
|
2013
2064
|
<div class="asset-crop-card">
|
|
2014
2065
|
<div class="asset-crop-header">
|
|
2015
2066
|
<div>
|
|
@@ -2060,7 +2111,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2060
2111
|
<button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
|
|
2061
2112
|
</div>
|
|
2062
2113
|
</div>
|
|
2063
|
-
`,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 n;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),(n=this.options)!=null&&n.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,n=this.cropX+this.cropWidth/2,i=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,n-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,i-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,n=this.cropWidth*this.scale,i=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,n,i),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,n,i),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+n-a,t],[e,t+i-a],[e+n-a,t+i-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 n=150;e.width=n,e.height=n;let i=n/this.cropWidth,a=n/this.cropHeight,s=Math.min(i,a),o=this.cropWidth*s,l=this.cropHeight*s,c=(n-o)/2,p=(n-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,p,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",n=>{let i=parseFloat(n.target.value);this.setZoom(i)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",n=>{let i=n.target.value;this.setAspectRatio(i)}),this.modal.addEventListener("click",n=>{switch(n.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",n=>{n.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,n=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,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,n=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,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 i;if(!this.image||!((i=this.options)!=null&&i.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 n=e.toDataURL("image/png");this.options.onCrop(n),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 Ca().open(r)};X();var Qn=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[Be("playable-portrait"),Be("iphone-14"),Be("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.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.hasUnsavedChanges=!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,n=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+n,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=Be(e.defaultDevice||vn.id),this.debugPanel=new zt,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.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setupShortcutListeners(),this.setupUnsavedChangesIndicator(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.updateDockState(),this.isInitialized=!0}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()}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}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(){this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.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 i,a;let n=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=Be(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:n}),t.suppressCallback||(a=(i=this.options).onDeviceChange)==null||a.call(i,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark"),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(i=>i.classList.toggle("active",i.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(i=>{i.style.left="",i.style.top="",i.style.width="",i.style.height="",i.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),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"),n=this.container.querySelector("#dock-console-content");t&&n&&t.parentElement!==n&&n.appendChild(t)}makeBottomDockResizable(e,t){let n,i,a=o=>{let l=o.clientY-n,c=Math.max(100,Math.min(800,i-l));e.style.height=`${c}px`;let p=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:p})},s=()=>{document.removeEventListener("pointermove",a),document.removeEventListener("pointerup",s),e.classList.remove("resizing")};t.addEventListener("pointerdown",o=>{o.preventDefault(),n=o.clientY,i=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",s),e.classList.add("resizing")})}makeSidebarResizable(e,t,n){let i,a,s=l=>{let c=n==="left"?l.clientX-i:i-l.clientX,p=Math.max(200,Math.min(600,a+c));e.style.width=`${p}px`;let d=this.container.querySelector(".preview-main");if(d){let g=n==="left"?`${p}px`:d.style.gridTemplateColumns.split(" ")[0]||"300px",m=n==="right"?`${p}px`:d.style.gridTemplateColumns.split(" ")[2]||"350px";d.style.gridTemplateColumns=`${g} 1fr ${m}`}let u=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:u})},o=()=>{document.removeEventListener("pointermove",s),document.removeEventListener("pointerup",o),e.classList.remove("resizing")};t.addEventListener("pointerdown",l=>{l.preventDefault(),i=l.clientX,a=e.offsetWidth,document.addEventListener("pointermove",s),document.addEventListener("pointerup",o),e.classList.add("resizing")})}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell layout-fixed",e.innerHTML=`
|
|
2114
|
+
`,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 n;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),(n=this.options)!=null&&n.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,n=this.cropX+this.cropWidth/2,i=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,n-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,i-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,n=this.cropWidth*this.scale,i=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,n,i),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,n,i),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+n-a,t],[e,t+i-a],[e+n-a,t+i-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 n=150;e.width=n,e.height=n;let i=n/this.cropWidth,a=n/this.cropHeight,s=Math.min(i,a),o=this.cropWidth*s,l=this.cropHeight*s,c=(n-o)/2,p=(n-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,p,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",n=>{let i=parseFloat(n.target.value);this.setZoom(i)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",n=>{let i=n.target.value;this.setAspectRatio(i)}),this.modal.addEventListener("click",n=>{switch(n.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",n=>{n.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,n=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,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,n=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,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 i;if(!this.image||!((i=this.options)!=null&&i.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 n=e.toDataURL("image/png");this.options.onCrop(n),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 Ta().open(r)};J();var ti=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[qe("playable-portrait"),qe("iphone-14"),qe("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.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.hasUnsavedChanges=!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,n=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+n,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=qe(e.defaultDevice||xn.id),this.debugPanel=new Ht,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.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setupShortcutListeners(),this.setupUnsavedChangesIndicator(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.updateDockState(),this.isInitialized=!0}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()}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}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(){this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.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 i,a;let n=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=qe(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:n}),t.suppressCallback||(a=(i=this.options).onDeviceChange)==null||a.call(i,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark"),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(i=>i.classList.toggle("active",i.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(i=>{i.style.left="",i.style.top="",i.style.width="",i.style.height="",i.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),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"),n=this.container.querySelector("#dock-console-content");t&&n&&t.parentElement!==n&&n.appendChild(t)}makeBottomDockResizable(e,t){let n,i,a=o=>{let l=o.clientY-n,c=Math.max(100,Math.min(800,i-l));e.style.height=`${c}px`;let p=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:p})},s=()=>{document.removeEventListener("pointermove",a),document.removeEventListener("pointerup",s),e.classList.remove("resizing")};t.addEventListener("pointerdown",o=>{o.preventDefault(),n=o.clientY,i=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",s),e.classList.add("resizing")})}makeSidebarResizable(e,t,n){let i,a,s=l=>{let c=n==="left"?l.clientX-i:i-l.clientX,p=Math.max(200,Math.min(600,a+c));e.style.width=`${p}px`;let d=this.container.querySelector(".preview-main");if(d){let g=n==="left"?`${p}px`:d.style.gridTemplateColumns.split(" ")[0]||"300px",m=n==="right"?`${p}px`:d.style.gridTemplateColumns.split(" ")[2]||"350px";d.style.gridTemplateColumns=`${g} 1fr ${m}`}let u=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:u})},o=()=>{document.removeEventListener("pointermove",s),document.removeEventListener("pointerup",o),e.classList.remove("resizing")};t.addEventListener("pointerdown",l=>{l.preventDefault(),i=l.clientX,a=e.offsetWidth,document.addEventListener("pointermove",s),document.addEventListener("pointerup",o),e.classList.add("resizing")})}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell layout-fixed",e.innerHTML=`
|
|
2064
2115
|
<div class="preview-toolbar">
|
|
2065
2116
|
<div class="preview-toolbar-left">
|
|
2066
2117
|
<span class="preview-logo">PREVIEWER</span>
|
|
@@ -2069,7 +2120,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2069
2120
|
<div class="preview-toolbar-center">
|
|
2070
2121
|
<div class="device-selector-wrapper">
|
|
2071
2122
|
<select class="device-dropdown" id="device-select">
|
|
2072
|
-
${
|
|
2123
|
+
${Wi.map(n=>`
|
|
2073
2124
|
<optgroup label="${n.label}">
|
|
2074
2125
|
${n.devices.map(i=>`
|
|
2075
2126
|
<option value="${i.id}" ${i.id===this.currentPreset.id?"selected":""}>
|
|
@@ -2230,7 +2281,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2230
2281
|
</div>
|
|
2231
2282
|
|
|
2232
2283
|
</div>
|
|
2233
|
-
`,this.setupEventListeners(e),e}setupEventListeners(e){var g,m,h,f,b,y,v,S;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",C=>{if(this.viewMode==="compare")return;let k=C.target.value;this.setDevice(k)});let n=e.querySelector("#theme-select");n==null||n.addEventListener("change",C=>{let k=C.target.value;this.setTheme(k)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(C=>{C.addEventListener("click",()=>{let k=C.dataset.viewToggle;k&&this.setViewMode(k)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(C=>{C.addEventListener("click",()=>{let k=C.dataset.layoutToggle;k&&this.setLayoutMode(k)})}),(g=e.querySelector("#rotate-btn"))==null||g.addEventListener("click",()=>this.toggleRotation()),(m=e.querySelector("#zoom-in-btn"))==null||m.addEventListener("click",()=>this.adjustUserZoom(.1)),(h=e.querySelector("#zoom-out-btn"))==null||h.addEventListener("click",()=>this.adjustUserZoom(-.1)),(f=e.querySelector("#refresh-btn"))==null||f.addEventListener("click",()=>this.refresh());let s=e.querySelector("#bottom-dock"),o=e.querySelector("#bottom-dock-resize");s&&o&&this.makeBottomDockResizable(s,o);let l=Array.from(e.querySelectorAll(".bottom-dock-tab"));l.forEach(C=>{C.addEventListener("click",()=>{let k=C.dataset.dockTab;if(!k)return;l.forEach(w=>w.classList.remove("active")),C.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(w=>{let x=w.dataset.dockPanel;w.classList.toggle("active",x===k)})})}),(b=e.querySelector("#console-clear"))==null||b.addEventListener("click",()=>this.clearConsole()),(y=e.querySelector("#corner-zoom-in-btn"))==null||y.addEventListener("click",()=>this.adjustUserZoom(.1)),(v=e.querySelector("#corner-zoom-out-btn"))==null||v.addEventListener("click",()=>this.adjustUserZoom(-.1)),(S=e.querySelector("#corner-grab-btn"))==null||S.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let c=e.querySelector(".scene-panel.scene-objects"),p=c==null?void 0:c.querySelector("[data-panel-resize-v]");c&&p&&this.makeSidebarResizable(c,p,"left");let d=e.querySelector(".debug-workbench"),u=d==null?void 0:d.querySelector("#workbench-resize-v");d&&u&&this.makeSidebarResizable(d,u,"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`,n=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=n,this.gameContainer.style.width=t,this.gameContainer.style.height=n,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=n,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=n,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(),n=this.getFitBounds(),i=Math.max(0,n.width),a=Math.max(0,n.height);if(i<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=i/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&&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 n=this.container.querySelector(".preview-container");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.appendChild(t))}else{let n=this.container.querySelector(".preview-main");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.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,n=e.ctrlKey||e.metaKey,i=e.shiftKey;if(n&&e.key==="s"&&!i){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(n&&e.key==="z"&&!i){e.preventDefault(),dn();return}if(n&&(e.key==="z"&&i||e.key==="y"&&!i)){e.preventDefault(),pn();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 n=document.querySelector("#apply-current-btn");n&&n.getAttribute("disabled")===null&&n.click()})}updateUnsavedChangesIndicator(){let t=Te().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let n=this.container.querySelector("#preview-unsaved-star"),i=this.container.querySelector("#preview-save-btn");n&&(n.style.display=t?"inline-block":"none"),i&&(i.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,n;if(this.viewMode==="compare")return;let e=this.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:e}),(n=(t=this.options).onDeviceChange)==null||n.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 n=window.gameApp;if(!(n!=null&&n.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var n;let t=new WeakSet;try{return JSON.stringify(e,(i,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((n=e.constructor)!=null&&n.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...n)=>{let i=n.map(s=>typeof s=="object"?this.safeStringify(s):String(s)).join(" ");this.consoleMessages.push({type:t,message:i,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 n=document.createElement("div");n.className=`console-msg type-${e.type}`;let i=e.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(i)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(n),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 n=this.container.querySelector('[data-dock-tab="console"]');if(n){n.click();let i=this.container.querySelector("#bottom-dock");i==null||i.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 n=t.dataset.viewport;if(!n)return;let i=this.comparePresets.find(d=>d.id===n);if(!i)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]"),p=t.querySelector("[data-compare-focus]");!a||!s||!o||!l||(t.addEventListener("click",d=>{let u=d.target;if(u!=null&&u.closest("[data-compare-focus]")){d.preventDefault(),this.activateCompareViewport(n);return}t.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:i,root:t,slot:a,ghost:s,wrapper:o,frame:l,canvas:c,focus:p}))})}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 n=this.container.querySelector("#rotate-btn");if(n&&(n.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen()}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 n=this.autoScale*this.userScaleMultiplier,i=this.activeCompareId;i&&i!==e&&this.captureCompareSnapshot(i),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:n}),(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,n=`${t.width}px`,i=`${t.height}px`;e.frame.style.width=n,e.frame.style.height=i,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 n=Math.max(0,t.clientWidth-24),i=Math.max(0,t.clientHeight-24);if(n<=0||i<=0)return;let a=n/e.preset.width,s=i/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 n=this.gameContainer.querySelector("canvas");if(!n)return;let i=t.canvas.getContext("2d");if(!i)return;let a=t.canvas.width,s=t.canvas.height,o=Math.min(a/n.width,s/n.height),l=n.width*o,c=n.height*o,p=(a-l)/2,d=(s-c)/2;i.clearRect(0,0,a,s),i.drawImage(n,p,d,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")return{width:this.previewContainer.clientWidth-40,height:this.previewContainer.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 Ta(r={}){let e=new Qn(r);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}X();function La(r){try{if(r&&typeof r.keys=="function")return Array.from(r.keys())}catch{}return[]}function Cs(r){var e;return r?((e=r.getDisplayObject)==null?void 0:e.call(r))||r.pixiObject||r:null}function pl(r,e){if(!r||!(e!=null&&e.interaction))return;let t=e.interaction,n=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);r.eventMode=n?"static":"none",r.interactive=n,n&&(r.cursor=t.draggable?"move":"pointer")}function Ts(r,e){var l,c,p;if(!r||!e)return;let t=e.transform||{};pl(r,e);let n=t.position||{},i=t.offset||{},a=(typeof n.x=="number"?n.x:0)+(typeof i.x=="number"?i.x:0),s=(typeof n.y=="number"?n.y:0)+(typeof i.y=="number"?i.y:0);(l=r.position)!=null&&l.set?r.position.set(a,s):(typeof r.x=="number"&&(r.x=a),typeof r.y=="number"&&(r.y=s)),typeof t.scale=="number"&&((c=r.scale)!=null&&c.set?r.scale.set(t.scale):r.scale&&(r.scale.x=t.scale,r.scale.y=t.scale));let o=t.anchor;if(o&&((p=r.anchor)!=null&&p.set)){let d=null;typeof window!="undefined"&&window.resolveAnchorVec2?d=window.resolveAnchorVec2(o):typeof o=="object"&&o.x!==void 0&&o.y!==void 0?d=o:Array.isArray(o)&&o.length===2&&(d={x:o[0],y:o[1]}),d&&typeof d.x=="number"&&typeof d.y=="number"&&r.anchor.set(d.x,d.y)}}function Ls(r){if(typeof window=="undefined")return;let e=r==null?void 0:r.objects,t=La(e),n=a=>{try{let s=window.__HANDLER_ACTIVE_SCREEN;if(!s||s==="all")return a;let o=window.__HANDLER_SCREEN_INDEX,l=o==null?void 0:o.instanceToScreen;return l?a.filter(c=>l[c]===s):a}catch{return a}};window.__editableObjectConfigs=e;let i=new Map;t.forEach(a=>i.set(a,[a])),window.__editableObjectInstances=i,window.refreshEditableConfigIndex=()=>Ls(window.__editableConfig),window.getEditableObjectList=()=>{var a;return n(La((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return La((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var p,d,u,g,m;let s=(g=(u=(d=(p=window.__editableConfig)==null?void 0:p.objects)==null?void 0:d.get)==null?void 0:u.call(d,a))!=null?g: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.instanceToScreen)==null?void 0:m[a];return c&&c===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 ul(){if(typeof window=="undefined")return;let r=t=>{let n=String(t||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},e=async(t,n)=>{var a,s,o;let i=r(n);if(i)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(et(),Er))]),p=Date.now(),d=/^(data:|blob:)/.test(i)?i:i+(i.includes("?")?`&t=${p}`:`?t=${p}`),u=await l.load(d);if(!u)return;c[t]=u;let g=window.CustomAssets;(a=g==null?void 0:g[t])!=null&&a.texture&&(g[t].texture=u);let m=window.gameObjectManager,h=(s=m==null?void 0:m.get)==null?void 0:s.call(m,t);if(h){let f=((o=h.getDisplayObject)==null?void 0:o.call(h))||h.pixiObject||h.pixi||h;if(f!=null&&f.texture)f.texture=u;else if(f!=null&&f.children){let b=f.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let n=K();Array.isArray(n)&&n.length&&(window.__editableConfig=t,Ce(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let n=K();Array.isArray(n)&&n.length&&(window.__editableConfig=t,Ce(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let i=[];if(t.runtime)for(let[a,s]of Object.entries(t.runtime))i.push({path:`runtime.${a}`,value:s});if(t.assets)for(let[a,s]of Object.entries(t.assets))i.push({path:`assets.${a}`,value:s}),typeof s=="string"&&e(a,s);if(t.splash)for(let[a,s]of Object.entries(t.splash))i.push({path:`splash.${a}`,value:s});if(t.loading)for(let[a,s]of Object.entries(t.loading))i.push({path:`loading.${a}`,value:s});if(t.start)for(let[a,s]of Object.entries(t.start))i.push({path:`start.${a}`,value:s});i.length&&Ce(i,{silent:!0,persist:!0,emitEvent:!0})}}function ei(r){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:n}=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,p=c==null?void 0:c.children.indexOf(l);o?t.remove(a):l&&l.destroy();let d=window.gameApp,u=await Ae.create(a,s,d);c&&(p!==void 0&&p!==-1?c.addChildAt(u,p):c.addChild(u));let g=t.create(a,u);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),g}),typeof window!="undefined"&&(ul(),window.applyEditableObjectConfig=(a,s)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let p=window.__editableConfig;(o=p==null?void 0:p.objects)!=null&&o.set&&(p.objects.set(a,s),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let d=(l=t==null?void 0:t.get)==null?void 0:l.call(t,a);if(console.log("[LIVE-EDIT] gameObject found?",!!d),d&&(console.log("[LIVE-EDIT] gameObject type:",(c=d.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof d.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof d.onConfigUpdate=="function")),d&&typeof d.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),d.updateConfig(s);else if(d&&typeof d.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),d.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let u=Cs(d);Ts(u,s)}}catch(p){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",p)}});let i={async applyObjectConfig(a,s){var p,d;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=e();(p=o==null?void 0:o.objects)!=null&&p.set&&(o.objects.set(a,s),console.log("[BRIDGE] \u2705 Updated config"));let l=(d=t==null?void 0:t.get)==null?void 0:d.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 u=Cs(l);Ts(u,s)}let c=[a];n==null||n(a,s,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,Ls(a))}};return i.rebuildIndexes(),i}X();var Ms=Xe(require("lottie-web"),1);yi(mi);typeof window!="undefined"&&!window.lottie&&(window.lottie=Ms.default);var st=null,gl=async()=>{if(!st){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 n=atob(e.split(",")[1]);st=JSON.parse(n)}else st=JSON.parse(e);return st}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}st=await(await fetch("./handler.config.json")).json()}return st},Pa,Dt,Ps,ot,Ia,Ma;function hl(r){Pa=r.initGame,Dt=r.CustomAssets,Ps=r.updateScreenState,ot=r.globalResponsiveMultipliers,Ia=r.layout,Ma=r.clearResponsiveElements}var ti="web_embed",$t="https://example.com",ks={profile_id:ti},Pe=null,ce=null,ka={width:0,height:0},fl=!0,ml=async()=>{var c,p,d,u;document.title="Handler Pixi Game";let r=await gl();ks={...r.ids||{},profile_id:ti},$t=r.destination_url||((p=(c=r.export_profiles)==null?void 0:c[ti])==null?void 0:p.destination_url)||$t,Oe.init({ids:ks,profile:ti,destinationUrl:$t});let e=Oe.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),ce=Ta({onDeviceChange:m=>{console.log(`[PREVIEW] Device switched to ${m.width}x${m.height}, restarting game...`),Is()},onRefresh:Is});let g=ce.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",m=>{var v,S,C,k,z,w,x,M,A,E,I;let h=window.gameApp,f=window.gameObjectManager,{width:b,height:y}=m.detail;if(ka.width=b,ka.height=y,Ps(b,y),!(!h||!h.renderer)){f&&o(h,f);try{h.renderer.resize(b,y);let L=h.view;L&&(L.style.width="100%",L.style.height="100%",L.style.display="block")}catch(L){console.warn("[SCREEN] Error resizing renderer:",L);return}if(t&&f&&Ia)try{let L=(v=window.__mainContainer)!=null?v:h.stage,_=(x=(w=(k=window.__tutorialLabel)!=null?k:(C=(S=f.get("label_1"))==null?void 0:S.getDisplayObject)==null?void 0:C.call(S))!=null?w:(z=f.get("label_1"))==null?void 0:z.pixiObject)!=null?x:f.get("label_1"),P=f.get("background_1"),R=(I=(E=(A=window.__background)!=null?A:(M=P==null?void 0:P.getDisplayObject)==null?void 0:M.call(P))!=null?E:P==null?void 0:P.pixiObject)!=null?I:P;if(L){let T=L===h.stage;Ia({mainContainer:L,label:_,background:R,backgroundTexture:(R==null?void 0:R.texture)||null,app:h},t,0,ka,f,{skipMainContainerTransform:T})}}catch(L){console.warn("[SCREEN] Error in layout:",L)}}})}let t=await ye("scene.main");window.__editableConfig=t,s(),window.__editableConfigBaseline||(window.__editableConfigBaseline=V(t),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(u=(d=t.engine.runtime)==null?void 0:d.layout)!=null&&u.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(g=>setTimeout(g,100)),t=await ye("scene.main"));let n=await Pa(e,t,$t,ce);Pe=n.app;let i=n.gameObjectManager;window.gameApp=Pe,window.gameObjectManager=i;try{window.__liveEditBridge=ei({getConfig:()=>window.__editableConfig,gameObjectManager:i,assets:Dt})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}ce&&ce.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(ot.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(Pe,i);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 C=await S.text();try{return JSON.parse(C)}catch{return null}},m=await g("configs/flow/app.flow.json");if(!m||typeof m!="object")return;let h=m.screens;if(!h||typeof h!="object")return;let f={},b={};for(let[y,v]of Object.entries(h)){let S=v==null?void 0:v.source;if(typeof S!="string")continue;let C=await g(S),k=C==null?void 0:C.elements;if(!Array.isArray(k))continue;let z=k.map(w=>w==null?void 0:w.instance_id).filter(w=>typeof w=="string");f[y]=z;for(let w of z)b[w]||(b[w]=y)}window.__HANDLER_APP_FLOW=m,window.__HANDLER_SCREEN_INDEX={screenToInstances:f,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,m){if(fl){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${ot.scale.toFixed(3)}`),g.stage){let f=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((S,C)=>{if(S&&S.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(S&&S.scale){let k=S.scale.x||1,z=S.scale.y||1;S.__originalScale||(S.__originalScale={x:k,y:z},console.log(`${v}[RESPONSIVE] Stored original scale for child[${C}]: ${k.toFixed(3)}, ${z.toFixed(3)}`));let w=S.__originalScale.x*ot.scale,x=S.__originalScale.y*ot.scale;typeof S.scale.set=="function"?S.scale.set(w,x):(S.scale.x=w,S.scale.y=x),console.log(`${v}[RESPONSIVE] Child[${C}] scale: ${k.toFixed(3)}\u2192${S.scale.x.toFixed(3)} (type: ${S.constructor.name})`),f(S,y+1)}else S&&console.log(`${v}[RESPONSIVE] Child[${C}] has no scale (type: ${S.constructor.name})`)})};var h=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){ot.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let m=window.gameApp,h=window.gameObjectManager;m&&h?(o(m,h),m.renderer&&(m.renderer.render(m.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!m}) or gameObjectManager (${!!h}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,Oe.start()},Is=async()=>{var e,t,n,i;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: ${((n=a.scale.x)!=null?n:1).toFixed(3)}, y: ${((i=a.scale.y)!=null?i:1).toFixed(3)}`)}if(ce){ce.notifyGameDestroyed();try{Ma&&Ma()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=ce.getGameContainer(),s=window.gameObjectManager;if(s&&typeof s.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),s.clear()),Pe){try{Pe.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Pe=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(()=>{ye("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=V(o)),Pa(a,o,$t).then(l=>{Pe=l.app,window.gameApp=Pe,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=ei({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Dt})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}ce&&ce.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{Oe.start()}catch{}})})},100)},1e3)}};yn();X();var de={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},_s=1.25,js={fontFamily:"Inter, system-ui, sans-serif"};var ni=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=`
|
|
2284
|
+
`,this.setupEventListeners(e),e}setupEventListeners(e){var g,m,h,f,b,y,v,w;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",E=>{if(this.viewMode==="compare")return;let j=E.target.value;this.setDevice(j)});let n=e.querySelector("#theme-select");n==null||n.addEventListener("change",E=>{let j=E.target.value;this.setTheme(j)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(E=>{E.addEventListener("click",()=>{let j=E.dataset.viewToggle;j&&this.setViewMode(j)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(E=>{E.addEventListener("click",()=>{let j=E.dataset.layoutToggle;j&&this.setLayoutMode(j)})}),(g=e.querySelector("#rotate-btn"))==null||g.addEventListener("click",()=>this.toggleRotation()),(m=e.querySelector("#zoom-in-btn"))==null||m.addEventListener("click",()=>this.adjustUserZoom(.1)),(h=e.querySelector("#zoom-out-btn"))==null||h.addEventListener("click",()=>this.adjustUserZoom(-.1)),(f=e.querySelector("#refresh-btn"))==null||f.addEventListener("click",()=>this.refresh());let s=e.querySelector("#bottom-dock"),o=e.querySelector("#bottom-dock-resize");s&&o&&this.makeBottomDockResizable(s,o);let l=Array.from(e.querySelectorAll(".bottom-dock-tab"));l.forEach(E=>{E.addEventListener("click",()=>{let j=E.dataset.dockTab;if(!j)return;l.forEach(S=>S.classList.remove("active")),E.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(S=>{let _=S.dataset.dockPanel;S.classList.toggle("active",_===j)})})}),(b=e.querySelector("#console-clear"))==null||b.addEventListener("click",()=>this.clearConsole()),(y=e.querySelector("#corner-zoom-in-btn"))==null||y.addEventListener("click",()=>this.adjustUserZoom(.1)),(v=e.querySelector("#corner-zoom-out-btn"))==null||v.addEventListener("click",()=>this.adjustUserZoom(-.1)),(w=e.querySelector("#corner-grab-btn"))==null||w.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let c=e.querySelector(".scene-panel.scene-objects"),p=c==null?void 0:c.querySelector("[data-panel-resize-v]");c&&p&&this.makeSidebarResizable(c,p,"left");let d=e.querySelector(".debug-workbench"),u=d==null?void 0:d.querySelector("#workbench-resize-v");d&&u&&this.makeSidebarResizable(d,u,"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`,n=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=n,this.gameContainer.style.width=t,this.gameContainer.style.height=n,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=n,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=n,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(),n=this.getFitBounds(),i=Math.max(0,n.width),a=Math.max(0,n.height);if(i<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=i/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&&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 n=this.container.querySelector(".preview-container");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.appendChild(t))}else{let n=this.container.querySelector(".preview-main");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.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,n=e.ctrlKey||e.metaKey,i=e.shiftKey;if(n&&e.key==="s"&&!i){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(n&&e.key==="z"&&!i){e.preventDefault(),un();return}if(n&&(e.key==="z"&&i||e.key==="y"&&!i)){e.preventDefault(),gn();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 n=document.querySelector("#apply-current-btn");n&&n.getAttribute("disabled")===null&&n.click()})}updateUnsavedChangesIndicator(){let t=Ie().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let n=this.container.querySelector("#preview-unsaved-star"),i=this.container.querySelector("#preview-save-btn");n&&(n.style.display=t?"inline-block":"none"),i&&(i.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,n;if(this.viewMode==="compare")return;let e=this.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:e}),(n=(t=this.options).onDeviceChange)==null||n.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 n=window.gameApp;if(!(n!=null&&n.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var n;let t=new WeakSet;try{return JSON.stringify(e,(i,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((n=e.constructor)!=null&&n.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...n)=>{let i=n.map(s=>typeof s=="object"?this.safeStringify(s):String(s)).join(" ");this.consoleMessages.push({type:t,message:i,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 n=document.createElement("div");n.className=`console-msg type-${e.type}`;let i=e.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(i)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(n),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 n=this.container.querySelector('[data-dock-tab="console"]');if(n){n.click();let i=this.container.querySelector("#bottom-dock");i==null||i.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 n=t.dataset.viewport;if(!n)return;let i=this.comparePresets.find(d=>d.id===n);if(!i)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]"),p=t.querySelector("[data-compare-focus]");!a||!s||!o||!l||(t.addEventListener("click",d=>{let u=d.target;if(u!=null&&u.closest("[data-compare-focus]")){d.preventDefault(),this.activateCompareViewport(n);return}t.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:i,root:t,slot:a,ghost:s,wrapper:o,frame:l,canvas:c,focus:p}))})}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 n=this.container.querySelector("#rotate-btn");if(n&&(n.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen()}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 n=this.autoScale*this.userScaleMultiplier,i=this.activeCompareId;i&&i!==e&&this.captureCompareSnapshot(i),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:n}),(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,n=`${t.width}px`,i=`${t.height}px`;e.frame.style.width=n,e.frame.style.height=i,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 n=Math.max(0,t.clientWidth-24),i=Math.max(0,t.clientHeight-24);if(n<=0||i<=0)return;let a=n/e.preset.width,s=i/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 n=this.gameContainer.querySelector("canvas");if(!n)return;let i=t.canvas.getContext("2d");if(!i)return;let a=t.canvas.width,s=t.canvas.height,o=Math.min(a/n.width,s/n.height),l=n.width*o,c=n.height*o,p=(a-l)/2,d=(s-c)/2;i.clearRect(0,0,a,s),i.drawImage(n,p,d,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")return{width:this.previewContainer.clientWidth-40,height:this.previewContainer.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 La(r={}){let e=new ti(r);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}J();function ka(r){try{if(r&&typeof r.keys=="function")return Array.from(r.keys())}catch{}return[]}function Cs(r){var e;return r?((e=r.getDisplayObject)==null?void 0:e.call(r))||r.pixiObject||r:null}function pl(r,e){if(!r||!(e!=null&&e.interaction))return;let t=e.interaction,n=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);r.eventMode=n?"static":"none",r.interactive=n,n&&(r.cursor=t.draggable?"move":"pointer")}function Ts(r,e){var l,c,p;if(!r||!e)return;let t=e.transform||{};pl(r,e);let n=t.position||{},i=t.offset||{},a=(typeof n.x=="number"?n.x:0)+(typeof i.x=="number"?i.x:0),s=(typeof n.y=="number"?n.y:0)+(typeof i.y=="number"?i.y:0);(l=r.position)!=null&&l.set?r.position.set(a,s):(typeof r.x=="number"&&(r.x=a),typeof r.y=="number"&&(r.y=s)),typeof t.scale=="number"&&((c=r.scale)!=null&&c.set?r.scale.set(t.scale):r.scale&&(r.scale.x=t.scale,r.scale.y=t.scale));let o=t.anchor;if(o&&((p=r.anchor)!=null&&p.set)){let d=null;typeof window!="undefined"&&window.resolveAnchorVec2?d=window.resolveAnchorVec2(o):typeof o=="object"&&o.x!==void 0&&o.y!==void 0?d=o:Array.isArray(o)&&o.length===2&&(d={x:o[0],y:o[1]}),d&&typeof d.x=="number"&&typeof d.y=="number"&&r.anchor.set(d.x,d.y)}}function Ls(r){if(typeof window=="undefined")return;let e=r==null?void 0:r.objects,t=ka(e),n=a=>{try{let s=window.__HANDLER_ACTIVE_SCREEN;if(!s||s==="all")return a;let o=window.__HANDLER_SCREEN_INDEX,l=o==null?void 0:o.instanceToScreen;return l?a.filter(c=>l[c]===s):a}catch{return a}};window.__editableObjectConfigs=e;let i=new Map;t.forEach(a=>i.set(a,[a])),window.__editableObjectInstances=i,window.refreshEditableConfigIndex=()=>Ls(window.__editableConfig),window.getEditableObjectList=()=>{var a;return n(ka((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return ka((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var p,d,u,g,m;let s=(g=(u=(d=(p=window.__editableConfig)==null?void 0:p.objects)==null?void 0:d.get)==null?void 0:u.call(d,a))!=null?g: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.instanceToScreen)==null?void 0:m[a];return c&&c===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 ul(){if(typeof window=="undefined")return;let r=t=>{let n=String(t||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},e=async(t,n)=>{var a,s,o;let i=r(n);if(i)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(nt(),Sr))]),p=Date.now(),d=/^(data:|blob:)/.test(i)?i:i+(i.includes("?")?`&t=${p}`:`?t=${p}`),u=await l.load(d);if(!u)return;c[t]=u;let g=window.CustomAssets;(a=g==null?void 0:g[t])!=null&&a.texture&&(g[t].texture=u);let m=window.gameObjectManager,h=(s=m==null?void 0:m.get)==null?void 0:s.call(m,t);if(h){let f=((o=h.getDisplayObject)==null?void 0:o.call(h))||h.pixiObject||h.pixi||h;if(f!=null&&f.texture)f.texture=u;else if(f!=null&&f.children){let b=f.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let n=X();Array.isArray(n)&&n.length&&(window.__editableConfig=t,ke(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let n=X();Array.isArray(n)&&n.length&&(window.__editableConfig=t,ke(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let i=[];if(t.runtime)for(let[a,s]of Object.entries(t.runtime))i.push({path:`runtime.${a}`,value:s});if(t.assets)for(let[a,s]of Object.entries(t.assets))i.push({path:`assets.${a}`,value:s}),typeof s=="string"&&e(a,s);if(t.splash)for(let[a,s]of Object.entries(t.splash))i.push({path:`splash.${a}`,value:s});if(t.loading)for(let[a,s]of Object.entries(t.loading))i.push({path:`loading.${a}`,value:s});if(t.start)for(let[a,s]of Object.entries(t.start))i.push({path:`start.${a}`,value:s});i.length&&ke(i,{silent:!0,persist:!0,emitEvent:!0})}}function ni(r){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:n}=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,p=c==null?void 0:c.children.indexOf(l);o?t.remove(a):l&&l.destroy();let d=window.gameApp,u=await Le.create(a,s,d);c&&(p!==void 0&&p!==-1?c.addChildAt(u,p):c.addChild(u));let g=t.create(a,u);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),g}),typeof window!="undefined"&&(ul(),window.applyEditableObjectConfig=(a,s)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let p=window.__editableConfig;(o=p==null?void 0:p.objects)!=null&&o.set&&(p.objects.set(a,s),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let d=(l=t==null?void 0:t.get)==null?void 0:l.call(t,a);if(console.log("[LIVE-EDIT] gameObject found?",!!d),d&&(console.log("[LIVE-EDIT] gameObject type:",(c=d.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof d.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof d.onConfigUpdate=="function")),d&&typeof d.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),d.updateConfig(s);else if(d&&typeof d.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),d.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let u=Cs(d);Ts(u,s)}}catch(p){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",p)}});let i={async applyObjectConfig(a,s){var p,d;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=e();(p=o==null?void 0:o.objects)!=null&&p.set&&(o.objects.set(a,s),console.log("[BRIDGE] \u2705 Updated config"));let l=(d=t==null?void 0:t.get)==null?void 0:d.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 u=Cs(l);Ts(u,s)}let c=[a];n==null||n(a,s,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,Ls(a))}};return i.rebuildIndexes(),i}J();var js=Ze(require("lottie-web"),1);vi(bi);typeof window!="undefined"&&!window.lottie&&(window.lottie=js.default);var lt=null,gl=async()=>{if(!lt){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 n=atob(e.split(",")[1]);lt=JSON.parse(n)}else lt=JSON.parse(e);return lt}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}lt=await(await fetch("./handler.config.json")).json()}return lt},_a,Ft,Ms,ct,ja,Ma;function hl(r){_a=r.initGame,Ft=r.CustomAssets,Ms=r.updateScreenState,ct=r.globalResponsiveMultipliers,ja=r.layout,Ma=r.clearResponsiveElements}var ii="web_embed",Nt="https://example.com",ks={profile_id:ii},Oe=null,de=null,Ia={width:0,height:0},fl=!0,ml=async()=>{var c,p,d,u;document.title="Handler Pixi Game";let r=await gl();ks={...r.ids||{},profile_id:ii},Nt=r.destination_url||((p=(c=r.export_profiles)==null?void 0:c[ii])==null?void 0:p.destination_url)||Nt,$e.init({ids:ks,profile:ii,destinationUrl:Nt});let e=$e.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),de=La({onDeviceChange:m=>{console.log(`[PREVIEW] Device switched to ${m.width}x${m.height}, restarting game...`),Is()},onRefresh:Is});let g=de.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",m=>{var v,w,E,j,z,S,_,R,T,C,M;let h=window.gameApp,f=window.gameObjectManager,{width:b,height:y}=m.detail;if(Ia.width=b,Ia.height=y,Ms(b,y),!(!h||!h.renderer)){f&&o(h,f);try{h.renderer.resize(b,y);let k=h.view;k&&(k.style.width="100%",k.style.height="100%",k.style.display="block")}catch(k){console.warn("[SCREEN] Error resizing renderer:",k);return}if(t&&f&&ja)try{let k=(v=window.__mainContainer)!=null?v:h.stage,A=(_=(S=(j=window.__tutorialLabel)!=null?j:(E=(w=f.get("label_1"))==null?void 0:w.getDisplayObject)==null?void 0:E.call(w))!=null?S:(z=f.get("label_1"))==null?void 0:z.pixiObject)!=null?_:f.get("label_1"),x=f.get("background_1"),I=(M=(C=(T=window.__background)!=null?T:(R=x==null?void 0:x.getDisplayObject)==null?void 0:R.call(x))!=null?C:x==null?void 0:x.pixiObject)!=null?M:x;if(k){let L=k===h.stage;ja({mainContainer:k,label:A,background:I,backgroundTexture:(I==null?void 0:I.texture)||null,app:h},t,0,Ia,f,{skipMainContainerTransform:L})}}catch(k){console.warn("[SCREEN] Error in layout:",k)}}})}let t=await xe("scene.main");window.__editableConfig=t,s(),window.__editableConfigBaseline||(window.__editableConfigBaseline=W(t),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(u=(d=t.engine.runtime)==null?void 0:d.layout)!=null&&u.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(g=>setTimeout(g,100)),t=await xe("scene.main"));let n=await _a(e,t,Nt,de);Oe=n.app;let i=n.gameObjectManager;window.gameApp=Oe,window.gameObjectManager=i;try{window.__liveEditBridge=ni({getConfig:()=>window.__editableConfig,gameObjectManager:i,assets:Ft})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}de&&de.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(ct.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(Oe,i);async function s(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,w=await fetch(v,{cache:"no-cache"});if(!w.ok)return null;let E=await w.text();try{return JSON.parse(E)}catch{return null}},m=await g("configs/flow/app.flow.json");if(!m||typeof m!="object")return;let h=m.screens;if(!h||typeof h!="object")return;let f={},b={};for(let[y,v]of Object.entries(h)){let w=v==null?void 0:v.source;if(typeof w!="string")continue;let E=await g(w),j=E==null?void 0:E.elements;if(!Array.isArray(j))continue;let z=j.map(S=>S==null?void 0:S.instance_id).filter(S=>typeof S=="string");f[y]=z;for(let S of z)b[S]||(b[S]=y)}window.__HANDLER_APP_FLOW=m,window.__HANDLER_SCREEN_INDEX={screenToInstances:f,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,m){if(fl){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${ct.scale.toFixed(3)}`),g.stage){let f=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((w,E)=>{if(w&&w.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(w&&w.scale){let j=w.scale.x||1,z=w.scale.y||1;w.__originalScale||(w.__originalScale={x:j,y:z},console.log(`${v}[RESPONSIVE] Stored original scale for child[${E}]: ${j.toFixed(3)}, ${z.toFixed(3)}`));let S=w.__originalScale.x*ct.scale,_=w.__originalScale.y*ct.scale;typeof w.scale.set=="function"?w.scale.set(S,_):(w.scale.x=S,w.scale.y=_),console.log(`${v}[RESPONSIVE] Child[${E}] scale: ${j.toFixed(3)}\u2192${w.scale.x.toFixed(3)} (type: ${w.constructor.name})`),f(w,y+1)}else w&&console.log(`${v}[RESPONSIVE] Child[${E}] has no scale (type: ${w.constructor.name})`)})};var h=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){ct.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let m=window.gameApp,h=window.gameObjectManager;m&&h?(o(m,h),m.renderer&&(m.renderer.render(m.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!m}) or gameObjectManager (${!!h}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,$e.start()},Is=async()=>{var e,t,n,i;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: ${((n=a.scale.x)!=null?n:1).toFixed(3)}, y: ${((i=a.scale.y)!=null?i:1).toFixed(3)}`)}if(de){de.notifyGameDestroyed();try{Ma&&Ma()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=de.getGameContainer(),s=window.gameObjectManager;if(s&&typeof s.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),s.clear()),Oe){try{Oe.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Oe=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof Ft.resetScene=="function"&&Ft.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{xe("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=W(o)),_a(a,o,Nt).then(l=>{Oe=l.app,window.gameApp=Oe,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=ni({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Ft})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}de&&de.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{$e.start()}catch{}})})},100)},1e3)}};wn();J();var pe={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},_s=1.25,Ps={fontFamily:"Inter, system-ui, sans-serif"};var ai=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=`
|
|
2234
2285
|
position: fixed;
|
|
2235
2286
|
inset: 0;
|
|
2236
2287
|
display: flex;
|
|
@@ -2239,7 +2290,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2239
2290
|
z-index: 50;
|
|
2240
2291
|
user-select: none;
|
|
2241
2292
|
overflow: hidden;
|
|
2242
|
-
background-color: ${
|
|
2293
|
+
background-color: ${pe.background};
|
|
2243
2294
|
`;let t=document.createElement("div");t.style.cssText=`
|
|
2244
2295
|
position: relative;
|
|
2245
2296
|
width: 288px;
|
|
@@ -2269,12 +2320,12 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2269
2320
|
font-size: 12px;
|
|
2270
2321
|
font-weight: 900;
|
|
2271
2322
|
letter-spacing: 0.15em;
|
|
2272
|
-
color: ${
|
|
2323
|
+
color: ${pe.ink};
|
|
2273
2324
|
`,s.innerHTML='LOADING<span class="loading-dots" style="animation: pulse 1.5s infinite;">..</span>',this.progressText=document.createElement("span"),this.progressText.style.cssText=`
|
|
2274
2325
|
font-size: 10px;
|
|
2275
2326
|
font-family: monospace;
|
|
2276
2327
|
font-weight: bold;
|
|
2277
|
-
color: ${
|
|
2328
|
+
color: ${pe.primaryAccent};
|
|
2278
2329
|
`,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,a.appendChild(s),a.appendChild(this.progressText);let o=document.createElement("div");o.style.cssText=`
|
|
2279
2330
|
height: 4px;
|
|
2280
2331
|
width: 100%;
|
|
@@ -2289,7 +2340,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2289
2340
|
border-radius: 9999px;
|
|
2290
2341
|
position: relative;
|
|
2291
2342
|
width: ${this.currentProgress}%;
|
|
2292
|
-
background-color: ${
|
|
2343
|
+
background-color: ${pe.primaryAccent};
|
|
2293
2344
|
`;let l=document.createElement("div");l.style.cssText=`
|
|
2294
2345
|
position: absolute;
|
|
2295
2346
|
inset: 0;
|
|
@@ -2328,7 +2379,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2328
2379
|
font-size: 24px;
|
|
2329
2380
|
letter-spacing: -0.05em;
|
|
2330
2381
|
animation: handlerMove 2.5s linear infinite;
|
|
2331
|
-
color: ${
|
|
2382
|
+
color: ${pe.ink};
|
|
2332
2383
|
display: flex;
|
|
2333
2384
|
align-items: center;
|
|
2334
2385
|
justify-content: center;
|
|
@@ -2341,7 +2392,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2341
2392
|
letter-spacing: 0.3em;
|
|
2342
2393
|
opacity: 0.2;
|
|
2343
2394
|
text-transform: uppercase;
|
|
2344
|
-
color: ${
|
|
2395
|
+
color: ${pe.ink};
|
|
2345
2396
|
`,this.authSeq.textContent=`Auth_Seq: 0x${Math.floor(this.currentProgress*2.55).toString(16).toUpperCase()} // System_Ready`,e.appendChild(t),e.appendChild(this.authSeq),this.injectStyles(),e}injectStyles(){if(document.getElementById("handler-loading-screen-styles"))return;let e=document.createElement("style");e.id="handler-loading-screen-styles",e.textContent=`
|
|
2346
2397
|
/* Box Loading Styles */
|
|
2347
2398
|
.boxLoading {
|
|
@@ -2372,7 +2423,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2372
2423
|
content: '';
|
|
2373
2424
|
width: 50px;
|
|
2374
2425
|
height: 50px;
|
|
2375
|
-
background: ${
|
|
2426
|
+
background: ${pe.primaryAccent};
|
|
2376
2427
|
animation: animate 0.5s linear infinite;
|
|
2377
2428
|
position: absolute;
|
|
2378
2429
|
top: 0;
|
|
@@ -2429,7 +2480,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
|
|
|
2429
2480
|
0%, 100% { opacity: 1; }
|
|
2430
2481
|
50% { opacity: 0.3; }
|
|
2431
2482
|
}
|
|
2432
|
-
`,document.head.appendChild(e)}setProgress(e){this.currentProgress=Math.max(0,Math.min(100,e)),this.progressBar.style.width=`${this.currentProgress}%`,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,this.authSeq.textContent=`Auth_Seq: 0x${Math.floor(this.currentProgress*2.55).toString(16).toUpperCase()} // System_Ready`}mount(e=document.body){e.appendChild(this.container)}unmount(){this.container.parentElement&&this.container.parentElement.removeChild(this.container)}getElement(){return this.container}};var _a=Za.version,bl=new Set(["init","boot","view","ready","start","pause","resume","complete","error","engagement","first_interaction","retry","cta_show","cta_click","cta_dismiss","clickout","conversion","session_time","level_time","load_time","level_start","level_complete","level_fail","checkpoint","reward","tutorial_start","tutorial_complete","tutorial_skip","ab_assign","fps","memory","asset_load_start","asset_load_complete"]);Ja();var Ns={mechanic_id:"TODO_mechanic_id",variant_id:"TODO_variant_id",deployment_id:"TODO_deployment_id",export_id:"TODO_export_id",profile_id:"TODO_profile_id",instance_id:"default"},Fs=Math.random().toString(36).slice(2),dt=null,lt={...Ns},Bs="web_embed",za={},Nt,ja=!1,Ht=!1,Bt=!1,Us=!1,Na=1,ai=0,oi=!1,we=!1,ct="",pt=Math.floor(window.innerWidth),ut=Math.floor(window.innerHeight),$a=pt>ut,xe=!1,Ft=!1,Os=!1,Rs=!1,Oa=!1,ri=null,Ge=null,Da=!1,Ha=!1,ii=new Map;function Gs(){if(!Ge)return null;let r=Date.now()-Ge;return!Number.isFinite(r)||r<0?null:r}function Ra(r){if(Da)return;let e=Gs();e!==null&&(Da=!0,$("session_time",{duration_ms:e,reason:r}))}function zs(){if(dt)return dt;let r=document.createElement("div");return r.id="handler-root",r.setAttribute("data-handler-root","true"),document.body.appendChild(r),dt=r,r}function si(r){switch(r){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return r}}function qs(r,e){return{event_name:r,ts:Date.now(),session_id:Fs,deployment_id:lt.deployment_id,variant_id:lt.variant_id,export_profile_id:lt.profile_id,instance_id:lt.instance_id||"default",env:Bs==="mraid"?"mraid":"web",attribution:Nt,payload:e}}function $(r,e){let t=si(r),n=qs(t,e);gi(n,!!za.analytics),Kt(t,n),t!==r&&Kt(r,n)}function Ut(){ri&&(ri(pt,ut),ri=null)}function gt(r){Na=r,$("volume",r)}function ht(r){r&&(Us=!0),!Bt&&(Bt=!0,$("pause"),gt(0))}function Gt(r){!r&&Us||Bt&&(Bt=!1,$("resume"),gt(Na))}function _e(r,e){pt=Math.floor(r||window.innerWidth),ut=Math.floor(e||window.innerHeight),$a=pt>ut,$("resize",{width:pt,height:ut})}function yl(){if(dr())try{let r=mraid.getMaxSize();_e(r.width,r.height);let e=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?Gt():ht()};if(mraid.addEventListener("viewableChange",e),mraid.addEventListener("stateChange",e),mraid.addEventListener("sizeChange",()=>{let t=mraid.getMaxSize();_e(t.width,t.height)}),mraid.getAudioVolume){let t=mraid.getAudioVolume();gt(t?1:0)}if(mraid.addEventListener("audioVolumeChange",t=>{t!==null&>(t>0?1:0)}),mraid.addEventListener("error",(t,n)=>{console.warn("mraid error:",t,"action:",n)}),oi=!0,mraid.isViewable()&&mraid.getState()!=="hidden")xe=!0,$("boot"),$("view"),$("ready"),we=!0,Ut();else{let t=()=>{xe=!0,$("boot"),$("view"),$("ready"),we=!0,Ut()};mraid.addEventListener("ready",t)}}catch(r){console.warn("MRAID hook skipped",r)}}function vl(){if(pr())try{let r=dapi.getScreenSize();_e(r.width,r.height),dapi.addEventListener("viewableChange",t=>{t.isViewable?Gt():ht()}),dapi.addEventListener("adResized",t=>{let n=dapi.getScreenSize();_e(t.width||n.width,t.height||n.height)});let e=dapi.getAudioVolume();if(gt(e?1:0),dapi.addEventListener("audioVolumeChange",t=>gt(t?1:0)),oi=!0,dapi.isViewable())xe=!0,$("boot"),$("view"),$("ready"),we=!0,Ut();else{let t=()=>{xe=!0,$("boot"),$("view"),$("ready"),we=!0,Ut()};dapi.addEventListener("ready",t)}}catch(r){console.warn("DAPI hook skipped",r)}}function $s(){let r=()=>{xe||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(xe=!0,$("boot"),$("view"),$("ready"),we=!0,Ut(),Ft&&(Ft=!1,re.start()))};window.addEventListener("resize",()=>_e()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(Gt(),r()):ht()}),document.readyState==="complete"||document.readyState==="interactive"?r():window.addEventListener("load",r),oi=!0}function wl(){let r=e=>{typeof TouchEvent!="undefined"&&e instanceof TouchEvent&&(Os=!0),!(Os&&e instanceof MouseEvent)&&(ai+=1,Ha||(Ha=!0,$("first_interaction",{count:ai})),$("interaction",ai))};document.addEventListener("mousedown",r),document.addEventListener("touchstart",r)}function Ds(r){var n,i,a,s,o,l,c,p,d,u,g,m;let e=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none";if((typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed")==="google")try{(n=window.ExitApi)==null||n.exit();return}catch{}if(e==="mraid"&&typeof mraid!="undefined")mraid.open(r||"");else if(e==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(Qe())(a=(i=window.TJ_API)==null?void 0:i.click)==null||a.call(i);else if(ur())(o=(s=window.FbPlayableAd)==null?void 0:s.onCTAClick)==null||o.call(s);else if(mr())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(fr())try{(d=(p=window.smxTracking)==null?void 0:p.redirect)==null||d.call(p)}catch(h){console.warn("Smadex redirect failed",h)}else if(gr()){let h=window.ExitApi;h&&typeof h.exit=="function"?h.exit(r||ct||""):r&&window.open(r)}else Ze()?(u=window.install)==null||u.call(window):hr()?(g=window.openAppStore)==null||g.call(window):hi()?(m=parent==null?void 0:parent.postMessage)==null||m.call(parent,"download","*"):r&&window.open(r)}function xl(){let r=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",e=t=>{if(!t)return;let n=new Image;n.src=t};if(r==="bigabid"){let t=window.BIGABID_BIDTIMEMACROS;if(!t)return;Z("view",()=>e(t.mraid_viewable)),Z("start",()=>e(t.game_viewable)),Z("engagement",()=>e(t.engagement));let n=()=>e(t.complete);Z("complete",n),Yt("engagement",i=>{var a;((a=i==null?void 0:i.payload)==null?void 0:a.count)>3&&n()}),Z("cta_click",()=>e(t.click))}else if(r==="inmobi"){let t=window.INMOBI_DSPMACROS;if(!t)return;Z("view",()=>e(t.Ad_Load_Start)),Z("start",()=>e(t.Ad_Viewable)),Z("engagement",()=>e(t.First_Engagement)),Z("complete",()=>e(t.Gameplay_Complete)),Z("cta_click",()=>e(t.DSP_Click)),Z("start",()=>{[5,10,15,20,25,30].forEach(n=>setTimeout(()=>e(t[`Spent_${n}_Seconds`]),n*1e3))})}}function El(){if(!Qe())return;let r=window.TJ_API;r&&r.setPlayableAPI&&r.setPlayableAPI({skipAd:()=>{try{re.finish()}catch(e){console.warn("Tapjoy skip failed",e)}}})}function Hs(){var e,t,n;let r=window.TJ_API;(e=r==null?void 0:r.objectiveComplete)==null||e.call(r),(t=r==null?void 0:r.playableFinished)==null||t.call(r),(n=r==null?void 0:r.gameplayFinished)==null||n.call(r)}function Sl(){Ze()&&(window.mintGameStart=()=>{Gt(!0),_e()},window.mintGameClose=()=>{ht(!0)})}function Al(){if(!fi())return;let r=window.NUC;!r||!r.trigger||(re.on("cta_click",()=>{var e,t;return(t=(e=r.trigger).convert)==null?void 0:t.call(e,ct)}),re.on("complete",()=>{var e,t;return(t=(e=r.trigger).tryAgain)==null?void 0:t.call(e)}))}var re={init(r={},e){var t;if(Bs=r.profile||"web_embed",za=r.consent||{},lt={...Ns,...r.ids||{}},dt=r.rootEl||dt,Nt=void 0,Ga((t=r.telemetry)!=null&&t.endpoint?r.telemetry:null),Ge=null,Da=!1,Ha=!1,ii.clear(),ct=r.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),e&&(ri=e),$("init"),document.body.oncontextmenu=()=>!1,zs(),Tl(dt),br(),yl(),vl(),!oi){if(document.readyState==="complete")$s();else if(!Rs){Rs=!0;let n=()=>{$s(),window.removeEventListener("load",n),document.removeEventListener("DOMContentLoaded",n)};window.addEventListener("load",n),document.addEventListener("DOMContentLoaded",n)}}wl(),xl(),El(),Sl(),Al(),console.log(`%c @handler/playable-sdk %c v${_a} `,"background: var(--ui-console-info); color: var(--ui-white); font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: var(--ui-console-bg); color: var(--ui-console-text); font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),xe&&!we&&($("boot"),$("view"),$("ready"),Ft&&(Ft=!1,re.start()),we=!0),we=xe},getRoot(){return zs()},get version(){return _a},get maxWidth(){return pt},get maxHeight(){return ut},get isLandscape(){return $a},get isReady(){return we},get isStarted(){return ja},get isPaused(){return Bt},get isFinished(){return Ht},get volume(){return Na},get interactions(){return ai},on(r,e){Yt(si(r),e)},off(r,e){ui(si(r),e)},start(){var r,e;if(!ja){if(!xe){Ft=!0;return}if(ja=!0,Ge||(Ge=Date.now()),$("start"),_e(),Ze())ht(),(r=window.gameReady)==null||r.call(window);else if(Qe()){let t=window.TJ_API;(e=t==null?void 0:t.setPlayableBuild)==null||e.call(t,{orientation:$a?"landscape":"portrait",buildID:_a})}}},finish(){var r,e;Ht||(Ht=!0,$("complete"),Ra("complete"),Ze()?(r=window.gameEnd)==null||r.call(window):hi()?(e=parent==null?void 0:parent.postMessage)==null||e.call(parent,"complete","*"):Qe()&&Hs())},install(r){if(!Ht){Ht=!0,Qe()?(Hs(),setTimeout(()=>re.install(r),300)):($("complete"),setTimeout(()=>re.install(r),0));return}Oa||(Oa=!0,setTimeout(()=>Oa=!1,500),$("cta_click"),$("conversion"),Ra("cta"),Ds(r||ct))},emit(r,e){let t=si(r);if(!bl.has(t)&&t!=="resize"&&t!=="volume"&&!t.startsWith("custom."))throw new Error(`Event ${r} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let n=qs(t,e);gi(n,!!za.analytics),Kt(t,n)},gameStart(){re.start()},gameEnd(){re.finish()},ctaClick(r,e){$("cta_click",{url:r||ct,manual:!0}),(e==null?void 0:e.open)!==!1&&Ds(r||ct)},ctaShow(r){$("cta_show",r)},ctaDismiss(r){$("cta_dismiss",r)},getGameTimeMs(){return Gs()},endSession(r="manual"){Ra(r)},setAttribution(r){Nt=r},abTest(r,e){if(!r)throw new Error("abTest requires experimentId");if(!Array.isArray(e)||e.length<2)throw new Error("abTest requires at least 2 variants");let t=Math.abs(Cl(`${Fs}:${r}`))%e.length,n=e[t];return Nt={...Nt||{},experiment_id:r},lt.variant_id=n,$("ab_assign",{experiment_id:r,variant_id:n}),n},levelStart(r,e){Ge||(Ge=Date.now()),$("level_start",{level_id:r,...e})},levelComplete(r,e){$("level_complete",{level_id:r,...e})},levelFail(r,e){$("level_fail",{level_id:r,...e})},checkpoint(r,e){$("checkpoint",{checkpoint_id:r,...e})},reward(r,e){$("reward",{reward_id:r,...e})},tutorialStart(r,e){$("tutorial_start",{step_id:r,...e})},tutorialComplete(r,e){$("tutorial_complete",{step_id:r,...e})},tutorialSkip(r,e){$("tutorial_skip",{step_id:r,...e})},timerStart(r){r&&ii.set(r,Date.now())},timerEnd(r,e="custom",t){if(!r)return;let n=ii.get(r);if(!n)return;ii.delete(r);let i=Date.now()-n;if(!(!Number.isFinite(i)||i<0)){if(e==="custom"){$("engagement",{action:"timer",key:r,duration_ms:i,...t});return}$(e,{key:r,duration_ms:i,...t})}},fps(r,e){$("fps",{value:r,...e})},memory(r,e){$("memory",{bytes:r,...e})},assetLoadStart(r,e){$("asset_load_start",{asset_id:r,...e})},assetLoadComplete(r,e){$("asset_load_complete",{asset_id:r,...e})},reportError(r,e,t){$("error",{code:r,message:e,...t})},retry(){var r,e,t;if(Ze())(r=window.gameRetry)==null||r.call(window);else if(fi()){let n=window.NUC;(t=(e=n==null?void 0:n.trigger)==null?void 0:e.tryAgain)==null||t.call(e)}$("engagement",{action:"retry"})},pause(){ht(!0)},resume(){Gt(!0)},resize(r,e){_e(r,e)}},Oe=re;function Cl(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e|0}function Tl(r){let e=document.createElement("script");e.type="text/javascript",e.textContent=`
|
|
2483
|
+
`,document.head.appendChild(e)}setProgress(e){this.currentProgress=Math.max(0,Math.min(100,e)),this.progressBar.style.width=`${this.currentProgress}%`,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,this.authSeq.textContent=`Auth_Seq: 0x${Math.floor(this.currentProgress*2.55).toString(16).toUpperCase()} // System_Ready`}mount(e=document.body){e.appendChild(this.container)}unmount(){this.container.parentElement&&this.container.parentElement.removeChild(this.container)}getElement(){return this.container}};var Pa=Qa.version,bl=new Set(["init","boot","view","ready","start","pause","resume","complete","error","engagement","first_interaction","retry","cta_show","cta_click","cta_dismiss","clickout","conversion","session_time","level_time","load_time","level_start","level_complete","level_fail","checkpoint","reward","tutorial_start","tutorial_complete","tutorial_skip","ab_assign","fps","memory","asset_load_start","asset_load_complete"]);Za();var Ns={mechanic_id:"TODO_mechanic_id",variant_id:"TODO_variant_id",deployment_id:"TODO_deployment_id",export_id:"TODO_export_id",profile_id:"TODO_profile_id",instance_id:"default"},Fs=Math.random().toString(36).slice(2),ut=null,dt={...Ns},Bs="web_embed",$a={},Ut,Oa=!1,Bt=!1,qt=!1,Us=!1,Fa=1,si=0,ci=!1,Se=!1,pt="",gt=Math.floor(window.innerWidth),ht=Math.floor(window.innerHeight),Da=gt>ht,Ae=!1,Gt=!1,Os=!1,Rs=!1,Ra=!1,oi=null,We=null,Ha=!1,Na=!1,ri=new Map;function Gs(){if(!We)return null;let r=Date.now()-We;return!Number.isFinite(r)||r<0?null:r}function za(r){if(Ha)return;let e=Gs();e!==null&&(Ha=!0,$("session_time",{duration_ms:e,reason:r}))}function zs(){if(ut)return ut;let r=document.createElement("div");return r.id="handler-root",r.setAttribute("data-handler-root","true"),document.body.appendChild(r),ut=r,r}function li(r){switch(r){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return r}}function qs(r,e){return{event_name:r,ts:Date.now(),session_id:Fs,deployment_id:dt.deployment_id,variant_id:dt.variant_id,export_profile_id:dt.profile_id,instance_id:dt.instance_id||"default",env:Bs==="mraid"?"mraid":"web",attribution:Ut,payload:e}}function $(r,e){let t=li(r),n=qs(t,e);hi(n,!!$a.analytics),Jt(t,n),t!==r&&Jt(r,n)}function Vt(){oi&&(oi(gt,ht),oi=null)}function ft(r){Fa=r,$("volume",r)}function mt(r){r&&(Us=!0),!qt&&(qt=!0,$("pause"),ft(0))}function Wt(r){!r&&Us||qt&&(qt=!1,$("resume"),ft(Fa))}function Re(r,e){gt=Math.floor(r||window.innerWidth),ht=Math.floor(e||window.innerHeight),Da=gt>ht,$("resize",{width:gt,height:ht})}function yl(){if(pr())try{let r=mraid.getMaxSize();Re(r.width,r.height);let e=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?Wt():mt()};if(mraid.addEventListener("viewableChange",e),mraid.addEventListener("stateChange",e),mraid.addEventListener("sizeChange",()=>{let t=mraid.getMaxSize();Re(t.width,t.height)}),mraid.getAudioVolume){let t=mraid.getAudioVolume();ft(t?1:0)}if(mraid.addEventListener("audioVolumeChange",t=>{t!==null&&ft(t>0?1:0)}),mraid.addEventListener("error",(t,n)=>{console.warn("mraid error:",t,"action:",n)}),ci=!0,mraid.isViewable()&&mraid.getState()!=="hidden")Ae=!0,$("boot"),$("view"),$("ready"),Se=!0,Vt();else{let t=()=>{Ae=!0,$("boot"),$("view"),$("ready"),Se=!0,Vt()};mraid.addEventListener("ready",t)}}catch(r){console.warn("MRAID hook skipped",r)}}function vl(){if(ur())try{let r=dapi.getScreenSize();Re(r.width,r.height),dapi.addEventListener("viewableChange",t=>{t.isViewable?Wt():mt()}),dapi.addEventListener("adResized",t=>{let n=dapi.getScreenSize();Re(t.width||n.width,t.height||n.height)});let e=dapi.getAudioVolume();if(ft(e?1:0),dapi.addEventListener("audioVolumeChange",t=>ft(t?1:0)),ci=!0,dapi.isViewable())Ae=!0,$("boot"),$("view"),$("ready"),Se=!0,Vt();else{let t=()=>{Ae=!0,$("boot"),$("view"),$("ready"),Se=!0,Vt()};dapi.addEventListener("ready",t)}}catch(r){console.warn("DAPI hook skipped",r)}}function $s(){let r=()=>{Ae||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(Ae=!0,$("boot"),$("view"),$("ready"),Se=!0,Vt(),Gt&&(Gt=!1,se.start()))};window.addEventListener("resize",()=>Re()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(Wt(),r()):mt()}),document.readyState==="complete"||document.readyState==="interactive"?r():window.addEventListener("load",r),ci=!0}function wl(){let r=e=>{typeof TouchEvent!="undefined"&&e instanceof TouchEvent&&(Os=!0),!(Os&&e instanceof MouseEvent)&&(si+=1,Na||(Na=!0,$("first_interaction",{count:si})),$("interaction",si))};document.addEventListener("mousedown",r),document.addEventListener("touchstart",r)}function Ds(r){var n,i,a,s,o,l,c,p,d,u,g,m;let e=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none";if((typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed")==="google")try{(n=window.ExitApi)==null||n.exit();return}catch{}if(e==="mraid"&&typeof mraid!="undefined")mraid.open(r||"");else if(e==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(tt())(a=(i=window.TJ_API)==null?void 0:i.click)==null||a.call(i);else if(gr())(o=(s=window.FbPlayableAd)==null?void 0:s.onCTAClick)==null||o.call(s);else if(br())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(mr())try{(d=(p=window.smxTracking)==null?void 0:p.redirect)==null||d.call(p)}catch(h){console.warn("Smadex redirect failed",h)}else if(hr()){let h=window.ExitApi;h&&typeof h.exit=="function"?h.exit(r||pt||""):r&&window.open(r)}else et()?(u=window.install)==null||u.call(window):fr()?(g=window.openAppStore)==null||g.call(window):fi()?(m=parent==null?void 0:parent.postMessage)==null||m.call(parent,"download","*"):r&&window.open(r)}function xl(){let r=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",e=t=>{if(!t)return;let n=new Image;n.src=t};if(r==="bigabid"){let t=window.BIGABID_BIDTIMEMACROS;if(!t)return;Q("view",()=>e(t.mraid_viewable)),Q("start",()=>e(t.game_viewable)),Q("engagement",()=>e(t.engagement));let n=()=>e(t.complete);Q("complete",n),Xt("engagement",i=>{var a;((a=i==null?void 0:i.payload)==null?void 0:a.count)>3&&n()}),Q("cta_click",()=>e(t.click))}else if(r==="inmobi"){let t=window.INMOBI_DSPMACROS;if(!t)return;Q("view",()=>e(t.Ad_Load_Start)),Q("start",()=>e(t.Ad_Viewable)),Q("engagement",()=>e(t.First_Engagement)),Q("complete",()=>e(t.Gameplay_Complete)),Q("cta_click",()=>e(t.DSP_Click)),Q("start",()=>{[5,10,15,20,25,30].forEach(n=>setTimeout(()=>e(t[`Spent_${n}_Seconds`]),n*1e3))})}}function El(){if(!tt())return;let r=window.TJ_API;r&&r.setPlayableAPI&&r.setPlayableAPI({skipAd:()=>{try{se.finish()}catch(e){console.warn("Tapjoy skip failed",e)}}})}function Hs(){var e,t,n;let r=window.TJ_API;(e=r==null?void 0:r.objectiveComplete)==null||e.call(r),(t=r==null?void 0:r.playableFinished)==null||t.call(r),(n=r==null?void 0:r.gameplayFinished)==null||n.call(r)}function Sl(){et()&&(window.mintGameStart=()=>{Wt(!0),Re()},window.mintGameClose=()=>{mt(!0)})}function Al(){if(!mi())return;let r=window.NUC;!r||!r.trigger||(se.on("cta_click",()=>{var e,t;return(t=(e=r.trigger).convert)==null?void 0:t.call(e,pt)}),se.on("complete",()=>{var e,t;return(t=(e=r.trigger).tryAgain)==null?void 0:t.call(e)}))}var se={init(r={},e){var t;if(Bs=r.profile||"web_embed",$a=r.consent||{},dt={...Ns,...r.ids||{}},ut=r.rootEl||ut,Ut=void 0,qa((t=r.telemetry)!=null&&t.endpoint?r.telemetry:null),We=null,Ha=!1,Na=!1,ri.clear(),pt=r.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),e&&(oi=e),$("init"),document.body.oncontextmenu=()=>!1,zs(),Tl(ut),yr(),yl(),vl(),!ci){if(document.readyState==="complete")$s();else if(!Rs){Rs=!0;let n=()=>{$s(),window.removeEventListener("load",n),document.removeEventListener("DOMContentLoaded",n)};window.addEventListener("load",n),document.addEventListener("DOMContentLoaded",n)}}wl(),xl(),El(),Sl(),Al(),console.log(`%c @handler/playable-sdk %c v${Pa} `,"background: var(--ui-console-info); color: var(--ui-white); font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: var(--ui-console-bg); color: var(--ui-console-text); font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),Ae&&!Se&&($("boot"),$("view"),$("ready"),Gt&&(Gt=!1,se.start()),Se=!0),Se=Ae},getRoot(){return zs()},get version(){return Pa},get maxWidth(){return gt},get maxHeight(){return ht},get isLandscape(){return Da},get isReady(){return Se},get isStarted(){return Oa},get isPaused(){return qt},get isFinished(){return Bt},get volume(){return Fa},get interactions(){return si},on(r,e){Xt(li(r),e)},off(r,e){gi(li(r),e)},start(){var r,e;if(!Oa){if(!Ae){Gt=!0;return}if(Oa=!0,We||(We=Date.now()),$("start"),Re(),et())mt(),(r=window.gameReady)==null||r.call(window);else if(tt()){let t=window.TJ_API;(e=t==null?void 0:t.setPlayableBuild)==null||e.call(t,{orientation:Da?"landscape":"portrait",buildID:Pa})}}},finish(){var r,e;Bt||(Bt=!0,$("complete"),za("complete"),et()?(r=window.gameEnd)==null||r.call(window):fi()?(e=parent==null?void 0:parent.postMessage)==null||e.call(parent,"complete","*"):tt()&&Hs())},install(r){if(!Bt){Bt=!0,tt()?(Hs(),setTimeout(()=>se.install(r),300)):($("complete"),setTimeout(()=>se.install(r),0));return}Ra||(Ra=!0,setTimeout(()=>Ra=!1,500),$("cta_click"),$("conversion"),za("cta"),Ds(r||pt))},emit(r,e){let t=li(r);if(!bl.has(t)&&t!=="resize"&&t!=="volume"&&!t.startsWith("custom."))throw new Error(`Event ${r} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let n=qs(t,e);hi(n,!!$a.analytics),Jt(t,n)},gameStart(){se.start()},gameEnd(){se.finish()},ctaClick(r,e){$("cta_click",{url:r||pt,manual:!0}),(e==null?void 0:e.open)!==!1&&Ds(r||pt)},ctaShow(r){$("cta_show",r)},ctaDismiss(r){$("cta_dismiss",r)},getGameTimeMs(){return Gs()},endSession(r="manual"){za(r)},setAttribution(r){Ut=r},abTest(r,e){if(!r)throw new Error("abTest requires experimentId");if(!Array.isArray(e)||e.length<2)throw new Error("abTest requires at least 2 variants");let t=Math.abs(Cl(`${Fs}:${r}`))%e.length,n=e[t];return Ut={...Ut||{},experiment_id:r},dt.variant_id=n,$("ab_assign",{experiment_id:r,variant_id:n}),n},levelStart(r,e){We||(We=Date.now()),$("level_start",{level_id:r,...e})},levelComplete(r,e){$("level_complete",{level_id:r,...e})},levelFail(r,e){$("level_fail",{level_id:r,...e})},checkpoint(r,e){$("checkpoint",{checkpoint_id:r,...e})},reward(r,e){$("reward",{reward_id:r,...e})},tutorialStart(r,e){$("tutorial_start",{step_id:r,...e})},tutorialComplete(r,e){$("tutorial_complete",{step_id:r,...e})},tutorialSkip(r,e){$("tutorial_skip",{step_id:r,...e})},timerStart(r){r&&ri.set(r,Date.now())},timerEnd(r,e="custom",t){if(!r)return;let n=ri.get(r);if(!n)return;ri.delete(r);let i=Date.now()-n;if(!(!Number.isFinite(i)||i<0)){if(e==="custom"){$("engagement",{action:"timer",key:r,duration_ms:i,...t});return}$(e,{key:r,duration_ms:i,...t})}},fps(r,e){$("fps",{value:r,...e})},memory(r,e){$("memory",{bytes:r,...e})},assetLoadStart(r,e){$("asset_load_start",{asset_id:r,...e})},assetLoadComplete(r,e){$("asset_load_complete",{asset_id:r,...e})},reportError(r,e,t){$("error",{code:r,message:e,...t})},retry(){var r,e,t;if(et())(r=window.gameRetry)==null||r.call(window);else if(mi()){let n=window.NUC;(t=(e=n==null?void 0:n.trigger)==null?void 0:e.tryAgain)==null||t.call(e)}$("engagement",{action:"retry"})},pause(){mt(!0)},resume(){Wt(!0)},resize(r,e){Re(r,e)}},$e=se;function Cl(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return e|0}function Tl(r){let e=document.createElement("script");e.type="text/javascript",e.textContent=`
|
|
2433
2484
|
(function(){
|
|
2434
2485
|
var events = ['touchstart','touchend','mousedown','keydown'];
|
|
2435
2486
|
function unlock(){
|