handler-playable-sdk 0.5.40 → 0.5.45
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-WTWSWRFR.js → chunk-7PB4AWTL.js} +197 -101
- 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 +278 -182
- package/dist/index.css +46 -0
- package/dist/index.js +1 -1
- package/dist/pixi/index.cjs +16 -16
- package/dist/pixi/index.css +46 -0
- package/dist/pixi/index.js +1 -1
- package/dist/three/index.cjs +39 -39
- package/dist/three/index.css +46 -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 Gt=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 ft=(r,e)=>{for(var t in e)Gt(r,t,{get:e[t],enumerable:!0})},Na=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Xs(e))!Zs.call(r,n)&&n!==t&&Gt(r,n,{get:()=>e[n],enumerable:!(i=Ks(e,n))||i.enumerable});return r};var Ye=(r,e,t)=>(t=r!=null?Ys(Js(r)):{},Na(e||!r||!r.__esModule?Gt(t,"default",{value:r,enumerable:!0}):t,r)),Qs=r=>Na(Gt({},"__esModule",{value:!0}),r);var ue,bn=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),i=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!i)}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: ${N}`),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(!(N==="publish"&&se!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),ge;if(!yn){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),yn=(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 i=await t.text();console.log("[AssetLoader] Received JS code, length:",i.length);let n=i.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(n)try{let a=n[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:",i.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return ge=await yn,console.log("[AssetLoader] Final inline assets cache:",Object.keys(ge)),ge}function vn(r){return r===null||typeof r!="object"||(Object.freeze(r),Object.values(r).forEach(e=>vn(e))),r}function uo(r=64,e=64,t=16711680){let i=document.createElement("canvas");i.width=r,i.height=e;let n=i.getContext("2d");return n.fillStyle=`#${t.toString(16).padStart(6,"0")}`,n.fillRect(0,0,r,e),n.strokeStyle="#000",n.strokeRect(0,0,r,e),n.fillStyle="#fff",n.font="10px sans-serif",n.textAlign="center",n.fillText("MISSING",r/2,e/2),he.Texture.from(i)}function wn(r,e){vr.set(r,e)}var he,br,yr,Re,N,se,Se,ge,yn,vr,ze,Yt=pe(()=>{"use strict";he=require("pixi.js");bn();br=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",yr=oo(),Re=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,N=yr?"publish":br,se=Re==null?void 0:Re.assetsInlined;Re!=null&&Re.buildMode&&(N=Re.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${N}`));Se=co();Se!=null&&Se.buildMode&&(N=Se.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${N}`));(Se==null?void 0:Se.assetsInlined)!==void 0&&(se=Se.assetsInlined);lo().then(r=>{r!=null&&r.buildMode&&r.buildMode!==N&&(N=r.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${N}`)),(r==null?void 0:r.assetsInlined)!==void 0&&(se=r.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${br}, Runtime: ${yr?"publish":"dev"}, Effective: ${N}`);ge={},yn=null;vr=new Map;ze=class{static async load(e,t,i,n){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: ${N}`),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&&n&&(l=o[n],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${n}`)),!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"),N==="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=vr.get(t.type);if(p)try{let d=await p(t.path,l,e,i);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=vn(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 i=N==="publish",n=i&&se!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${N}, isPublishMode: ${i}, inlineData: ${t?"EXISTS":"MISSING"}`),n){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 i=N==="publish",n=i&&se!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${N}, isPublishMode: ${i}, inlineData: ${t?"EXISTS":"MISSING"}`),n){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,i){if(N==="dev"){let a=t==="image"?uo():vn({__placeholder:!0,type:t});return ue.set(e+":"+((i==null?void 0:i.path)||"missing"),a),a}throw i}};wn("image",async(r,e)=>{let t=N==="publish",i=t&&se!==!1,n=N==="brand",a=t&&se===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${N}, isPublishMode: ${t}, isBrandMode: ${n}, inlineData: ${e?"EXISTS":"MISSING"}`),i){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(n||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)});wn("json",async(r,e)=>{let t=N==="publish",i=t&&se!==!1,n=N==="brand",a=t&&se===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${N}, isPublishMode: ${t}, isBrandMode: ${n}, inlineData: ${e?"EXISTS":"MISSING"}`),i){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((n||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 xr={};ft(xr,{AssetTextures:()=>oe,initAssetTextures:()=>Sn});function Sn(r,e){wr.init(r,e),typeof window!="undefined"&&(window.__AssetTextures=oe)}var En,wr,oe,Ze=pe(()=>{"use strict";Yt();En=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(i=>{this.priorityReadyResolve=i}),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 i=new Set(["background_loading_1"]),n=[],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{}}};i.has(o)?n.push(p()):a.push(p())}n.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(n),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 n=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(n.length===0)return;this.ready().catch(()=>{});let a=()=>n.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:n}),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())}},wr=new En,oe=new Proxy(wr,{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={};ft(He,{applyConfigOverride:()=>le,applyConfigOverrides:()=>Ce,applyConfigsToDisk:()=>li,clearConfigOverrides:()=>ee,clearConfigOverridesForObject:()=>Mr,configOverrideManager:()=>_r,deepClone:()=>V,exportConfigsAsJSON:()=>De,getConfigOverrides:()=>Y,getConfigStateSummary:()=>Te,getOverrideMode:()=>Et,redoLastConfigChange:()=>oi,removeConfigOverride:()=>St,resetToApplied:()=>At,resetToOriginal:()=>ci,setOverrideMode:()=>_n,trackObjectCreation:()=>Pr,trackObjectDeletion:()=>jr,undoLastConfigChange:()=>si});function ni(){return typeof window=="undefined"?null:window.__editableConfig||null}function kn(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function Ln(r,e){var t,i;if(!r)return null;try{if(r instanceof Map)return(t=r.get(e))!=null?t:null;if(typeof r=="object")return(i=r[e])!=null?i: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 Lr(r,e){for(let t of e)xt(r,t.path,t.value)}function ai(r){var o;if(typeof window=="undefined")return;let e=ni();if(!e)return;let t=kn(),i=(o=t?Ln(t.objects,r):null)!=null?o:Ln(e.objects,r);if(!i)return;let n=V(i),a=Y().filter(l=>l.objectId===r);try{Lr(n,a)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",r,l);return}Do(e.objects,r,n);let s=window.applyEditableObjectConfig;if(typeof s=="function")try{s(r,n)}catch{}}function In(){var n;if(typeof window=="undefined")return;let r=ni();if(!(r!=null&&r.engine))return;let e=kn(),t=V(((n=e==null?void 0:e.engine)!=null?n:r.engine)||{}),i=Y().filter(a=>!a.objectId&&!a.sceneId);try{Lr(t,i)}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 kr(){return`handler_preview_config_overrides::${Ho()}`}function No(){if(typeof window=="undefined")return[];try{let r=window.localStorage.getItem(kr());if(!r)return[];let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch{return[]}}function ri(r){if(typeof window!="undefined")try{window.localStorage.setItem(kr(),JSON.stringify(r))}catch{}}function Et(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function _n(r){if(typeof window!="undefined"){window.__enableConfigOverrides=r;try{window.localStorage.setItem(Ir,r?"true":"false")}catch{}}}function le(r,e={}){var u,g;let{objectId:t,path:i,value:n}=r,{silent:a=!1,persist:s=!0,emitEvent:o=!0}=e,l=ni();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:i,hasObjects:!!l.objects});return}a||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:i,value:n});let p;try{p=Or(c,i),xt(c,i,n)}catch(m){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:i,value:n},m);return}if(e.trackHistory!==!1){window.__configChanges=window.__configChanges||[];let m=window.__configChanges;m.push({objectId:t,path:i,oldValue:p,newValue:n,ts:Date.now()}),m.length>Mn&&m.shift(),window.__configChangeRedo=[]}if(s){let m=Y(),f=m.findIndex(h=>h.objectId===t&&h.sceneId===r.sceneId&&h.path===i);f>=0?m[f].value=n:m.push(r),window.__configOverrides=m,ri(m),Et()||_n(!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,i=[];for(let n of r)n!=null&&n.objectId&&typeof n.objectId=="string"&&i.push(n.objectId),le(n,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let n=Array.from(new Set(i));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:n,count:r.length}}))}}function ee(){window.__configOverrides=[],window.__configChanges=[],window.__configChangeRedo=[],ri([]),console.log("[CONFIG] Cleared all overrides")}function Mr(r){let e=Y().filter(i=>i.objectId!==r);window.__configOverrides=e,ri(e);let t=window.__configChanges||[];window.__configChanges=t.filter(i=>i.objectId!==r),ai(r),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:r}}))}function St(r,e){let t=Y().filter(n=>n.objectId!==r||n.path!==e);window.__configOverrides=t,ri(t);let i=window.__configChanges||[];window.__configChanges=i.filter(n=>n.objectId!==r||n.path!==e),r?ai(r):In(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:r,path:e}}))}function Y(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=No()),window.__configOverrides||[])}function si(){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 i=kn(),n=!1;if(i){let s=e.objectId?Ln(i.objects,e.objectId):i.engine;if(s){let o=Or(s,e.path);JSON.stringify(o)===JSON.stringify(e.oldValue)&&(n=!0)}}return n?St(e.objectId,e.path):(le({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?ai(e.objectId):In()),console.log("[CONFIG] Undo:",e.path),!0}function oi(){var i;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:n,objectConfigId:a}=e.metadata||{},s=e.newValue;return e.objectId&&n&&s&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,instanceId:e.objectId,objectConfigId:a||((i=s==null?void 0:s.identity)==null?void 0:i.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:n}=e.metadata||{};return e.objectId&&n&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:n})}).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?ai(e.objectId):In(),console.log("[CONFIG] Redo:",e.path),!0}function Pr(r,e,t){var n;if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let i=window.__configChanges;i.push({objectId:r,path:"__object_create__",oldValue:null,newValue:t,ts:Date.now(),changeType:"object_create",metadata:{screenId:e,objectConfigId:(n=t==null?void 0:t.identity)==null?void 0:n.id}}),window.__configChangeRedo=[],i.length>Mn&&i.shift(),console.log("[CONFIG] Tracked object creation:",r)}function jr(r,e,t){if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let i=window.__configChanges;i.push({objectId:r,path:"__object_delete__",oldValue:t,newValue:null,ts:Date.now(),changeType:"object_delete",metadata:{screenId:e}}),window.__configChangeRedo=[],i.length>Mn&&i.shift(),console.log("[CONFIG] Tracked object deletion:",r)}function xt(r,e,t){var s;let i=e.split("."),n=i.pop(),a=r;for(let o of i){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[n]=t}function Or(r,e){return e.split(".").reduce((t,i)=>t?t[i]: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((i,n)=>t.set(n,V(i))),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 Tr(e)}return Tr(r)}function Tr(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 i=r.scenes;if(i instanceof Map)i.forEach((a,s)=>{e.scenes[s]=V(a)});else if(i&&typeof i=="object")for(let a in i)e.scenes[a]=V(i[a]);let n=Y();for(let a of n)a.objectId?(e.objects[a.objectId]||(e.objects[a.objectId]={}),xt(e.objects[a.objectId],a.path,a.value)):a.sceneId?(e.scenes[a.sceneId]||(e.scenes[a.sceneId]={}),xt(e.scenes[a.sceneId],a.path,a.value)):xt(e.engine,a.path,a.value);return e}function Te(){let r=Y(),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 li(r){let e=De(),t={};for(let[n,a]of Object.entries(e.objects)){let s=a,o=n;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${n}`),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[n,a]of Object.entries(e.scenes)){let s=n.startsWith("scene.")?n:`scene.${n}`;t[`scenes/${s}.json`]=a}let i=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:Y().length>0,versionName:r})});if(!i.ok){let n=await i.json();throw new Error(`Apply failed: ${n.error||"Unknown error"}`)}ee();try{let n=ni();n&&(window.__editableConfigBaseline=V(n))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function At(){ee(),window.location.reload()}async function ci(){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"}`)}ee(),window.location.reload()}var Ir,Mn,_r,K=pe(()=>{"use strict";Ir="handler_preview_override_mode";if(typeof window!="undefined"){let r=window.localStorage.getItem(Ir);window.__enableConfigOverrides=r===null?!0:r==="true"}Mn=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 i=r.indexOf(",");if(i===-1)return null;let n=r.slice(0,i);if(!n.includes("application/json")&&!n.includes("text/plain"))return null;let a=r.slice(i+1),s=n.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(/^\.\/+/,""),i=t.split("/").pop()||t,n=[t,i,t.replace(/\.json$/,""),i.replace(/\.json$/,"")];for(let a of n){let s=e[a];if(s){let o=Fo(s,a);if(o!==null)return o}}return null}async function Ct(r){if(Pn.has(r)&&!jn)return console.log(`[CONFIG] Using cached config for: "${r}"`),Pn.get(r);if(console.log(`[CONFIG] loadConfigFile called with: "${r}", MODE: ${H.toUpperCase()}, CACHE: ${jn?"DISABLED":"ENABLED"}`),H==="publish"){let i=Bo(r);return i?(console.log(`[CONFIG] \u2713 Loaded ${r} via INLINE_ASSETS`),i):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${r} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}H==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${r}"`);let e;H==="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(i=>i.startsWith("./")?[i,`/${i.slice(2)}`]:i.startsWith("/")?[i]:[i,`/${i}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let i=jn?"no-store":"force-cache";for(let n of e)try{let a=await fetch(n,{cache:i});if(!a.ok)continue;let s=await a.json();return console.log(`[CONFIG] \u2713 Loaded ${r} via ${n}`,s),s}catch(a){console.warn(`[CONFIG] \u2717 Failed to load ${n} (mode: ${H}):`,a)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${r}; using defaults`),{}})();return Pn.set(r,t),t}async function di(){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 i=H==="publish"||H==="brand"?t.split("/").pop()||t:`configs/${t}`,n=await Ct(i);n.component&&(e.set(n.component,n),console.log(`[CONFIG] \u2713 Schema loaded: ${n.component} ${H==="publish"||H==="brand"?"(flattened)":"(nested)"}`))}catch(i){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,i)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function Le(r){console.log(`[CONFIG] Loading object config: ${r}`);let e=H==="publish"||H==="brand"?`${r}.json`:`configs/objects/${r}.json`;return await Ct(e)}async function pi(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 i=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(i)||(i=`json.${i}`);let n=await Le(i);(!n||Object.keys(n).length===0)&&i!==t.instance_id&&(n=await Le(t.instance_id)),!n||Object.keys(n).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),n=await Le(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...n,instance_id:t.instance_id,object_config:t.object_config})}catch(i){console.warn(`Failed to load object ${t.object_config}:`,i)}}return e}async function ui(){console.log("[CONFIG] Loading engine configs...");let r=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(r.map(i=>{let n=`engine.${i}.json`,a=H==="publish"||H==="brand"?n:`configs/engine/${n}`;return Ct(a)})),t=Object.fromEntries(r.map((i,n)=>[i,e[n]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(r.map(i=>{var s;let n=(s=t[i])!=null?s:{},a=Object.keys(n);return[i,a.length>0?a:"empty"]}))),t}async function On(){return await Ct(H==="publish"||H==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function gi(r="scene.main"){console.log(`[CONFIG] Loading scene config: ${r}`);let e=H==="publish"||H==="brand"?`${r}.json`:`configs/scenes/${r}.json`;return await Ct(e)}function Qe(r,e){let t=[];if(!r.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let i=e.get("identity");if(i)for(let n of i.required||[])r.identity[n]||t.push(`Missing required identity field: ${n}`);for(let[n,a]of Object.entries(r)){if(n==="identity")continue;let s=e.get(n);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 ${n}: ${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(`${n}.${l} value ${p} is below minimum ${d.min}`),d.max!==void 0&&p>d.max&&t.push(`${n}.${l} value ${p} is above maximum ${d.max}`))}}}}return{valid:t.length===0,errors:t}}function Ne(r,e){let t={...r},i=["identity","transform","render"];for(let[n,a]of e.entries())a.defaults&&Object.keys(a.defaults).length>0&&(i.includes(n)||t[n])&&(t[n]||(t[n]={}),t[n]={...a.defaults,...t[n]});return t}function te(r,e,t,i){return typeof r!="number"||!Number.isFinite(r)?e:Math.min(Math.max(r,t),i)}function zr(r,e){if(Array.isArray(r))return{x:te(r[0],e.x,-2e3,2e3),y:te(r[1],e.y,-2e3,2e3)};if(!r||typeof r!="object")return e;let{x:t,y:i}=r;return{x:te(t,e.x,-2e3,2e3),y:te(i,e.y,-2e3,2e3)}}function Uo(r,e){if(Array.isArray(r))return{x:te(r[0],e.x,0,1),y:te(r[1],e.y,0,1)};if(!r||typeof r!="object")return e;let{x:t,y:i}=r;return{x:te(t,e.x,0,1),y:te(i,e.y,0,1)}}function Go(r){if(Array.isArray(r))return{x:te(r[0],.5,-10,10),y:te(r[1],.5,-10,10)};if(r&&typeof r=="object"){let{x:e,y:t}=r;return{x:te(e,.5,-10,10),y:te(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,f,h,b,y,v,S,x;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await di(),i=Y();i.length>0&&console.log(`[CONFIG] Applying ${i.length} active overrides`);let n=await gi(r);console.log(`[CONFIG] Scene config loaded: ${((l=n.objects)==null?void 0:l.length)||0} objects`);let a=await ui();console.log("[CONFIG] Loading object configs...");let s=await pi(n);console.log(`[CONFIG] Loaded ${s.size} object configs:`,Array.from(s.keys()));for(let[w,P]of s.entries()){let E=Ne(P,t),_=Qe(E,t);_.valid||console.warn(`Object ${w} validation errors:`,_.errors),(c=E.transform)!=null&&c.position&&(E.transform.position=zr(E.transform.position,{x:0,y:0})),(p=E.transform)!=null&&p.offset&&(E.transform.offset=zr(E.transform.offset,{x:0,y:0})),((d=E.transform)==null?void 0:d.anchor)!==void 0&&(E.transform.anchor=Go(E.transform.anchor)),((u=E.transform)==null?void 0:u.position_ratio)!==void 0&&E.transform.position_ratio!==null&&(E.transform.position_ratio=Uo(E.transform.position_ratio,{x:.5,y:.5})),s.set(w,E)}if(e){if(e.objects)for(let[w,P]of e.objects.entries())s.set(w,P);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:n,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))),i.length>0&&Et()&&Ce(i,{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((f=a.runtime)!=null?f:{}),assets:Object.keys((h=a.assets)!=null?h:{}),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((x=a.endgame)!=null?x:{})},scene:n.scene_id||"unknown"}),o}function Rn(r){var t,i,n,a,s,o,l,c,p,d,u,g,m,f,h,b,y,v,S,x,w,P,E,_,R,C,A,k,L,I,M,z,T;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[j,O]of r.objects.entries()){let F=((t=O.identity)==null?void 0:t.id)||j;F.includes("character")&&(e.gameplay.character_pos=((i=O.transform)==null?void 0:i.position)||{x:0,y:0},e.gameplay.character_scale=((n=O.transform)==null?void 0:n.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),(F.includes("gun")||F.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)||{}),F.includes("diamond")&&(e.gameplay.diamond=O),F.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=((f=O.transform)==null?void 0:f.position)||{x:0,y:0},e.gameplay.hybrid_melting=((h=O.effects)==null?void 0:h.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||{}),F.includes("water")&&(e.gameplay.water_drops=O),F.includes("crack")&&(e.gameplay.crack=O),F.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=((x=O.transform)==null?void 0:x.scale)||1.5),F.includes("hazard")&&(e.gameplay.hazard=((w=O.gameplay)==null?void 0:w.tuning)||{},e.gameplay.danger_pos=((P=O.transform)==null?void 0:P.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((_=(E=O.gameplay)==null?void 0:E.tuning)==null?void 0:_.danger_pulse)||{},e.gameplay.hazard_height=((C=(R=O.gameplay)==null?void 0:R.tuning)==null?void 0:C.hazard_height)||140)}return e.gameplay.timeline=((A=r.engine.runtime)==null?void 0:A.timeline)||{},e.gameplay.drag_surface=((k=r.engine.runtime)==null?void 0:k.drag_surface)||{},e.gameplay.background=((L=r.engine.runtime)==null?void 0:L.background)||{},e.gameplay.ui_styles=((I=r.engine.runtime)==null?void 0:I.ui_styles)||{},e.gameplay.label_pulse=((M=r.engine.runtime)==null?void 0:M.label_pulse)||{},e.ui=((z=r.engine.runtime)==null?void 0:z.ui)||{},e.theme=((T=r.engine.runtime)==null?void 0:T.theme)||{},e.assets=r.engine.assets||{},e}var Rr,H,Pn,jn,zn=pe(()=>{"use strict";K();Rr=null,H="dev";if(typeof window!="undefined"){let r=window.__BUILD_SETTINGS__;if(r!=null&&r.buildMode)Rr=r,H=r.buildMode,console.log("[CONFIG] Loaded inline build settings:",r,"buildMode:",H);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);Rr=t,H=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",H)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",H)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",H);Pn=new Map,jn=H==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function $n(r,e){let t=[];function i(n,a,s=""){if(n!==a){if(typeof n!=typeof a){t.push(`${s}: type changed`);return}if(typeof n=="object"&&n!==null&&a!==null){let o=new Set([...Object.keys(n),...Object.keys(a)]);for(let l of o){let c=s?`${s}.${l}`:l;l in n?l in a?i(n[l],a[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${s}: changed`)}}return i(r,e),t}function Dn(r,e,t,i){let n={...t};for(let[a,s]of i.entries())n[a]&&s.defaults&&(n[a]={...s.defaults,...n[a]});return n}var Tt,Fe,Hn=pe(()=>{"use strict";Tt=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 i=`${e}?t=${Date.now()}&r=${Math.random()}`,n=await fetch(i,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(n.ok){let a=await n.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(i){console.warn(`Failed to check ${e}:`,i)}}determineEventType(e){var t,i;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:(i=e.split("/").pop())==null?void 0:i.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,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 Fn(r){if(typeof window=="undefined")return;let e=typeof Nn!="undefined"&&!!Nn.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let n=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 f=new Set;f.add("configs/engine/engine.runtime.json"),f.add("configs/engine/engine.assets.json"),f.add("configs/engine/engine.splash.json"),f.add("configs/scenes/scene.main.json");let h=(y=(b=m.scene)==null?void 0:b.objects)!=null?y:[];for(let v of h)v!=null&&v.object_config&&f.add(`configs/objects/${v.object_config}.json`);for(let v of o)f.has(v)||s.unwatch(v);for(let v of f)o.has(v)||s.watch(v,S=>g(S));o=f},c=new Set,p=!1,d=async m=>{let f=await Le(m),h=Ne(f,r.activeConfig.schemas),b=Qe(h,r.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${m} validation errors:`,b.errors),await r.liveEditBridge.applyObjectConfig(m,h)};async function u(m){if(!a){a=!0;try{if(p||c.size===0){r.audioSystem.destroy();let f=await ye("scene.main");r.setActiveConfig(f),r.gameObjectManager.updateConfig(f),r.CustomAssets.updateConfig(f),await r.CustomAssets.ready();let h=r.createAudioSystem(f);r.setAudioSystem(h),window.__audioSystem=h,await h.start(),r.liveEditBridge.rebuildIndexes(),l(f),console.log(`[GAME] Hot-reload complete (${m})`)}else{let f=Array.from(c);c.clear();for(let h of f)await d(h);console.log(`[GAME] Hot-reload updated objects: ${f.join(", ")}`)}}catch(f){console.warn("[GAME] Hot-reload failed:",f)}finally{a=!1,p=!1,c.clear()}}}function g(m){m.type==="object"&&m.objectId?c.add(m.objectId):p=!0,n&&window.clearTimeout(n),n=window.setTimeout(()=>{u(m.type)},120)}e&&Nn.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(r.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var Nn,$r=pe(()=>{"use strict";Hn();zn();Nn={}});var Dr={};ft(Dr,{ConfigWatcher:()=>Fe,DefaultReloadStrategy:()=>Tt,applyDefaults:()=>Ne,diffConfigs:()=>$n,loadAllObjectConfigs:()=>pi,loadComponentSchemas:()=>di,loadEngineConfig:()=>ui,loadGamePromptConfig:()=>On,loadObjectCentricConfig:()=>ye,loadObjectConfig:()=>Le,loadSceneConfig:()=>gi,rehydrateObject:()=>Dn,setupHotReload:()=>Fn,toLegacyFormat:()=>Rn,validateObjectConfig:()=>Qe});var hi=pe(()=>{"use strict";zn();Hn();$r()});var Ss={};ft(Ss,{AssetEditorModal:()=>wa});var wa,xa=pe(()=>{"use strict";wa=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,i,n){this.currentObjectId=e,this.currentPath=t,this.currentAsset=i,this.onApplyCallback=n,this.createModal(e,i),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let i=document.createElement("div");i.className="asset-editor-modal",i.innerHTML=`
|
|
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(),f=m.findIndex(h=>h.objectId===t&&h.sceneId===r.sceneId&&h.path===n);f>=0?m[f].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,f,h,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((f=a.runtime)!=null?f:{}),assets:Object.keys((h=a.assets)!=null?h:{}),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,f,h,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=((f=O.transform)==null?void 0:f.position)||{x:0,y:0},e.gameplay.hybrid_melting=((h=O.effects)==null?void 0:h.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 f=new Set;f.add("configs/engine/engine.runtime.json"),f.add("configs/engine/engine.assets.json"),f.add("configs/engine/engine.splash.json"),f.add("configs/scenes/scene.main.json");let h=(y=(b=m.scene)==null?void 0:b.objects)!=null?y:[];for(let v of h)v!=null&&v.object_config&&f.add(`configs/objects/${v.object_config}.json`);for(let v of o)f.has(v)||s.unwatch(v);for(let v of f)o.has(v)||s.watch(v,S=>g(S));o=f},c=new Set,p=!1,d=async m=>{let f=await Le(m),h=Ne(f,r.activeConfig.schemas),b=tt(h,r.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${m} validation errors:`,b.errors),await r.liveEditBridge.applyObjectConfig(m,h)};async function u(m){if(!a){a=!0;try{if(p||c.size===0){r.audioSystem.destroy();let f=await ye("scene.main");r.setActiveConfig(f),r.gameObjectManager.updateConfig(f),r.CustomAssets.updateConfig(f),await r.CustomAssets.ready();let h=r.createAudioSystem(f);r.setAudioSystem(h),window.__audioSystem=h,await h.start(),r.liveEditBridge.rebuildIndexes(),l(f),console.log(`[GAME] Hot-reload complete (${m})`)}else{let f=Array.from(c);c.clear();for(let h of f)await d(h);console.log(`[GAME] Hot-reload updated objects: ${f.join(", ")}`)}}catch(f){console.warn("[GAME] Hot-reload failed:",f)}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=`
|
|
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=i}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 i=this.modal.querySelector("[data-ai-generate]");i==null||i.addEventListener("click",()=>{this.openAiEditor("generate")});let n=this.modal.querySelector("[data-ai-edit]");n==null||n.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(n=>{n.classList.toggle("active",n.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(n=>{n.classList.toggle("active",n.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 i="";e==="edit"&&this.currentAsset?i=`Edit this image: ${this.currentObjectId}`:i=`Create an image for: ${this.currentObjectId}`,t(this.currentObjectId||"unknown",i,this.currentAsset,{path:this.currentPath,onApply:n=>{this.onApplyCallback&&this.onApplyCallback(n),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={};ft(Ll,{COLORS:()=>de,ConfigWatcher:()=>Fe,DebugPanel:()=>Ot,DefaultReloadStrategy:()=>Tt,Handler:()=>ae,PlayableLoadingScreen:()=>Zi,PreviewShell:()=>Ki,STROKE_WIDTH:()=>_s,THEME:()=>Ps,applyConfigOverride:()=>le,applyConfigOverrides:()=>Ce,applyConfigsToDisk:()=>li,applyDefaults:()=>Ne,baseLottie:()=>hn,bootstrap:()=>ml,clearConfigOverrides:()=>ee,clearConfigOverridesForObject:()=>Mr,configOverrideManager:()=>_r,createPreviewShell:()=>Aa,deepClone:()=>V,default:()=>Oe,defaultPreset:()=>fi,deviceGroups:()=>Gn,devicePresets:()=>Un,diffConfigs:()=>$n,exportConfigsAsJSON:()=>De,getConfigOverrides:()=>Y,getConfigStateSummary:()=>Te,getOverrideMode:()=>Et,getPresetById:()=>Be,getPresetsByCategory:()=>qo,loadAllObjectConfigs:()=>pi,loadComponentSchemas:()=>di,loadEngineConfig:()=>ui,loadGamePromptConfig:()=>On,loadObjectCentricConfig:()=>ye,loadObjectConfig:()=>Le,loadSceneConfig:()=>gi,redoLastConfigChange:()=>oi,rehydrateObject:()=>Dn,removeConfigOverride:()=>St,resetToApplied:()=>At,resetToOriginal:()=>ci,setBootstrapDependencies:()=>hl,setOverrideMode:()=>_n,setupHotReload:()=>Fn,setupLiveEditBridge:()=>Xi,toLegacyFormat:()=>Rn,trackObjectCreation:()=>Pr,trackObjectDeletion:()=>jr,undoLastConfigChange:()=>si,validateObjectConfig:()=>Qe});module.exports=Qs(Ll);var Ee={};function qt(r,e,t=!1){Ee[r]||(Ee[r]=[]),Ee[r].push({fn:e,once:t})}function dn(r,e){if(Ee[r]){if(!e){delete Ee[r];return}Ee[r]=Ee[r].filter(t=>t.fn!==e)}}function Vt(r,...e){let t=Ee[r];if(t)for(let i of[...t])i.fn(...e),i.once&&dn(r,i.fn)}function J(r,e){qt(r,e,!0)}var G=null,ie=[],Ke=null;function Ua(r){G=r,ie=[],Ke!==null&&(clearTimeout(Ke),Ke=null)}function Ga(){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 Fa(r,e,t,i){let n=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(r,new Blob([n],{type:"application/json"}));i&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){i&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0}),i&&console.log("[handler.telemetry] fetch",e)}catch(a){i&&console.warn("[handler.telemetry] fetch failed",a)}}function pn(r,e){let t=Ga();if(e&&t.endpoint){if(ie.push(r),ie.length>t.maxQueue&&(ie=ie.slice(ie.length-t.maxQueue)),ie.length>=t.batchSize){Ba();return}Ke===null&&(Ke=window.setTimeout(()=>{Ke=null,Ba()},t.flushIntervalMs))}}async function Ba(){let r=Ga();if(!r.endpoint||ie.length===0)return;let e=ie.splice(0,r.batchSize);await Fa(r.endpoint,{events:e},r.transport,r.debug),ie.length>0&&await Fa(r.endpoint,{events:ie.splice(0,r.batchSize)},r.transport,r.debug)}function qa(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.]+)\)/),i=t?Number(t[1]):1.8;return n=>1+(i+1)*Math.pow(n-1,3)+i*Math.pow(n-1,2)}return t=>1-(1-t)*(1-t)}function mt(){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 Va(r,e,t){try{r[e]=t}catch{}}function io(r){let e=r==null?void 0:r.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,i=typeof e.y=="number"?e.y:1;return{x:t,y:i}}function Wa(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 Ya(r,e){let t=io(r);if(!t)return{from:null,to:null};let i=null,n=null;return typeof e.scale=="number"?(i=e.scale,n=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(i=e.scale.x),typeof e.scale.y=="number"&&(n=e.scale.y)),typeof e.scaleX=="number"&&(i=e.scaleX),typeof e.scaleY=="number"&&(n=e.scaleY),i===null&&n===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:i!=null?i:t.x,y:n!=null?n:t.y}}}function Ka(){let r=new Set,e=new WeakMap,t=null,i=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),r.size>0&&i()})},n=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),i()},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=mt();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 f=g.durationMs>0?m/g.durationMs:1,h=qa(f),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(f),b-1):0;if(g.repeat>0&&f>=1){let x=f-y;h=qa(x)}let v=g.ease(h);g.yoyo&&y%2===1&&(v=1-v);for(let x of g.props)Va(g.target,x.key,x.from+(x.to-x.from)*v);g.scaleFrom&&g.scaleTo&&Wa(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(f>=b){s(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(p,d,u)=>{var x;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+((x=u==null?void 0:u.delayMsOverride)!=null?x:0)),f=eo(d.ease),h=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 w of Object.keys(d)){if(y.has(w))continue;let P=d[w];typeof P=="number"&&v.push({key:w,from:to(p,w),to:P})}let S=Ya(p,d);return{target:p,startMs:mt(),delayMs:m,durationMs:g,ease:f,props:v,scaleFrom:S.from,scaleTo:S.to,repeat:h,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 n(u),{kill:()=>s(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=mt())},resume:()=>{var f;if(!u.paused)return;let g=(f=u.pauseAtMs)!=null?f:mt(),m=mt()-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"&&Va(p,g,m)}let u=Ya(p,d);u.to&&Wa(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=[],f=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},h=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 h({kind:"to",target:y,vars:v,atMs:f(S)}),b},fromTo(y,v,S,x){return h({kind:"fromTo",target:y,vars:S,from:v,atMs:f(x)}),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 Xa(){if(typeof window=="undefined")return;let r=window;if(!r.gsap)try{r.gsap=Ka()}catch{}}var Ja={name:"handler-playable-sdk",version:"0.5.40",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 Z=0,ao=Z++,Za=Z++,Qa=Z++,er=Z++,tr=Z++,ir=Z++,nr=Z++,ar=Z++,rr=Z++,sr=Z++,or=Z++,lr=Z++,B=ao;function cr(){return B===Za}function dr(){return B===Qa}function pr(){return B===er}function ur(){return B===tr}function Xe(){return B===ir}function Je(){return B===nr}function gr(){return B===ar}function hr(){return B===rr}function fr(){return B===sr}function un(){return B===or}function gn(){return B===lr}function mr(){let r=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(r==="mraid")try{mraid.getState(),B=Za;return}catch{}else if(r==="dapi")try{dapi.isReady(),B=Qa;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(B=er)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(B=tr)}catch{}else if(e==="mintegral")window.gameReady&&(B=ir);else if(e==="tapjoy")window.TJ_API&&(B=nr);else if(e==="tiktok")window.openAppStore&&(B=ar);else if(e==="smadex")try{window.smxTracking&&(B=rr)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(B=sr)}catch{}else e==="vungle"?B=or:(r==="nucleo"||e==="nucleo")&&(B=lr)}var Wt=Ye(require("lottie-web"),1),hn=Wt.default;typeof window!="undefined"&&(window.lottie=Wt.default,window.__baseLottie=Wt.default);var ro=require("pixi.js");var fn=require("pixi.js");var so=null;function mn(r){so=r}Yt();bn();var bt=require("pixi.js");Yt();var go=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",xn=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&&(xn=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${xn}`))}}catch{}function ho(r){var t,i,n,a,s;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(r);let e={center:{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};if(Array.isArray(r))return{x:(t=r[0])!=null?t:.5,y:(i=r[1])!=null?i:.5};if(r&&typeof r=="object"&&"x"in r&&"y"in r)return{x:(n=r.x)!=null?n:.5,y:(a=r.y)!=null?a:.5};if(typeof r=="string"){let o=r.trim().toLowerCase();return(s=e[o])!=null?s:{x:.5,y:.5}}return null}var Ae=class{static async create(e,t,i){var l,c,p,d,u,g,m;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${xn}`);let n=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!n){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let f=new bt.Container;return this.applyTransform(f,t==null?void 0:t.transform,t),f}let a=(c=t==null?void 0:t.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${e}, configId: ${a}, type: ${n.type}, path: ${n.path}`);let s=await ze.load(e,n,i,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(n.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",e),o=new bt.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(n.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 bt.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let f=[n.path,`/assets/${n.path}`,`assets/${n.path}`,`../assets/${n.path}`],h=!1;for(let b of f)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),h=!0;break}}catch{continue}h||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=s)}else o=s;else o=s,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,i){var n,a,s,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(n=t.position.x)!=null?n:0,e.y=(a=t.position.y)!=null?a:0):"position"in e&&e.position&&e.position.set((s=t.position.x)!=null?s:0,(o=t.position.y)!=null?o:0)),t.scale!==void 0&&"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(t.scale):e.scale=t.scale),t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor)){let l=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 yt=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=Ye(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=bo);Ze();var Kt=require("pixi.js");Ze();var An=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new yt}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(n=>!this.instanceCache.has(n));if(t.length===0)return;let i=async n=>{n.length&&(console.log("[Assets] Loading objects:",n),await Promise.all(n.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 i(t);let n=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));n.length>0&&(console.warn("[Assets] Retrying missing assets:",n),await i(n)),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 i=await Ae.create(e,t,this.app);this.instanceCache.set(e,i)}}get(e){return this.instanceCache.get(e)}},yo=new An,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)}});Ze();var Er=require("pixi.js"),fe={width:400,height:600,designWidth:400,scaleFactor:1},Jt={scale:1,position:1},Tn=[];function xo(r,e,t,i,n,a,s){Tn.push({element:r,originalScale:a,positionHelper:e,heightPercent:n}),e(r,t,i,n,a,s,!1)}function Eo(){Tn.forEach(({element:r,originalScale:e,positionHelper:t,heightPercent:i})=>{let n=e*fe.scaleFactor;t(r,fe.width,fe.height,i,n,!0,!1)})}function Cn(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),Jt.scale=fe.scaleFactor,Jt.position=1,console.log(`[SCREEN] Global multipliers - scale: ${Jt.scale.toFixed(3)}`),Eo()}var wt={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 i=wt[r];i&&i[e]!==void 0&&(i[e]=t,console.log(`Updated ${r}.${e} = ${t}`))}function Ao(){return wt}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 Xt(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function Zt(r,e={x:.5,y:.5}){var t;if(Array.isArray(r))return{x:Xt(r[0],e.x),y:Xt(r[1],e.y)};if(r&&typeof r=="object"){let i=r;return{x:Xt(i.x,e.x),y:Xt(i.y,e.y)}}if(typeof r=="string"){let i=r.trim().toLowerCase();return(t=Co[i])!=null?t:e}return e}function Sr(r,e,t,i={}){var g,m,f,h,b,y;let n=Zt(t),a=(g=i.inset)!=null?g:{},s=(m=i.padding)!=null?m:{x:0,y:0},o=((f=a.left)!=null?f:0)+s.x,l=((h=a.right)!=null?h: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*n.x,y:c+u*n.y}}function Ar(r,e,t,i={}){var f,h,b,y,v,S;let n=(f=i.inset)!=null?f:{},a=(h=i.padding)!=null?h:{x:0,y:0},s=((b=n.left)!=null?b:0)+a.x,o=((y=n.right)!=null?y:0)+a.x,l=((v=n.top)!=null?v:0)+a.y,c=((S=n.bottom)!=null?S:0)+a.y,p=Math.max(0,r-s-o),d=Math.max(0,e-l-c),u=Zt(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 i=window.innerWidth,n=window.innerHeight;(i!==r||n!==e)&&(r=i,e=n,Cn(i,n))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),Cn(window.innerWidth,window.innerHeight),window.updateDebugConfig=So,window.getDebugConfig=Ao,window.copyConfig=zo,window.applyConfig=vt,window.applyConfigForRatio=$o,window.positionAtBottom=Cr,window.positionAtTop=ko,window.positionAtCenter=Io,window.positionAtLeft=Mo,window.positionAtRight=_o,window.positionAtBottomLeft=Po,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 Qt(r,e,t=0){return r*e+t}function ei(r,e,t=0){return r*(1-e)+t}function ti(r,e,t=0){return r*e+t}function ii(r,e,t=0){return r*(1-e)+t}function Q(r,e=0){return r/2+e}function To(r,e){return r*e}function Lo(r,e,t,i){var s,o,l,c,p,d,u,g,m,f,h,b,y,v,S,x,w,P,E,_;let n=0,a=0;switch(i.type){case"top":n=Q(e,(o=(s=i.offset)==null?void 0:s.x)!=null?o:0),a=Qt(t,i.percent,(c=(l=i.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":n=Q(e,(d=(p=i.offset)==null?void 0:p.x)!=null?d:0),a=ei(t,i.percent,(g=(u=i.offset)==null?void 0:u.y)!=null?g:0);break;case"left":n=ti(e,i.percent,(f=(m=i.offset)==null?void 0:m.x)!=null?f:0),a=Q(t,(b=(h=i.offset)==null?void 0:h.y)!=null?b:0);break;case"right":n=ii(e,i.percent,(v=(y=i.offset)==null?void 0:y.x)!=null?v:0),a=Q(t,(x=(S=i.offset)==null?void 0:S.y)!=null?x:0);break;case"center":n=Q(e,(P=(w=i.offset)==null?void 0:w.x)!=null?P:0),a=Q(t,(_=(E=i.offset)==null?void 0:E.y)!=null?_:0);break}r.position?r.position.set(n,a):(r.x=n,r.y=a),i.scale!==void 0&&i.scale!==1&&r.scale&&(typeof r.scale.set=="function"?r.scale.set(i.scale,i.scale):(r.scale.x=i.scale,r.scale.y=i.scale))}function Cr(r,e,t,i=.2,n=1,a=!0,s=!1){let o=To(t,i),l=ei(t,i/2);me(r,Q(e),l);let c=a?n*fe.scaleFactor:n;be(r,c),s&&!Tn.find(p=>p.element===r)&&xo(r,Cr,e,t,i,n,a)}function ko(r,e,t,i=.1,n=1){me(r,Q(e),Qt(t,i)),be(r,n)}function Io(r,e,t,i=0,n=0,a=1){me(r,Q(e,i),Q(t,n)),be(r,a)}function Mo(r,e,t,i=.1,n=1){me(r,ti(e,i),Q(t)),be(r,n)}function _o(r,e,t,i=.1,n=1){me(r,ii(e,i),Q(t)),be(r,n)}function Po(r,e,t,i=.05,n=.05,a=1){me(r,ti(e,n),ei(t,i)),be(r,a)}function jo(r,e,t,i=.05,n=.05,a=1){me(r,ii(e,n),ei(t,i)),be(r,a)}function Oo(r,e,t,i=.05,n=.05,a=1){me(r,ti(e,n),Qt(t,i)),be(r,a)}function Ro(r,e,t,i=.05,n=.05,a=1){me(r,ii(e,n),Qt(t,i)),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(wt))}function vt(r){Object.keys(r).forEach(e=>{let t=e;wt[t]&&r[t]&&Object.assign(wt[t],r[t])}),console.log("Config applied:",r)}function $o(r,e){let t=r/e;t>1.6?(vt($e.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(vt($e.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(vt($e.square),console.log("Applied SQUARE config for ratio:",t)):(vt($e.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let r=window;r.configPresets=$e,r.resolveAnchorVec2=r.resolveAnchorVec2||Zt,r.resolveScreenAnchorPoint=r.resolveScreenAnchorPoint||Sr,r.resolveScreenRatioPoint=r.resolveScreenRatioPoint||Ar}hi();function q(r,e){let t=(n,a)=>a===0?n:t(a,n%a),i=t(r,e);return`${r/i}:${e/i}`}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)}],id=[{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)}],nd=[{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)}],Bn=[{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 Un=[...Bn],Gn=[{category:"playable",label:"Playable Ad",devices:Bn}],fi=Bn[0];function Be(r){return Un.find(e=>e.id===r)||fi}function qo(r){return Un.filter(e=>e.category===r)}K();var ke=class{async updateProperty(e,t,i,n={}){var l,c,p;console.log("[PropertyUpdateManager] Updating:",e,t,i);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let s=a(e);if(!s){console.error("[PropertyUpdateManager] Config not found for:",e);return}le({objectId:e,path:t,value:i},{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),n.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let i=t.split("."),n=e;for(let a of i)if(n&&typeof n=="object"&&a in n)n=n[a];else return;return n}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function qn(r){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let i=(a=t.target.files)==null?void 0:a[0];if(!i)return;let n=new FileReader;n.onload=async()=>{let s=n.result,o=r.category||"misc",c=`${(r.objectId||"new_asset").replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")||"new_asset"}_uploaded`;try{let 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.")}},n.readAsDataURL(i)},e.click()}var mi=class{constructor(){this.updateManager=new ke}async handleAction(e,t,i){console.log("[QuickActionsBar] Action:",e,t,i);let n=window.getEditableObjectConfig;if(typeof n!="function")return;let a=n(t);if(!a)return;let s=this.updateManager.getNestedProperty(a,i);if(e==="ai-convert"||e==="upload"||e==="library"){let o=i==="ui.text"||i==="render.asset.path",l=i==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&i!=="render.asset.path"&&(i="render.asset.path"))}switch(e){case"library":this.openLibrary(t,i,s);break;case"ai-edit":this.openAIEditor(t,i,s);break;case"upload":this.openUpload(t,i);break;case"reset":await this.resetToDefault(t,i);break;case"ai-convert":this.handleAiConvert(t,i,s);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var i,n;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let s=((n=(i=t.transform)==null?void 0:i.scale)!=null?n:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",s),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",s)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let i=window.getEditableAssets;if(typeof i!="function")return;let n=i();if(!n||!n.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!n.slots.some(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),n.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"}),n.categories&&!n.categories.includes(p)&&n.categories.push(p),n.libraryAssets&&!n.libraryAssets[p]&&(n.libraryAssets[p]=[]);let d=window.reRenderAssetLibrary;typeof d=="function"&&d()}}openLibrary(e,t,i){var a;let n=window.__debugContext;if(n){if(n.activeTab!=="library"){n.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(n.libraryPanel){let s=window.getEditableObjectConfig,o=s==null?void 0:s(e),l=(a=o==null?void 0:o.identity)==null?void 0:a.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),n.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let a=t.split(".").pop()||t;n(a,`Edit ${a} for ${e}`,i,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var s;let i=window.getEditableObjectConfig,n=i==null?void 0:i(e),a=((s=n==null?void 0:n.identity)==null?void 0:s.category)||(t.split(".")[0]==="render"?"environment":"ui");qn({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 i=await this.getDefaultValue(e,t);i!==void 0?(await this.updateManager.updateProperty(e,t,i),console.log("[QuickActionsBar] Reset to default value:",i)):alert("No default value found for this property.")}catch(i){console.error("[QuickActionsBar] Failed to reset to default:",i),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let i=t.split(".");if(i.length<2)return;let n=i[0],a=i.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(n):typeof s.schemas=="object"&&(o=s.schemas[n]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of a)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let s=`A single, high-quality, high-detail game UI icon/asset representing "${String(i||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",o),n(e,s,"",{objectId:e,path:o});let l=window.__debugContext;if(l){l.activeTab="ai";let c=window.__updateWorkbenchTabs;typeof c=="function"&&c()}}else console.warn("[QuickActionsBar] AI Editor not available")}};var 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"],Hr={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}}},bi=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={};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 f=g.durationMs>0?m/g.durationMs:1,h=Va(f),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(f),b-1):0;if(g.repeat>0&&f>=1){let C=f-y;h=Va(C)}let v=g.ease(h);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(f>=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)),f=eo(d.ease),h=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:f,props:v,scaleFrom:S.from,scaleTo:S.to,repeat:h,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 f;if(!u.paused)return;let g=(f=u.pauseAtMs)!=null?f: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=[],f=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},h=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 h({kind:"to",target:y,vars:v,atMs:f(S)}),b},fromTo(y,v,S,C){return h({kind:"fromTo",target:y,vars:S,from:v,atMs:f(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.45",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 f=new vt.Container;return this.applyTransform(f,t==null?void 0:t.transform,t),f}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 f=[i.path,`/assets/${i.path}`,`assets/${i.path}`,`../assets/${i.path}`],h=!1;for(let b of f)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),h=!0;break}}catch{continue}h||(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,f,h,b,y;let i=tn(t),a=(g=n.inset)!=null?g:{},s=(m=n.padding)!=null?m:{x:0,y:0},o=((f=a.left)!=null?f:0)+s.x,l=((h=a.right)!=null?h: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 f,h,b,y,v,S;let i=(f=n.inset)!=null?f:{},a=(h=n.padding)!=null?h:{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,f,h,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,(f=(m=n.offset)==null?void 0:m.x)!=null?f:0),a=ee(t,(b=(h=n.offset)==null?void 0:h.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=`
|
|
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(Nr).map(e=>`<option value="${e}">${e}</option>`).join("")}
|
|
270
270
|
</select>
|
|
271
271
|
</div>
|
|
272
272
|
<div class="wizard-field-group">
|
|
@@ -288,19 +288,19 @@
|
|
|
288
288
|
</div>
|
|
289
289
|
</div>
|
|
290
290
|
</div>
|
|
291
|
-
`}renderTypeCard(e,t,
|
|
291
|
+
`}renderTypeCard(e,t,n){return`
|
|
292
292
|
<button class="wizard-type-card" type="button" data-object-type="${e}">
|
|
293
293
|
<div class="wizard-type-icon">${t}</div>
|
|
294
|
-
<div class="wizard-type-name">${
|
|
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
|
|
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";Wi({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=Nr[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
|
-
`});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(
|
|
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
|
|
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(
|
|
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
|
+
`)):(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 En=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>
|
|
@@ -309,11 +309,11 @@
|
|
|
309
309
|
<div class="context-menu-item" data-action="inspect">Open in Inspector</div>
|
|
310
310
|
<div class="context-menu-separator"></div>
|
|
311
311
|
<div class="context-menu-item danger" data-action="delete">Delete</div>
|
|
312
|
-
`,this.menu=e}positionMenu(e){if(!this.menu)return;let{x:t,y:
|
|
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:
|
|
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,i,
|
|
315
|
-
`))||(l==null?void 0:l.error)||"Rename failed.";alert(c);return}(
|
|
316
|
-
`))||(o==null?void 0:o.error)||"Move failed.";alert(l);return}(a=(
|
|
312
|
+
`,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 n=e.target.dataset.action;n&&(e.stopPropagation(),this.handleAction(n))}),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))}handleAction(e){var t,n;switch(e){case"duplicate":this.handleDuplicate();break;case"rename":this.handleRename();break;case"move":this.handleMove();break;case"copy":this.handleCopyConfig();break;case"inspect":this.handleOpenInspector();break;case"delete":(n=(t=this.options).onDeleteRequest)==null||n.call(t,this.options.objectId),this.close();break}}async handleDuplicate(){var i,a,s,o,l;let e=`${this.options.objectId}_copy`,t=window.prompt("New instance ID",e);if(!t)return;if(!this.isInstanceIdUnique(t)){alert(`Instance ID "${t}" already exists.`);return}let n=window.confirm(`Share config with original?
|
|
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
|
+
`))||(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
|
+
`))||(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 Fr=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],Sn=class{constructor(e){this.menu=null;this.closeHandler=null;this.keyHandler=null;this.templates=[];this.isLoadingTemplates=!1;this.options=e}async open(e){await this.loadTemplates(),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
317
|
<div class="context-menu-section-title">Objects</div>
|
|
318
318
|
<div class="context-menu-item" data-action="object" data-object-type="sprite">\u{1F5BC}\uFE0F Sprite</div>
|
|
319
319
|
<div class="context-menu-item" data-action="object" data-object-type="ui-image">\u{1F9E9} UI Image</div>
|
|
@@ -329,9 +329,10 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
329
329
|
<div class="context-menu-item" data-action="system" data-system-type="drag-snap-couples">DragSnapCouples</div>
|
|
330
330
|
<div class="context-menu-item" data-action="system" data-system-type="swerve-collect">SwerveCollect</div>
|
|
331
331
|
<div class="context-menu-item" data-action="system" data-system-type="tap-destroy">TapDestroy</div>
|
|
332
|
+
<div class="context-menu-item" data-action="system" data-system-type="scratch-card">ScratchCard</div>
|
|
332
333
|
<div class="context-menu-item" data-action="system" data-system-type="bullet-system">BulletSystem</div>
|
|
333
334
|
<div class="context-menu-item" data-action="system" data-system-type="spawner">Spawner</div>
|
|
334
|
-
`,this.menu=e}positionMenu(e){if(!this.menu)return;let{x:t,y:
|
|
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.dataset.action;if(!n)return;e.stopPropagation();let i=t.dataset.objectType,a=t.dataset.systemType,s=t.dataset.templateId;n==="object"&&i?this.handleCreateObject(i):n==="system"&&a?this.handleCreateSystem(a):n==="template"&&s&&this.handleCreateFromTemplate(s)}),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=`
|
|
335
336
|
<div class="add-menu-modal">
|
|
336
337
|
<div class="add-menu-modal-header">
|
|
337
338
|
<div class="add-menu-modal-title">${this.escapeHtml(e)}</div>
|
|
@@ -340,7 +341,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
340
341
|
<div class="add-menu-modal-body">
|
|
341
342
|
<label class="add-menu-modal-label">Screen:</label>
|
|
342
343
|
<select class="add-menu-modal-select" id="screen-select" required>
|
|
343
|
-
${
|
|
344
|
+
${Fr.map((u,g)=>`<option value="${this.escapeHtml(u.value)}" ${g===2?"selected":""}>${this.escapeHtml(u.label)}</option>`).join("")}
|
|
344
345
|
</select>
|
|
345
346
|
</div>
|
|
346
347
|
<div class="add-menu-modal-footer">
|
|
@@ -348,7 +349,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
348
349
|
<button class="add-menu-modal-btn add-menu-modal-btn-primary" type="button" data-action="confirm">Confirm</button>
|
|
349
350
|
</div>
|
|
350
351
|
</div>
|
|
351
|
-
`;let
|
|
352
|
+
`;let i=()=>{n.parentNode&&n.parentNode.removeChild(n)},a=()=>{let g=n.querySelector("#screen-select").value.trim();if(!g||!Fr.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()})}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=`
|
|
352
353
|
<div class="add-menu-modal">
|
|
353
354
|
<div class="add-menu-modal-header">
|
|
354
355
|
<div class="add-menu-modal-title">${this.escapeHtml(t)}</div>
|
|
@@ -364,15 +365,108 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
364
365
|
<button class="add-menu-modal-btn add-menu-modal-btn-primary" type="button" data-action="confirm">Confirm</button>
|
|
365
366
|
</div>
|
|
366
367
|
</div>
|
|
367
|
-
`;let a=()=>{
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
368
|
+
`;let a=()=>{i.parentNode&&i.parentNode.removeChild(i)},s=()=>{let m=i.querySelector("#name-input").value.trim(),f=this.sanitizeInstanceId(m);if(!f){alert("Invalid name. Use letters, numbers, dots, dashes, or underscores.");return}a(),n(f)},o=()=>{a(),n(null)};i.querySelector(".add-menu-modal").addEventListener("click",g=>{g.stopPropagation()}),(p=i.querySelector('[data-action="confirm"]'))==null||p.addEventListener("click",s),(d=i.querySelector('[data-action="cancel"]'))==null||d.addEventListener("click",o),(u=i.querySelector(".add-menu-modal-close"))==null||u.addEventListener("click",o),i.addEventListener("click",g=>{g.target===i&&o()});let c=i.querySelector("#name-input");c.addEventListener("keydown",g=>{g.key==="Enter"?(g.preventDefault(),s()):g.key==="Escape"&&(g.preventDefault(),o())}),c.select(),document.body.appendChild(i),c.focus()})}async promptSpawnerConfig(){return new Promise(e=>{var m,f,h;let t=document.createElement("div");t.className="add-menu-modal-overlay";let n="template_id",i=`${n}_spawner_1`,a="",s=JSON.stringify([{x:-120,y:-120},{x:0,y:-120},{x:120,y:-120}],null,2),o=JSON.stringify({x:[-240,240],y:[-170,-170]},null,2),l="";t.innerHTML=`
|
|
369
|
+
<div class="add-menu-modal add-menu-modal-wide">
|
|
370
|
+
<div class="add-menu-modal-header">
|
|
371
|
+
<div class="add-menu-modal-title">Create Spawner</div>
|
|
372
|
+
<button class="add-menu-modal-close" type="button">\xD7</button>
|
|
373
|
+
</div>
|
|
374
|
+
<div class="add-menu-modal-body">
|
|
375
|
+
<div class="add-menu-modal-row">
|
|
376
|
+
<label class="add-menu-modal-label">Instance ID:</label>
|
|
377
|
+
<input class="add-menu-modal-input" id="spawner-instance-id" value="${this.escapeHtml(i)}" />
|
|
378
|
+
</div>
|
|
379
|
+
<div class="add-menu-modal-row">
|
|
380
|
+
<label class="add-menu-modal-label">Template ID (single):</label>
|
|
381
|
+
<input class="add-menu-modal-input" id="spawner-template-id" value="${this.escapeHtml(n)}" />
|
|
382
|
+
</div>
|
|
383
|
+
<div class="add-menu-modal-row">
|
|
384
|
+
<label class="add-menu-modal-label">Spawn Templates (JSON, optional):</label>
|
|
385
|
+
<textarea class="add-menu-modal-textarea" id="spawner-spawn-templates" rows="5" placeholder='[{"templateId":"coin.template","weight":3},{"templateId":"gem.template","weight":1}]'>${this.escapeHtml(a)}</textarea>
|
|
386
|
+
<div class="add-menu-modal-hint">If non-empty, overrides single template and supports weights.</div>
|
|
387
|
+
</div>
|
|
388
|
+
|
|
389
|
+
<div class="add-menu-modal-row">
|
|
390
|
+
<label class="add-menu-modal-label">Position Source:</label>
|
|
391
|
+
<select class="add-menu-modal-select" id="spawner-position-source">
|
|
392
|
+
<option value="spawner">spawner</option>
|
|
393
|
+
<option value="points" selected>points</option>
|
|
394
|
+
<option value="random">random</option>
|
|
395
|
+
<option value="target">target</option>
|
|
396
|
+
<option value="custom">custom</option>
|
|
397
|
+
</select>
|
|
398
|
+
</div>
|
|
399
|
+
<div class="add-menu-modal-row">
|
|
400
|
+
<label class="add-menu-modal-label">Spawn Point Mode:</label>
|
|
401
|
+
<select class="add-menu-modal-select" id="spawner-point-mode">
|
|
402
|
+
<option value="cycle" selected>cycle</option>
|
|
403
|
+
<option value="random">random</option>
|
|
404
|
+
</select>
|
|
405
|
+
</div>
|
|
406
|
+
<div class="add-menu-modal-row">
|
|
407
|
+
<label class="add-menu-modal-label">Spawn Points (JSON):</label>
|
|
408
|
+
<textarea class="add-menu-modal-textarea" id="spawner-spawn-points" rows="5">${this.escapeHtml(s)}</textarea>
|
|
409
|
+
</div>
|
|
410
|
+
<div class="add-menu-modal-row">
|
|
411
|
+
<label class="add-menu-modal-label">Random Bounds (JSON):</label>
|
|
412
|
+
<textarea class="add-menu-modal-textarea" id="spawner-random-bounds" rows="3">${this.escapeHtml(o)}</textarea>
|
|
413
|
+
</div>
|
|
414
|
+
|
|
415
|
+
<div class="add-menu-modal-row">
|
|
416
|
+
<label class="add-menu-modal-label">Pattern / Rate:</label>
|
|
417
|
+
<div style="display:flex; gap:8px; width:100%;">
|
|
418
|
+
<select class="add-menu-modal-select" id="spawner-pattern" style="flex:1;">
|
|
419
|
+
<option value="continuous" selected>continuous</option>
|
|
420
|
+
<option value="onClick">onClick</option>
|
|
421
|
+
<option value="wave">wave</option>
|
|
422
|
+
<option value="burst">burst</option>
|
|
423
|
+
</select>
|
|
424
|
+
<input class="add-menu-modal-input" id="spawner-rate" style="flex:1;" value="650" />
|
|
425
|
+
</div>
|
|
426
|
+
<div class="add-menu-modal-hint">Rate is milliseconds between spawns (continuous).</div>
|
|
427
|
+
</div>
|
|
428
|
+
<div class="add-menu-modal-row">
|
|
429
|
+
<label class="add-menu-modal-label">Pool / Lifetime:</label>
|
|
430
|
+
<div style="display:flex; gap:8px; width:100%;">
|
|
431
|
+
<input class="add-menu-modal-input" id="spawner-pool" style="flex:1;" value="18" />
|
|
432
|
+
<input class="add-menu-modal-input" id="spawner-lifetime" style="flex:1;" value="5000" />
|
|
433
|
+
</div>
|
|
434
|
+
</div>
|
|
435
|
+
<div class="add-menu-modal-row">
|
|
436
|
+
<label class="add-menu-modal-label">Return On Invisible:</label>
|
|
437
|
+
<input type="checkbox" id="spawner-return-on-invisible" checked />
|
|
438
|
+
</div>
|
|
439
|
+
|
|
440
|
+
<div class="add-menu-modal-row">
|
|
441
|
+
<label class="add-menu-modal-label">Movement:</label>
|
|
442
|
+
<div style="display:flex; gap:8px; width:100%;">
|
|
443
|
+
<select class="add-menu-modal-select" id="spawner-movement" style="flex:1;">
|
|
444
|
+
<option value="velocity" selected>velocity</option>
|
|
445
|
+
<option value="none">none</option>
|
|
446
|
+
</select>
|
|
447
|
+
<input class="add-menu-modal-input" id="spawner-velocity" style="flex:1;" value="0,320" />
|
|
448
|
+
</div>
|
|
449
|
+
</div>
|
|
450
|
+
<div class="add-menu-modal-row">
|
|
451
|
+
<label class="add-menu-modal-label">Velocity Range (JSON, optional):</label>
|
|
452
|
+
<textarea class="add-menu-modal-textarea" id="spawner-velocity-range" rows="3" placeholder='{"x":[-90,90],"y":[260,420]}'>${this.escapeHtml(l)}</textarea>
|
|
453
|
+
</div>
|
|
454
|
+
</div>
|
|
455
|
+
<div class="add-menu-modal-footer">
|
|
456
|
+
<button class="add-menu-modal-btn add-menu-modal-btn-secondary" type="button" data-action="cancel">Cancel</button>
|
|
457
|
+
<button class="add-menu-modal-btn add-menu-modal-btn-primary" type="button" data-action="confirm">Create</button>
|
|
458
|
+
</div>
|
|
459
|
+
</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 W;let b=t.querySelector("#spawner-instance-id").value.trim(),y=t.querySelector("#spawner-template-id").value.trim(),v=t.querySelector("#spawner-spawn-templates").value,S=t.querySelector("#spawner-position-source").value.trim(),C=t.querySelector("#spawner-point-mode").value.trim(),k=t.querySelector("#spawner-spawn-points").value,z=t.querySelector("#spawner-random-bounds").value,w=t.querySelector("#spawner-pattern").value.trim(),x=Number(t.querySelector("#spawner-rate").value.trim()),M=Number(t.querySelector("#spawner-pool").value.trim()),A=Number(t.querySelector("#spawner-lifetime").value.trim()),E=t.querySelector("#spawner-return-on-invisible").checked,I=t.querySelector("#spawner-movement").value.trim(),L=t.querySelector("#spawner-velocity").value.trim(),_=t.querySelector("#spawner-velocity-range").value,P=p(v),R=Array.isArray(P)&&P.length?P:null,T=typeof((W=R==null?void 0:R[0])==null?void 0:W.templateId)=="string"?String(R[0].templateId):y;if(!b){alert("Instance ID is required.");return}if(!T){alert("Template ID is required (or provide Spawn Templates JSON).");return}let j={templateId:T,spawnPattern:w,spawnRate:Number.isFinite(x)?x:650,poolSize:Number.isFinite(M)?M:18,returnOnInvisible:E,positionSource:S,spawnPointMode:C,movementMode:I,lifetime:Number.isFinite(A)?A:5e3};R&&(j.spawnTemplates=R);let O=p(k);Array.isArray(O)&&(j.spawnPoints=O);let H=p(z);if(H&&typeof H=="object"&&(j.randomBounds=H),L.includes(",")){let[J,qt]=L.split(",").map(li=>li.trim()),qe=Number(J),Ve=Number(qt);Number.isFinite(qe)&&Number.isFinite(Ve)&&(j.velocity={x:qe,y:Ve})}let F=p(_);F&&typeof F=="object"&&(j.velocityRange=F),c(),e({templateId:T,instanceId:b,spawnerProps:j})},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),(f=t.querySelector('[data-action="cancel"]'))==null||f.addEventListener("click",u),(h=t.querySelector(".add-menu-modal-close"))==null||h.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){var o,l,c;this.close();let t=await this.promptScreen();if(!t)return;let n=e==="ui-text"?"text_1":e==="graphics"?"graphics_1":"sprite_1",i=await this.promptName(n);if(!i)return;let a=i,s=this.buildDefaultConfig(e,a,i);try{let p=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:t,instanceId:a,objectConfigId:s.identity.id,layer:e==="ui-image"||e==="ui-text"?"ui":"world",config:s})}),d=await p.json().catch(()=>({}));if(!p.ok||(d==null?void 0:d.success)===!1){let g=((o=d==null?void 0:d.errors)==null?void 0:o.join(`
|
|
461
|
+
`))||(d==null?void 0:d.error)||"Failed to create object.";alert(g);return}let{trackObjectCreation:u}=await Promise.resolve().then(()=>(X(),He));u(a,t,s),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed")),(c=(l=this.options).onRefresh)==null||c.call(l)}catch(p){alert(`Failed to create object: ${p instanceof Error?p.message:String(p)}`)}}async handleCreateFromTemplate(e){var a,s,o;this.close();let t=await this.promptScreen();if(!t)return;let n=e.replace(/\.template$/,"").replace(/^json\./,"").replace(/[._]/g,"_")+"_1",i=await this.promptName(n);if(i)try{let l=await fetch("/api/objects/create-from-template",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({templateId:e,instanceId:i,screenId:t})}),c=await l.json().catch(()=>({}));if(!l.ok||(c==null?void 0:c.success)===!1){let p=((a=c==null?void 0:c.errors)==null?void 0:a.join(`
|
|
462
|
+
`))||(c==null?void 0:c.error)||"Failed to create from template.";alert(p);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(o=(s=this.options).onRefresh)==null||o.call(s)}catch(l){alert(`Failed to create from template: ${l instanceof Error?l.message:String(l)}`)}}async handleCreateSystem(e){var n,i,a,s,o,l,c,p,d,u,g,m,f,h,b,y,v,S,C,k,z;this.close();let t=await this.promptScreen();if(t){if(e==="collectable-system")try{let w=await fetch("/api/systems/collectable-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:t})}),x=await w.json().catch(()=>({}));if(!w.ok||(x==null?void 0:x.success)===!1){let M=((n=x==null?void 0:x.errors)==null?void 0:n.join(`
|
|
463
|
+
`))||(x==null?void 0:x.error)||"Failed to create collectable system.";alert(M);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(a=(i=this.options).onRefresh)==null||a.call(i)}catch(w){alert(`Failed to create collectable system: ${w instanceof Error?w.message:String(w)}`)}if(e==="drag-snap-couples")try{let w=await fetch("/api/systems/drag-snap-couples",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:t})}),x=await w.json().catch(()=>({}));if(!w.ok||(x==null?void 0:x.success)===!1){let M=((s=x==null?void 0:x.errors)==null?void 0:s.join(`
|
|
464
|
+
`))||(x==null?void 0:x.error)||"Failed to create drag-snap system.";alert(M);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(w){alert(`Failed to create drag-snap system: ${w instanceof Error?w.message:String(w)}`)}if(e==="swerve-collect")try{let w=await fetch("/api/systems/swerve-collect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:t})}),x=await w.json().catch(()=>({}));if(!w.ok||(x==null?void 0:x.success)===!1){let M=((c=x==null?void 0:x.errors)==null?void 0:c.join(`
|
|
465
|
+
`))||(x==null?void 0:x.error)||"Failed to create swerve collect system.";alert(M);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(d=(p=this.options).onRefresh)==null||d.call(p)}catch(w){alert(`Failed to create swerve collect system: ${w instanceof Error?w.message:String(w)}`)}if(e==="tap-destroy")try{let w=await fetch("/api/systems/tap-destroy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:t})}),x=await w.json().catch(()=>({}));if(!w.ok||(x==null?void 0:x.success)===!1){let M=((u=x==null?void 0:x.errors)==null?void 0:u.join(`
|
|
466
|
+
`))||(x==null?void 0:x.error)||"Failed to create tap destroy system.";alert(M);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(m=(g=this.options).onRefresh)==null||m.call(g)}catch(w){alert(`Failed to create tap destroy system: ${w instanceof Error?w.message:String(w)}`)}if(e==="scratch-card")try{let w=await fetch("/api/systems/scratch-card",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:t})}),x=await w.json().catch(()=>({}));if(!w.ok||(x==null?void 0:x.success)===!1){let M=((f=x==null?void 0:x.errors)==null?void 0:f.join(`
|
|
467
|
+
`))||(x==null?void 0:x.error)||"Failed to create scratch card system.";alert(M);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(b=(h=this.options).onRefresh)==null||b.call(h)}catch(w){alert(`Failed to create scratch card system: ${w instanceof Error?w.message:String(w)}`)}if(e==="bullet-system")try{let w=await fetch("/api/systems/bullet-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:t})}),x=await w.json().catch(()=>({}));if(!w.ok||(x==null?void 0:x.success)===!1){let M=((y=x==null?void 0:x.errors)==null?void 0:y.join(`
|
|
468
|
+
`))||(x==null?void 0:x.error)||"Failed to create bullet system.";alert(M);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(S=(v=this.options).onRefresh)==null||S.call(v)}catch(w){alert(`Failed to create bullet system: ${w instanceof Error?w.message:String(w)}`)}if(e==="spawner"){let w=await this.promptSpawnerConfig();if(!w)return;let{templateId:x,instanceId:M,spawnerProps:A}=w;try{let E=await fetch("/api/systems/spawner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:t,templateId:x,instanceId:M,spawnerProps:A})}),I=await E.json().catch(()=>({}));if(!E.ok||(I==null?void 0:I.success)===!1){let L=((C=I==null?void 0:I.errors)==null?void 0:C.join(`
|
|
469
|
+
`))||(I==null?void 0:I.error)||"Failed to create spawner.";alert(L);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(z=(k=this.options).onRefresh)==null||z.call(k)}catch(E){alert(`Failed to create spawner: ${E instanceof Error?E.message:String(E)}`)}}}}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 An=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}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`
|
|
376
470
|
<div class="scene-panel scene-objects panel-accent-teal" data-panel="scene-objects">
|
|
377
471
|
<div class="scene-panel-header" data-panel-handle>
|
|
378
472
|
<div class="panel-title">
|
|
@@ -411,8 +505,9 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
411
505
|
</div>
|
|
412
506
|
<div class="panel-resize-handle-v" data-panel-resize-v></div>
|
|
413
507
|
</div>
|
|
414
|
-
`}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
|
|
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=(c=this.root)==null?void 0:c.querySelector("[data-add-object]");n==null||n.addEventListener("click",m=>{m.stopPropagation();let f=n.getBoundingClientRect();this.openAddObjectMenu({x:f.left,y:f.bottom+4})});let i=(p=this.root)==null?void 0:p.querySelector("#scene-screen-filter");if(i){try{let m=window.localStorage.getItem(this.getScreenFilterStorageKey());m&&(this.screenFilter=m)}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 m=i.value||"all";this.screenFilter=m;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=(d=this.root)==null?void 0:d.querySelector("#scene-templates-toggle");if(a){try{let m=window.localStorage.getItem(this.getShowTemplatesStorageKey());this.showTemplates=m==="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()})}(u=this.root)==null||u.addEventListener("click",m=>{let f=m.target;if(!f||f.closest("[data-context-menu]"))return;let h=f.closest(".scene-object-checkbox");if(h||f.tagName==="INPUT"&&f.classList.contains("scene-object-checkbox")){let k=(h||f).dataset.objectId;if(!k)return;m.stopPropagation(),m.preventDefault(),this.toggleSelect(k);return}let b=f.closest("[data-object-id]");if(!b)return;let y=b.dataset.objectId;if(!y)return;let v=m.ctrlKey||m.metaKey;m.shiftKey&&this.lastSelectedIndex>=0?this.selectRange(this.lastSelectedIndex,y):v?this.toggleSelect(y):this.select(y)}),(g=this.listContainer)==null||g.addEventListener("contextmenu",m=>{var C;let f=m.target,h=f==null?void 0:f.closest("[data-object-id]");if(!h)return;let b=h.dataset.objectId;if(!b)return;m.preventDefault();let y=window.getEditableObjectConfig,v=typeof y=="function"?y(b):null;if(!v){let k=window.__editableObjectConfigs;k&&typeof k.get=="function"&&(v=(C=k.get(b))!=null?C:null)}let S=this.inferScreen(b,v);this.showContextMenu(b,S,m.clientX,m.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;p.classList.toggle("selected",u);let g=p.querySelector(".scene-object-checkbox");g&&(g.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"},f=(((c=u==null?void 0:u.identity)==null?void 0:c.id)||p).toString(),h=this.formatDisplayName(f);n.textContent=m[g]||g,i.textContent=h,t.style.display="flex"}else t.style.display="none"}}refreshObjects(){var f;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.getEditableObjectConfig,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof e!="function"){this.scheduleRetry();return}let i=e();if(!Array.isArray(i)||i.length===0){let h=window.__editableObjectConfigs;h&&typeof h.keys=="function"&&(i=Array.from(h.keys()))}if(!Array.isArray(i)||i.length===0){this.scheduleRetry();return}let a=(((f=this.searchInput)==null?void 0:f.value)||"").trim().toLowerCase(),s=["loading","start","gameplay","tutorial","endgame"],o=Object.fromEntries(s.map(h=>[h,[]])),l=Object.fromEntries(s.map(h=>[h,[]])),c=[],p=[];i.forEach(h=>{var _,P,R,T,j;let b=typeof t=="function"?t(h):null;if(!b){let O=window.__editableObjectConfigs;O&&typeof O.get=="function"&&(b=(_=O.get(h))!=null?_:null)}let y=(((P=b==null?void 0:b.identity)==null?void 0:P.category)||"scene").toString(),v=(((R=b==null?void 0:b.identity)==null?void 0:R.id)||h).toString(),S=y.toLowerCase(),C=v.toLowerCase(),k=S.includes("ui")||C.startsWith("ui")||C.includes("label"),z=S==="system",w=((T=b==null?void 0:b.identity)==null?void 0:T.is_template)===!0||C.includes(".template")||h.toLowerCase().includes(".template"),x=this.formatDisplayName(v||h),M=((j=b==null?void 0:b.render)==null?void 0:j.visible)===!1||(b==null?void 0:b.enabled)===!1,A=this.getObjectType(b),E={id:h,label:x,category:y,isUi:k,isTemplate:w,isUnused:M,objectType:A},I=this.inferScreen(E.id,b);if(!(this.screenFilter!=="all"&&I!==this.screenFilter||!(!a||E.id.toLowerCase().includes(a)||E.label.toLowerCase().includes(a)))){if(w){if(!this.showTemplates)return;p.push(E);return}z?c.push(E):(E.isUnused?l:o)[I].push(E)}});let d={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},u=c.length>0?this.renderSystemGroup(c):"",g=s.map(h=>this.renderGroup(d[h],[...o[h],...l[h]])).join(""),m=p.length>0?this.renderGroup("Templates",p):"";if(this.listContainer.innerHTML=u+g+m,this.objectEntries=[...c,...s.flatMap(h=>[...o[h],...l[h]]),...p],c.length>0){let h=this.listContainer.querySelector("[data-delete-system-group]");h==null||h.addEventListener("click",b=>{b.stopPropagation(),this.deleteSystemGroup(c)})}this.updateSelectionUI()}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>':"",d=this.selectedIds.has(a.id);return`
|
|
415
509
|
<button class="scene-object-item ${a.isUnused?"unused":""}" data-object-id="${a.id}">
|
|
510
|
+
<input type="checkbox" class="scene-object-checkbox" ${d?"checked":""} data-object-id="${a.id}">
|
|
416
511
|
<span class="scene-object-label">${a.label}</span>
|
|
417
512
|
${c?`<span class="scene-object-text-preview">${c}</span>`:""}
|
|
418
513
|
${p}
|
|
@@ -422,14 +517,15 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
422
517
|
<div class="scene-object-group">
|
|
423
518
|
<div class="scene-object-group-title">${e} <span class="scene-object-count">${t.length}</span></div>
|
|
424
519
|
<div class="scene-object-group-items">
|
|
425
|
-
${
|
|
520
|
+
${i}
|
|
426
521
|
</div>
|
|
427
522
|
</div>
|
|
428
|
-
`}renderSystemGroup(e){if(!e.length)return"";let t=window.getEditableObjectConfig,
|
|
429
|
-
<button class="scene-object-item ${
|
|
430
|
-
<
|
|
523
|
+
`}renderSystemGroup(e){if(!e.length)return"";let t=window.getEditableObjectConfig,n=e.map(i=>{var p,d;let a=typeof t=="function"?t(i.id):null;if(!a){let u=window.__editableObjectConfigs;u&&typeof u.get=="function"&&(a=(p=u.get(i.id))!=null?p:null)}let s=this.getTypeIconByType(i.objectType),o=this.getAssetPreview(a),l=(d=a==null?void 0:a.ui)!=null&&d.text?`"${a.ui.text.substring(0,12)}${a.ui.text.length>12?"...":""}"`:"",c=this.selectedIds.has(i.id);return`
|
|
524
|
+
<button class="scene-object-item ${i.isUnused?"unused":""}" data-object-id="${i.id}">
|
|
525
|
+
<input type="checkbox" class="scene-object-checkbox" ${c?"checked":""} data-object-id="${i.id}">
|
|
526
|
+
<span class="scene-object-label">${i.label}</span>
|
|
431
527
|
${l?`<span class="scene-object-text-preview">${l}</span>`:""}
|
|
432
|
-
<span class="scene-object-badge system">${
|
|
528
|
+
<span class="scene-object-badge system">${i.category}</span>
|
|
433
529
|
</button>
|
|
434
530
|
`}).join("");return`
|
|
435
531
|
<div class="scene-object-group scene-object-group-system">
|
|
@@ -438,21 +534,21 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
|
|
|
438
534
|
<button class="scene-object-group-delete" data-delete-system-group type="button" title="Delete all system objects">\u{1F5D1}\uFE0F</button>
|
|
439
535
|
</div>
|
|
440
536
|
<div class="scene-object-group-items">
|
|
441
|
-
${
|
|
537
|
+
${n}
|
|
442
538
|
</div>
|
|
443
539
|
</div>
|
|
444
|
-
`}getTypeIconByType(e){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[e]||"\u{1F4E6}"}getTypeIcon(e){var i,
|
|
445
|
-
`))||(o==null?void 0:o.error)||"Delete failed.";alert(l);return}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,
|
|
446
|
-
`))||(l==null?void 0:l.error)||"Delete failed.";
|
|
447
|
-
`):`${
|
|
448
|
-
${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
|
|
540
|
+
`}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.selectedIds.clear(),this.selectedIds.add(e),this.selectedId=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))}toggleSelect(e){var t,n,i;this.selectedIds.has(e)?(this.selectedIds.delete(e),this.selectedId===e&&(this.selectedId=this.selectedIds.size>0?Array.from(this.selectedIds)[0]:null)):(this.selectedIds.add(e),this.selectedId=e),this.updateLastSelectedIndex(e),this.updateSelectionUI(),this.selectedId&&((t=this.options)==null||t.onSelect(this.selectedId)),(i=(n=this.options)==null?void 0:n.onMultiSelect)==null||i.call(n,Array.from(this.selectedIds))}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 Sn({onRefresh:()=>this.refreshObjects(),onClose:()=>{}}).open(e)}catch(t){console.warn("[SceneObjectsPanel] Failed to open AddObjectMenu:",t)}}async openAddObjectWizard(e){try{new xn().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 En({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(`
|
|
541
|
+
`))||(o==null?void 0:o.error)||"Delete failed.";alert(l);return}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(`
|
|
542
|
+
`))||(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(`
|
|
543
|
+
`):`${n} object(s) failed to delete.`;alert(`Deleted ${t} object(s). Errors:
|
|
544
|
+
${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(`
|
|
449
545
|
`))||(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(`
|
|
450
546
|
`):`${s} object(s) failed to delete.`;alert(`Deleted ${a} object(s). Errors:
|
|
451
|
-
${c}`)}await this.syncScreens(),this.refreshObjects()}async moveObject(e,t){var a;let
|
|
452
|
-
`))||(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
|
|
453
|
-
`))||(p==null?void 0:p.error)||"Move failed.";a.push(`${o}: ${d}`)}}catch(c){
|
|
454
|
-
`):`${
|
|
455
|
-
${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-screens",{method:"POST"})}catch(e){console.warn("[SceneObjectsPanel] Failed to sync screens:",e)}}};var
|
|
547
|
+
${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(`
|
|
548
|
+
`))||(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(`
|
|
549
|
+
`))||(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(`
|
|
550
|
+
`):`${i} object(s) failed to move.`;alert(`Moved ${n} object(s). Errors:
|
|
551
|
+
${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-screens",{method:"POST"})}catch(e){console.warn("[SceneObjectsPanel] Failed to sync screens:",e)}}};var Cn=class{constructor(){this.root=null;this.options=null;this.isCollapsed=!1}render(){return`
|
|
456
552
|
<div class="scene-tools-corner-panel ${this.isCollapsed?"collapsed":""}" data-panel="scene-tools-corner">
|
|
457
553
|
<div class="scene-tools-header" data-tools-header data-panel-handle>
|
|
458
554
|
<span class="scene-tools-title">Scene Tools</span>
|
|
@@ -497,7 +593,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
497
593
|
</div>
|
|
498
594
|
</div>
|
|
499
595
|
</div>
|
|
500
|
-
`}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let
|
|
596
|
+
`}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 Tn=class{constructor(){this.root=null;this.options=null}render(){return`
|
|
501
597
|
<div class="nudge-panel hidden" data-panel="nudge-panel">
|
|
502
598
|
<div class="nudge-panel-header" data-panel-handle>
|
|
503
599
|
<span class="nudge-panel-title">Nudge Controls</span>
|
|
@@ -554,7 +650,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
554
650
|
</div>
|
|
555
651
|
</div>
|
|
556
652
|
</div>
|
|
557
|
-
`}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 i
|
|
653
|
+
`}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 It=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`
|
|
558
654
|
<div class="scene-panel library-panel panel-accent-purple" data-panel="library">
|
|
559
655
|
<div class="scene-panel-header" data-panel-handle>
|
|
560
656
|
<div class="panel-title">
|
|
@@ -573,15 +669,15 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
573
669
|
</div>
|
|
574
670
|
<div class="panel-resize-handle" data-panel-resize></div>
|
|
575
671
|
</div>
|
|
576
|
-
`}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 i=(s=this.root)==null?void 0:s.querySelector("[data-create-ai]");i==null||i.addEventListener("click",()=>{this.handleCreateWithAI()});let n=(o=this.root)==null?void 0:o.querySelector("[data-refresh-library]");n==null||n.addEventListener("click",()=>{n.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>n.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,i=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(i.ok){let n=await i.json(),a=this.mergeRegistries(t,n);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 i=t();if(i!=null&&i.slots&&Array.isArray(i.slots)&&i.slots.length>0){this.registry=i,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 i of this.registry.slots)e[i.category]||(e[i.category]=[]),e[i.category].push(i);let t=Date.now();this.slotsContainer.innerHTML="";for(let i of this.registry.categories){let n=e[i]||[];if(n.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(i),a.appendChild(s);let o=document.createElement("div");o.className="library-category-slots";for(let l of n){let c=this.createSlotElement(l,t);o.appendChild(c)}a.appendChild(o),this.slotsContainer.appendChild(a)}}createSlotElement(e,t){let i=this.expandedSlot===e.slotId,n=document.createElement("div");n.className=`library-slot ${i?"expanded":""}`,n.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 h=>{h.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 h=>{h.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 h=>{h.stopPropagation(),await this.handleReset(e)}),d.appendChild(m);let f=document.createElement("span");if(f.className="slot-expand-icon",f.textContent=i?"\u25BC":"\u25B6",d.appendChild(f),a.appendChild(d),a.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===e.slotId?null:e.slotId,this.renderSlots()}),n.appendChild(a),i){let h=this.createLibraryElement(e,t);n.appendChild(h)}return n}createLibraryElement(e,t){var a;let i=document.createElement("div");i.className="slot-library";let n=((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 n)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){i.innerHTML='<div class="library-empty">No alternative assets</div>';return}i.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)}),i.appendChild(p)}}),i.innerHTML='<div class="library-loading">Loading assets...</div>',i}async fetchFolderAssets(e,t){try{let i=await fetch(`/raw/library/${e}/?t=${t}`);if(!i.ok)return[];let n=await i.text(),a=[],s=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=s.exec(n))!==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 i;console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{let n=window.__wizardAssetPicker;if(n!=null&&n.onPick){let a=`raw/library/${e.libraryFolder}/${t}`;n.onPick(a),window.__wizardAssetPicker=null;return}await((i=this.options)==null?void 0:i.onApply(e.objectId,t,e.category)),e.currentAsset=t,this.renderSlots()}catch(n){console.error("[LIBRARY] Failed to apply asset:",n)}}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(i){console.error("[LIBRARY] Failed to reset slot:",i)}}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 i=e.slotId||e.objectId,n="render.texture";e.category==="ui"&&(n="ui.image"),e.category==="audio"&&(n="audio.src"),t(i,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:n})}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 n;let i=(n=t.files)==null?void 0:n[0];if(i){console.log("[Library] File selected:",i.name);try{let a=await this.fileToDataUrl(i);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 i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>t(null),i.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 i=e.startsWith("json.")?e.replace("json.",""):e,n=this.registry.slots.find(a=>(a.objectId===i||a.slotId===i)&&(!t||a.category===t));n?(console.log("[LIBRARY] Highlighting slot:",n.slotId),this.expandedSlot=n.slotId,this.renderSlots(),setTimeout(()=>{var s;let a=(s=this.slotsContainer)==null?void 0:s.querySelector(`[data-slot-id="${n.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 Si=class{detectType(e,t,i){let n=e.toLowerCase();return n==="logic_id"||n==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":n.includes("color")||n.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 Ai=class{render(e,t,i,n){let a=this.formatLabel(t),s=i?this.getThumbnailUrl(i):"";return`
|
|
672
|
+
`}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 h=>{h.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 h=>{h.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 h=>{h.stopPropagation(),await this.handleReset(e)}),d.appendChild(m);let f=document.createElement("span");if(f.className="slot-expand-icon",f.textContent=n?"\u25BC":"\u25B6",d.appendChild(f),a.appendChild(d),a.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===e.slotId?null:e.slotId,this.renderSlots()}),i.appendChild(a),n){let h=this.createLibraryElement(e,t);i.appendChild(h)}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`
|
|
577
673
|
<div class="inspector-property" data-property-type="image">
|
|
578
674
|
<div class="inspector-property-header">
|
|
579
675
|
<label class="inspector-label">${a}</label>
|
|
580
676
|
<div class="inspector-quick-actions">
|
|
581
|
-
<button class="debug-btn debug-btn-sm" data-action="library" data-path="${
|
|
582
|
-
<button class="debug-btn debug-btn-sm" data-action="ai-edit" data-path="${
|
|
583
|
-
<button class="debug-btn debug-btn-sm" data-action="upload" data-path="${
|
|
584
|
-
<button class="debug-btn debug-btn-sm" data-action="reset" data-path="${
|
|
677
|
+
<button class="debug-btn debug-btn-sm" data-action="library" data-path="${i}" data-object="${e}" title="Choose from Library">\u{1F3A8}</button>
|
|
678
|
+
<button class="debug-btn debug-btn-sm" data-action="ai-edit" data-path="${i}" data-object="${e}" title="Edit with AI">\u2728</button>
|
|
679
|
+
<button class="debug-btn debug-btn-sm" data-action="upload" data-path="${i}" data-object="${e}" title="Upload">\u{1F4E4}</button>
|
|
680
|
+
<button class="debug-btn debug-btn-sm" data-action="reset" data-path="${i}" data-object="${e}" title="Reset">\u21BA</button>
|
|
585
681
|
</div>
|
|
586
682
|
</div>
|
|
587
683
|
${s?`
|
|
@@ -595,59 +691,59 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
595
691
|
</div>
|
|
596
692
|
`}
|
|
597
693
|
</div>
|
|
598
|
-
`}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
|
|
694
|
+
`}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 In=class{render(e,t,n,i){let a=n||"#000000";return`
|
|
599
695
|
<div class="inspector-property inspector-property-color">
|
|
600
696
|
<label class="inspector-property-label">${this.formatLabel(t)}</label>
|
|
601
697
|
<div class="inspector-color-group">
|
|
602
698
|
<input type="color"
|
|
603
699
|
class="inspector-color-picker"
|
|
604
700
|
value="${a}"
|
|
605
|
-
data-property-path="${
|
|
701
|
+
data-property-path="${i}"
|
|
606
702
|
data-object-id="${e}" />
|
|
607
703
|
<input type="text"
|
|
608
704
|
class="inspector-input inspector-color-text"
|
|
609
705
|
value="${a}"
|
|
610
|
-
data-property-path="${
|
|
706
|
+
data-property-path="${i}"
|
|
611
707
|
data-object-id="${e}" />
|
|
612
708
|
</div>
|
|
613
709
|
</div>
|
|
614
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
710
|
+
`}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){return`
|
|
615
711
|
<div class="inspector-property inspector-property-number">
|
|
616
712
|
<label class="inspector-property-label">${this.formatLabel(t)}</label>
|
|
617
713
|
<input type="number"
|
|
618
714
|
class="inspector-input"
|
|
619
|
-
value="${
|
|
620
|
-
data-property-path="${
|
|
715
|
+
value="${n}"
|
|
716
|
+
data-property-path="${i}"
|
|
621
717
|
data-object-id="${e}"
|
|
622
718
|
step="any" />
|
|
623
719
|
</div>
|
|
624
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
720
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Pn=class{render(e,t,n,i){let a=String(n||"");return`
|
|
625
721
|
<div class="inspector-property inspector-property-text">
|
|
626
722
|
<label class="inspector-property-label">${this.formatLabel(t)}</label>
|
|
627
723
|
<div class="inspector-input-group">
|
|
628
724
|
<input type="text"
|
|
629
725
|
class="inspector-input"
|
|
630
726
|
value="${a}"
|
|
631
|
-
data-property-path="${
|
|
727
|
+
data-property-path="${i}"
|
|
632
728
|
data-object-id="${e}" />
|
|
633
729
|
</div>
|
|
634
730
|
</div>
|
|
635
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
731
|
+
`}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`
|
|
636
732
|
<div class="inspector-property inspector-property-boolean">
|
|
637
733
|
<label class="inspector-property-label">
|
|
638
734
|
<input type="checkbox"
|
|
639
735
|
class="inspector-checkbox"
|
|
640
|
-
${
|
|
641
|
-
data-property-path="${
|
|
736
|
+
${n?"checked":""}
|
|
737
|
+
data-property-path="${i}"
|
|
642
738
|
data-object-id="${e}" />
|
|
643
739
|
<span>${this.formatLabel(t)}</span>
|
|
644
740
|
</label>
|
|
645
741
|
</div>
|
|
646
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
742
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var jn=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=`
|
|
647
743
|
<button class="inspector-button inspector-button-small"
|
|
648
744
|
data-logic-remove="true"
|
|
649
745
|
data-object-id="${e}"
|
|
650
|
-
data-property-path="${
|
|
746
|
+
data-property-path="${i}"
|
|
651
747
|
data-index="${d}">
|
|
652
748
|
Remove
|
|
653
749
|
</button>
|
|
@@ -669,7 +765,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
669
765
|
<button class="inspector-button inspector-button-small"
|
|
670
766
|
data-logic-convert="true"
|
|
671
767
|
data-object-id="${e}"
|
|
672
|
-
data-property-path="${
|
|
768
|
+
data-property-path="${i}"
|
|
673
769
|
data-index="${d}">
|
|
674
770
|
Convert
|
|
675
771
|
</button>
|
|
@@ -682,7 +778,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
682
778
|
<button class="inspector-button"
|
|
683
779
|
data-logic-add="true"
|
|
684
780
|
data-object-id="${e}"
|
|
685
|
-
data-property-path="${
|
|
781
|
+
data-property-path="${i}">
|
|
686
782
|
Add Logic
|
|
687
783
|
</button>
|
|
688
784
|
`;return`
|
|
@@ -695,19 +791,19 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
695
791
|
${c}
|
|
696
792
|
</div>
|
|
697
793
|
</div>
|
|
698
|
-
`}if(!Array.isArray(
|
|
794
|
+
`}if(!Array.isArray(n)||n.length===0)return`
|
|
699
795
|
<div class="inspector-property inspector-property-array">
|
|
700
796
|
<label class="inspector-property-label">${this.formatLabel(t)}</label>
|
|
701
797
|
<div class="inspector-array-empty">Empty array</div>
|
|
702
798
|
</div>
|
|
703
|
-
`;let a=
|
|
799
|
+
`;let a=n.map((s,o)=>typeof s=="string"?`<div class="inspector-array-item">\u2022 ${s}</div>`:typeof s=="object"?`<div class="inspector-array-item">\u2022 ${JSON.stringify(s)}</div>`:`<div class="inspector-array-item">\u2022 ${String(s)}</div>`).join("");return`
|
|
704
800
|
<div class="inspector-property inspector-property-array">
|
|
705
|
-
<label class="inspector-property-label">${this.formatLabel(t)} (${
|
|
801
|
+
<label class="inspector-property-label">${this.formatLabel(t)} (${n.length} items)</label>
|
|
706
802
|
<div class="inspector-array-list">
|
|
707
803
|
${a}
|
|
708
804
|
</div>
|
|
709
805
|
</div>
|
|
710
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
806
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var On=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"))?`
|
|
711
807
|
<div class="inspector-subsection">
|
|
712
808
|
<div class="inspector-subsection-title">${this.formatLabel(t)}</div>
|
|
713
809
|
<div class="inspector-subsection-content">
|
|
@@ -721,12 +817,12 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
721
817
|
${a.join("")}
|
|
722
818
|
</div>
|
|
723
819
|
</div>
|
|
724
|
-
`}renderLogic(e,t,i
|
|
820
|
+
`}renderLogic(e,t,n,i){let a=[],s=typeof(n==null?void 0:n.id)=="string"?n.id:"",o={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"]},l=(()=>{let u=window,g=Array.isArray(u==null?void 0:u.__HANDLER_LOGIC_OPTIONS)?u.__HANDLER_LOGIC_OPTIONS:[],f=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...g].map(h=>String(h)).filter(h=>h.trim().length>0);return Array.from(new Set(f)).sort((h,b)=>h.localeCompare(b))})(),c=s&&!l.includes(s)?[s,...l]:l;a.push(`
|
|
725
821
|
<div class="inspector-property inspector-property-text">
|
|
726
822
|
<label class="inspector-property-label">Id</label>
|
|
727
823
|
<div class="inspector-input-group">
|
|
728
824
|
<select class="inspector-component-select inspector-input"
|
|
729
|
-
data-property-path="${
|
|
825
|
+
data-property-path="${i}.id"
|
|
730
826
|
data-object-id="${e}"
|
|
731
827
|
data-logic-id-selector="true">
|
|
732
828
|
<option value="" ${s?"":"selected"}>None</option>
|
|
@@ -734,15 +830,15 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
734
830
|
</select>
|
|
735
831
|
</div>
|
|
736
832
|
</div>
|
|
737
|
-
`);for(let u in
|
|
833
|
+
`);for(let u in n){if(u==="id")continue;let g=n[u],m=`${i}.${u}`;if(u==="props"&&g&&typeof g=="object"){let h=[];for(let b in g){let y=g[b],v=`${m}.${b}`,S=o[b];if(b==="targetId"||b==="inputId"){let C=this.registry.getObjectIds(),k=typeof y=="string"?y:"",z=k&&!C.includes(k)?[k,...C]:C;h.push(`
|
|
738
834
|
<div class="inspector-property inspector-property-text">
|
|
739
835
|
<label class="inspector-property-label">${this.formatLabel(b)}</label>
|
|
740
836
|
<div class="inspector-input-group">
|
|
741
837
|
<select class="inspector-component-select inspector-input"
|
|
742
838
|
data-property-path="${v}"
|
|
743
839
|
data-object-id="${e}">
|
|
744
|
-
<option value="" ${
|
|
745
|
-
${
|
|
840
|
+
<option value="" ${k?"":"selected"}>None</option>
|
|
841
|
+
${z.map(w=>`<option value="${w}" ${w===k?"selected":""}>${w}</option>`).join("")}
|
|
746
842
|
</select>
|
|
747
843
|
</div>
|
|
748
844
|
</div>
|
|
@@ -753,23 +849,23 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
753
849
|
<select class="inspector-component-select inspector-input"
|
|
754
850
|
data-property-path="${v}"
|
|
755
851
|
data-object-id="${e}">
|
|
756
|
-
${S.map(
|
|
852
|
+
${S.map(C=>`<option value="${String(C)}" ${String(C)===String(y)?"selected":""}>${String(C)}</option>`).join("")}
|
|
757
853
|
</select>
|
|
758
854
|
</div>
|
|
759
855
|
</div>
|
|
760
|
-
`);else{let
|
|
856
|
+
`);else{let C=this.registry.renderProperty(e,b,y,v);C&&h.push(C)}}h.length&&a.push(`
|
|
761
857
|
<div class="inspector-property inspector-property-object">
|
|
762
858
|
<div class="inspector-object-header">Props</div>
|
|
763
859
|
<div class="inspector-object-body">
|
|
764
860
|
${h.join("")}
|
|
765
861
|
</div>
|
|
766
862
|
</div>
|
|
767
|
-
`);continue}let f=this.registry.renderProperty(e,u,g,m);f&&a.push(f)}if(a.length===0)return"";let d=/(^|\.)logic\.\d+$/.test(
|
|
863
|
+
`);continue}let f=this.registry.renderProperty(e,u,g,m);f&&a.push(f)}if(a.length===0)return"";let d=/(^|\.)logic\.\d+$/.test(i)?"":`
|
|
768
864
|
<div class="inspector-array-actions" style="margin-top: 12px;">
|
|
769
865
|
<button class="inspector-button"
|
|
770
866
|
data-logic-add="true"
|
|
771
867
|
data-object-id="${e}"
|
|
772
|
-
data-property-path="${
|
|
868
|
+
data-property-path="${i}"
|
|
773
869
|
style="width: 100%;">
|
|
774
870
|
\u2795 Add Another Logic
|
|
775
871
|
</button>
|
|
@@ -782,45 +878,45 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
782
878
|
${d}
|
|
783
879
|
</div>
|
|
784
880
|
</div>
|
|
785
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
881
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Rn=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`
|
|
786
882
|
<div class="inspector-property inspector-property-text">
|
|
787
883
|
<label class="inspector-property-label">${this.formatLabel(t)}</label>
|
|
788
884
|
<div class="inspector-input-group">
|
|
789
885
|
<select class="inspector-component-select inspector-input"
|
|
790
|
-
data-property-path="${
|
|
886
|
+
data-property-path="${i}"
|
|
791
887
|
data-object-id="${e}">
|
|
792
888
|
${l.map(c=>`<option value="${c}" ${c===s?"selected":""}>${c}</option>`).join("")}
|
|
793
889
|
</select>
|
|
794
890
|
</div>
|
|
795
891
|
</div>
|
|
796
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
892
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var zn=class{render(e,t,n,i){let a=this.safeStringify(n);return`
|
|
797
893
|
<div class="inspector-property inspector-property-text">
|
|
798
894
|
<label class="inspector-property-label">${this.formatLabel(t)}</label>
|
|
799
895
|
<div class="inspector-input-group">
|
|
800
896
|
<textarea class="inspector-input"
|
|
801
|
-
data-property-path="${
|
|
897
|
+
data-property-path="${i}"
|
|
802
898
|
data-object-id="${e}"
|
|
803
899
|
data-json="true"
|
|
804
900
|
rows="6">${a}</textarea>
|
|
805
901
|
</div>
|
|
806
902
|
</div>
|
|
807
|
-
`}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
|
|
903
|
+
`}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 $n=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`
|
|
808
904
|
<div class="inspector-row" style="gap:8px; align-items:center;">
|
|
809
905
|
<input type="number"
|
|
810
906
|
class="inspector-input"
|
|
811
907
|
value="${c}"
|
|
812
|
-
data-property-path="${
|
|
908
|
+
data-property-path="${i}.${l}.x"
|
|
813
909
|
data-object-id="${e}" />
|
|
814
910
|
<input type="number"
|
|
815
911
|
class="inspector-input"
|
|
816
912
|
value="${p}"
|
|
817
|
-
data-property-path="${
|
|
913
|
+
data-property-path="${i}.${l}.y"
|
|
818
914
|
data-object-id="${e}" />
|
|
819
915
|
<button type="button"
|
|
820
916
|
class="inspector-btn inspector-btn-sm"
|
|
821
917
|
data-spawnpoints-remove="true"
|
|
822
918
|
data-object-id="${e}"
|
|
823
|
-
data-property-path="${
|
|
919
|
+
data-property-path="${i}"
|
|
824
920
|
data-index="${l}">Remove</button>
|
|
825
921
|
</div>
|
|
826
922
|
`}).join("");return`
|
|
@@ -833,14 +929,14 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
833
929
|
class="inspector-btn inspector-btn-sm primary"
|
|
834
930
|
data-spawnpoints-add="true"
|
|
835
931
|
data-object-id="${e}"
|
|
836
|
-
data-property-path="${
|
|
932
|
+
data-property-path="${i}">Add Point</button>
|
|
837
933
|
</div>
|
|
838
934
|
</div>
|
|
839
935
|
</div>
|
|
840
|
-
`}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 Dn=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`
|
|
841
937
|
<div class="inspector-row" style="gap:8px; align-items:center;">
|
|
842
938
|
<select class="inspector-select inspector-input"
|
|
843
|
-
data-property-path="${
|
|
939
|
+
data-property-path="${i}.${p}.templateId"
|
|
844
940
|
data-object-id="${e}">
|
|
845
941
|
${g}
|
|
846
942
|
</select>
|
|
@@ -849,13 +945,13 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
849
945
|
style="width:72px;"
|
|
850
946
|
value="${u}"
|
|
851
947
|
placeholder="weight"
|
|
852
|
-
data-property-path="${
|
|
948
|
+
data-property-path="${i}.${p}.weight"
|
|
853
949
|
data-object-id="${e}" />
|
|
854
950
|
<button type="button"
|
|
855
951
|
class="inspector-btn inspector-btn-sm"
|
|
856
952
|
data-spawntemplates-remove="true"
|
|
857
953
|
data-object-id="${e}"
|
|
858
|
-
data-property-path="${
|
|
954
|
+
data-property-path="${i}"
|
|
859
955
|
data-index="${p}">Remove</button>
|
|
860
956
|
</div>
|
|
861
957
|
`}).join("");return`
|
|
@@ -868,21 +964,21 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{await fetch("/api/sync-scre
|
|
|
868
964
|
class="inspector-btn inspector-btn-sm primary"
|
|
869
965
|
data-spawntemplates-add="true"
|
|
870
966
|
data-object-id="${e}"
|
|
871
|
-
data-property-path="${
|
|
967
|
+
data-property-path="${i}">Add Template</button>
|
|
872
968
|
</div>
|
|
873
969
|
</div>
|
|
874
970
|
</div>
|
|
875
|
-
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var
|
|
971
|
+
`}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Hn=class{constructor(){this.typeDetector=new Ln,this.imageRenderer=new kn,this.colorRenderer=new In,this.numberRenderer=new Mn,this.textRenderer=new Pn,this.booleanRenderer=new _n,this.arrayRenderer=new jn(this),this.objectRenderer=new On(this),this.selectRenderer=new Rn,this.jsonRenderer=new zn,this.spawnPointsRenderer=new $n,this.spawnTemplatesRenderer=new Dn(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(),f=this.selectRenderer.render(e,t,n,i,m);return s?`
|
|
876
972
|
${f}
|
|
877
973
|
<div class="inspector-array-actions">
|
|
878
974
|
<button class="inspector-button"
|
|
879
975
|
data-logic-add="true"
|
|
880
976
|
data-object-id="${e}"
|
|
881
|
-
data-property-path="${
|
|
977
|
+
data-property-path="${i}">
|
|
882
978
|
Add Logic
|
|
883
979
|
</button>
|
|
884
980
|
</div>
|
|
885
|
-
`:f}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&&
|
|
981
|
+
`:f}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(),f=this.selectRenderer.render(e,t,n!=null?n:"",i,["",...m]);return t==="hitTemplateId"&&i.includes("logic.props")?f+'<div class="inspector-text-sm" style="opacity:0.7; margin-top:4px;">Use template id (e.g. bullet_template), not spawner.</div>':f}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 f=["1","-1"],h=n==null?"1":String(n);return this.selectRenderer.render(e,t,h,i,f)}if(["speed","amplitude","intensity","minScale","maxScale","radius","lifetime","pivotOffsetX","pivotOffsetY","duration","delay","startScale","startAlpha","startYOffset","startXOffset"].includes(t)){let f=typeof n=="number"&&!Number.isNaN(n)?n:0;return this.numberRenderer.render(e,t,f,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 Nn=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 Hn,this.updateManager=new ke,this.quickActions=new wn;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`
|
|
886
982
|
<div class="scene-panel inspector-panel panel-accent-violet" data-panel="inspector">
|
|
887
983
|
<div class="scene-panel-header" data-panel-handle>
|
|
888
984
|
<div class="panel-title">
|
|
@@ -903,7 +999,7 @@ ${f}
|
|
|
903
999
|
</div>
|
|
904
1000
|
</div>
|
|
905
1001
|
</div>
|
|
906
|
-
`}initialize(e,t){var
|
|
1002
|
+
`}initialize(e,t){var n;this.options=t,this.root=e.querySelector('[data-panel="inspector"]'),this.contentContainer=(n=this.root)==null?void 0:n.querySelector("[data-inspector-content]")}loadObject(e){this.selectedObjectId=e;let t=window.getEditableObjectConfig;if(typeof t!="function"){this.showError("Config system not ready");return}let n=t(e);if(!n){console.error("[InspectorPanel] Object not found in config system:",e),this.showError(`Object not found: ${e}`);return}this.renderProperties(e,n)}renderProperties(e,t){if(!this.contentContainer)return;let n=[],i=t.identity||{},a=i.id||e,s=i.category||"unknown";n.push(`
|
|
907
1003
|
<div class="inspector-header">
|
|
908
1004
|
<div class="inspector-header-info">
|
|
909
1005
|
<div class="inspector-object-name">${a}</div>
|
|
@@ -911,7 +1007,7 @@ ${f}
|
|
|
911
1007
|
</div>
|
|
912
1008
|
${this.renderConversionButtons(e,t)}
|
|
913
1009
|
</div>
|
|
914
|
-
`);let o=["transform","ui","render","gameplay","interaction","audio","effects","physics","motion","identity"];for(let l of o){let c=t[l];if(c){if(!this.showAdvanced&&!this.isSectionMeaningful(l,c,t))continue;
|
|
1010
|
+
`);let o=["transform","ui","render","gameplay","interaction","audio","effects","physics","motion","identity"];for(let l of o){let c=t[l];if(c){if(!this.showAdvanced&&!this.isSectionMeaningful(l,c,t))continue;n.push(this.renderSection(e,l,c,l))}}for(let l in t)if(!o.includes(l)&&typeof t[l]=="object"&&t[l]!==null){if(!this.showAdvanced&&!this.isSectionMeaningful(l,t[l],t))continue;n.push(this.renderSection(e,l,t[l],l))}this.contentContainer.innerHTML=n.join("")+this.renderFooter(t),this.attachEventListeners(),this.expandMotionOnNextRender=!1}renderConversionButtons(e,t){var o,l,c,p;let n=!!t.ui,i=((o=t.ui)==null?void 0:o.renderMode)==="png"||((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.type)==="image";if(!(n||e.includes("ui_endgame")||e.includes("splash")||e.includes("button")||e.includes("label"))||i)return"";let s=(p=t.ui)!=null&&p.text?"ui.text":"render.asset.path";return`
|
|
915
1011
|
<div class="inspector-quick-actions">
|
|
916
1012
|
<button class="debug-btn debug-btn-sm success ai-simple-btn" type="button" data-convert-toggle>
|
|
917
1013
|
\u2728 Convert to PNG
|
|
@@ -922,17 +1018,17 @@ ${f}
|
|
|
922
1018
|
<button class="debug-btn debug-btn-sm" data-action="upload" data-path="render.asset.path" data-object="${e}">\u{1F4E4} Upload</button>
|
|
923
1019
|
</div>
|
|
924
1020
|
</div>
|
|
925
|
-
`}renderFooter(e){let t=["logic","motion","effects","ui","audio","physics","interaction","gameplay","visibility"],
|
|
1021
|
+
`}renderFooter(e){let t=["logic","motion","effects","ui","audio","physics","interaction","gameplay","visibility"],n=Object.keys(e),i=t.filter(a=>!n.includes(a));return i.length===0?"":`
|
|
926
1022
|
<div class="inspector-footer">
|
|
927
1023
|
<div class="inspector-add-component">
|
|
928
1024
|
<select class="inspector-component-select" data-inspector-component-select>
|
|
929
1025
|
<option value="" disabled selected>Add Component...</option>
|
|
930
|
-
${
|
|
1026
|
+
${i.map(a=>`<option value="${a}">${this.formatLabel(a)}</option>`).join("")}
|
|
931
1027
|
</select>
|
|
932
1028
|
<button class="debug-btn debug-btn-sm primary" data-inspector-add-component-btn>Add</button>
|
|
933
1029
|
</div>
|
|
934
1030
|
</div>
|
|
935
|
-
`}renderSection(e,t,i
|
|
1031
|
+
`}renderSection(e,t,n,i){if(t==="motion")return this.renderMotionSection(e,n,i);if(t==="logic")return this.renderLogicSection(e,n,i);let a=[],s=["kind","renderMode","position_ratio","position_mode","responsive","slot_id","asset_type"];for(let c in n){if(!this.showAdvanced&&s.includes(c))continue;let p=n[c],d=`${i}.${c}`,u=this.rendererRegistry.renderProperty(e,c,p,d);u&&a.push(u)}return a.length===0?"":`
|
|
936
1032
|
<div class="inspector-section ${t==="transform"?"":"collapsed"}" data-section="${t}">
|
|
937
1033
|
<div class="inspector-section-header" data-section-toggle="${t}">
|
|
938
1034
|
<span class="inspector-section-arrow">\u25BC</span>
|
|
@@ -943,7 +1039,7 @@ ${f}
|
|
|
943
1039
|
${a.join("")}
|
|
944
1040
|
</div>
|
|
945
1041
|
</div>
|
|
946
|
-
`}renderLogicSection(e,t,
|
|
1042
|
+
`}renderLogicSection(e,t,n){let i=this.rendererRegistry.renderProperty(e,"logic",t,n);return i?`
|
|
947
1043
|
<div class="inspector-section collapsed" data-section="logic">
|
|
948
1044
|
<div class="inspector-section-header" data-section-toggle="logic">
|
|
949
1045
|
<span class="inspector-section-arrow">\u25BC</span>
|
|
@@ -951,10 +1047,10 @@ ${f}
|
|
|
951
1047
|
<span class="inspector-section-title">${this.formatLabel("logic")}</span>
|
|
952
1048
|
</div>
|
|
953
1049
|
<div class="inspector-section-body" data-section-body="logic">
|
|
954
|
-
${
|
|
1050
|
+
${i}
|
|
955
1051
|
</div>
|
|
956
1052
|
</div>
|
|
957
|
-
`:""}applyMotionDefaults(e,t){if(!t||typeof t!="object")return e!=null?e:{};let
|
|
1053
|
+
`:""}applyMotionDefaults(e,t){if(!t||typeof t!="object")return e!=null?e:{};let n={...e!=null?e:{}};for(let i of Object.keys(t)){let a=t[i],s=n[i];a!=null&&typeof a=="object"&&!Array.isArray(a)?n[i]=this.applyMotionDefaults(s,a):s===void 0&&(n[i]=a)}return n}renderMotionSection(e,t,n){var m;let i=[],a=this.getMotionDefaults(),s=this.applyMotionDefaults(t!=null?t:{},a!=null?a:{}),o=(m=s.intro)!=null?m:{},l=o.enabled===!0&&(typeof o.duration!="number"||o.duration<=0)?'<div class="inspector-warning">\u26A0\uFE0F Duration must be > 0 to play.</div>':"",c=`
|
|
958
1054
|
<div class="inspector-motion-presets">
|
|
959
1055
|
<span class="inspector-subsection-title">Intro Motions</span>
|
|
960
1056
|
<div class="inspector-motion-buttons">
|
|
@@ -971,7 +1067,7 @@ ${f}
|
|
|
971
1067
|
<button class="debug-btn debug-btn-sm ${this.motionSimpleMode?"primary":""}" data-motion-simple-toggle>
|
|
972
1068
|
${this.motionSimpleMode?"Simple":"Advanced"}
|
|
973
1069
|
</button>
|
|
974
|
-
`,d='<button class="debug-btn debug-btn-sm success" data-motion-preview>Preview Intro</button>',u=f=>{let h=f.split(".").filter(Boolean),b=s;for(let S of h)b=b==null?void 0:b[S];let y=h[h.length-1],v=`${
|
|
1070
|
+
`,d='<button class="debug-btn debug-btn-sm success" data-motion-preview>Preview Intro</button>',u=f=>{let h=f.split(".").filter(Boolean),b=s;for(let S of h)b=b==null?void 0:b[S];let y=h[h.length-1],v=`${n}.${f}`;return this.rendererRegistry.renderProperty(e,y,b,v)};if(this.motionSimpleMode){let f=u("enabled");f&&i.push(f);let h=[],b=u("intro.enabled"),y=u("intro.type"),v=u("intro.duration"),S=u("intro.easing");b&&h.push(b),y&&h.push(y),v&&h.push(v),S&&h.push(S),h.length&&i.push(`
|
|
975
1071
|
<div class="inspector-subsection">
|
|
976
1072
|
<div class="inspector-subsection-title">Intro</div>
|
|
977
1073
|
<div class="inspector-subsection-content">
|
|
@@ -980,18 +1076,18 @@ ${f}
|
|
|
980
1076
|
${h.join("")}
|
|
981
1077
|
</div>
|
|
982
1078
|
</div>
|
|
983
|
-
`);let
|
|
1079
|
+
`);let C=[u("pulse.enabled"),u("pulse.speed"),u("pulse.intensity")].filter(Boolean),k=[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),w=[u("continuousRotate.enabled"),u("continuousRotate.speed"),u("continuousRotate.direction")].filter(Boolean),x=[u("orbit.enabled"),u("orbit.radius"),u("orbit.speed"),u("orbit.direction"),u("orbit.pivotOffsetX"),u("orbit.pivotOffsetY")].filter(Boolean);if(C.length||k.length||z.length||w.length||x.length){let A=(I,L)=>L.length?`
|
|
984
1080
|
<div class="inspector-motion-continuous-group">
|
|
985
|
-
<div class="inspector-subsection-title">${
|
|
1081
|
+
<div class="inspector-subsection-title">${I}</div>
|
|
986
1082
|
<div class="inspector-subsection-content">${L.join("")}</div>
|
|
987
|
-
</div>`:"",
|
|
1083
|
+
</div>`:"",E=[A("Pulse",C),A("Swing",k),A("Move forever",z),A("Rotate (pivoting itself)",w),A("Rotate around",x)].filter(Boolean).join("");i.push(`
|
|
988
1084
|
<div class="inspector-subsection inspector-subsection-continuous">
|
|
989
1085
|
<div class="inspector-subsection-title">Continuous</div>
|
|
990
1086
|
<div class="inspector-subsection-content inspector-motion-continuous-groups">
|
|
991
|
-
${
|
|
1087
|
+
${E}
|
|
992
1088
|
</div>
|
|
993
1089
|
</div>
|
|
994
|
-
`)}}else for(let f in s){let h=s[f],b=`${
|
|
1090
|
+
`)}}else for(let f in s){let h=s[f],b=`${n}.${f}`,y=this.rendererRegistry.renderProperty(e,f,h,b);y&&i.push(y)}return i.length===0?"":`
|
|
995
1091
|
<div class="inspector-section ${this.expandMotionOnNextRender?"":"collapsed"}" data-section="motion">
|
|
996
1092
|
<div class="inspector-section-header" data-section-toggle="motion">
|
|
997
1093
|
<span class="inspector-section-arrow">\u25BC</span>
|
|
@@ -1001,22 +1097,22 @@ ${f}
|
|
|
1001
1097
|
</div>
|
|
1002
1098
|
<div class="inspector-section-body" data-section-body="motion">
|
|
1003
1099
|
${c}
|
|
1004
|
-
${
|
|
1100
|
+
${i.join("")}
|
|
1005
1101
|
</div>
|
|
1006
1102
|
</div>
|
|
1007
|
-
`}attachEventListeners(){var S,x,w,P;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=Ko((E,_,R)=>{var C,A;this.updateManager.updateProperty(E,_,R),(A=(C=this.options)==null?void 0:C.onPropertyChange)==null||A.call(C,E,_,R)},300),i=E=>E?/(^|\.)logic(\.\d+)?\.id$/.test(E):!1;e.forEach(E=>{let _=C=>{var I,M;let A=C.target,k=A.dataset.propertyPath,L=A.dataset.objectId;if(k&&L){let z=A.value;if(A.type==="checkbox")z=A.checked;else if(A.type==="number"){if(z=parseFloat(A.value),isNaN(z))return}else if(A.dataset.json==="true")try{z=JSON.parse(A.value)}catch{return}A.type==="text"||A.type==="range"||A.tagName==="TEXTAREA"?t(L,k,z):(this.updateManager.updateProperty(L,k,z),(M=(I=this.options)==null?void 0:I.onPropertyChange)==null||M.call(I,L,k,z))}},R=E.dataset.propertyPath;i(R)?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",R),E.addEventListener("change",async C=>{var O;let A=C.target,k=A.dataset.propertyPath,L=A.dataset.objectId,I=A.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",I),!k||!L)return;await this.updateManager.updateProperty(L,k,I),console.log("[Inspector v1.0.0] Logic ID updated");let M=window,z=(O=M==null?void 0:M.__HANDLER_LOGIC_META)==null?void 0:O[I],T=this.getDefaultPropsForLogic(I,z);console.log("[Inspector v1.0.0] New logic default props:",T);let j=k.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)})):(E.addEventListener("change",_),(E.tagName==="INPUT"||E.tagName==="TEXTAREA")&&E.addEventListener("input",_))}),this.contentContainer.querySelectorAll("[data-action]").forEach(E=>{E.addEventListener("click",_=>{let R=_.target,C=R.dataset.action,A=R.dataset.path,k=R.dataset.object;C&&A&&k&&this.quickActions.handleAction(C,k,A)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(E=>{E.addEventListener("click",_=>{var A,k;let R=_.target,C=R.dataset.sectionToggle||((A=R.closest("[data-section-toggle]"))==null?void 0:A.getAttribute("data-section-toggle"));if(C){let L=(k=this.contentContainer)==null?void 0:k.querySelector(`[data-section="${C}"]`);L==null||L.classList.toggle("collapsed")}})}),this.contentContainer.querySelectorAll("[data-motion-preset]").forEach(E=>{E.addEventListener("click",async _=>{let C=_.currentTarget.dataset.motionPreset;!C||!this.selectedObjectId||await this.applyMotionPreset(this.selectedObjectId,C)})}),this.contentContainer.querySelectorAll("[data-motion-preview]").forEach(E=>{E.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(E=>{E.addEventListener("click",async _=>{let R=_.target,C=R.dataset.objectId,A=R.dataset.propertyPath;if(!C||!A)return;let k=window.getEditableObjectConfig,L=k==null?void 0:k(C);if(!L)return;let I=this.updateManager.getNestedProperty(L,A),M=Array.isArray(I)?[...I]:[];M.push({x:0,y:0}),await this.updateManager.updateProperty(C,A,M),this.loadObject(C)})}),this.contentContainer.querySelectorAll("[data-spawnpoints-remove]").forEach(E=>{E.addEventListener("click",async _=>{let R=_.target,C=R.dataset.objectId,A=R.dataset.propertyPath,k=Number(R.dataset.index||"-1");if(!C||!A||k<0)return;let L=window.getEditableObjectConfig,I=L==null?void 0:L(C);if(!I)return;let M=this.updateManager.getNestedProperty(I,A);if(!Array.isArray(M))return;let z=M.filter((T,j)=>j!==k);await this.updateManager.updateProperty(C,A,z),this.loadObject(C)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-add]").forEach(E=>{E.addEventListener("click",async _=>{let R=_.target,C=R.dataset.objectId,A=R.dataset.propertyPath;if(!C||!A)return;let k=window.getEditableObjectConfig,L=k==null?void 0:k(C);if(!L)return;let I=this.updateManager.getNestedProperty(L,A),M=Array.isArray(I)?[...I]:[];M.push({templateId:"",weight:1}),await this.updateManager.updateProperty(C,A,M),this.loadObject(C)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-remove]").forEach(E=>{E.addEventListener("click",async _=>{var T;let R=_.target,C=R.dataset.objectId,A=R.dataset.propertyPath,k=Number((T=R.dataset.index)!=null?T:-1);if(!C||!A||k<0)return;let L=window.getEditableObjectConfig,I=L==null?void 0:L(C);if(!I)return;let M=this.updateManager.getNestedProperty(I,A);if(!Array.isArray(M))return;let z=M.filter((j,O)=>O!==k);await this.updateManager.updateProperty(C,A,z),this.loadObject(C)})}),this.contentContainer.querySelectorAll("[data-logic-add]").forEach(E=>{E.addEventListener("click",async _=>{var F;let R=_.target,C=R.dataset.objectId,A=R.dataset.propertyPath;if(!C||!A)return;let k=window.getEditableObjectConfig,L=k==null?void 0:k(C);if(!L)return;let I=this.updateManager.getNestedProperty(L,A),M;Array.isArray(I)?M=[...I]:I!=null?typeof I=="string"?M=[{id:I,props:{}}]:typeof I=="object"?M=[I]:M=[]:M=[];let z=this.getDefaultLogicId(),T=window,j=(F=T==null?void 0:T.__HANDLER_LOGIC_META)==null?void 0:F[z],O=this.getDefaultPropsForLogic(z,j);M.push({id:z,props:O}),console.log("[InspectorPanel] Adding logic to array:",{objectId:C,path:A,current:I,next:M}),await this.updateManager.updateProperty(C,A,M),this.loadObject(C)})}),this.contentContainer.querySelectorAll("[data-logic-remove]").forEach(E=>{E.addEventListener("click",async _=>{var T;let R=_.target,C=R.dataset.objectId,A=R.dataset.propertyPath,k=Number((T=R.dataset.index)!=null?T:-1);if(!C||!A||k<0)return;let L=window.getEditableObjectConfig,I=L==null?void 0:L(C);if(!I)return;let M=this.updateManager.getNestedProperty(I,A);if(!Array.isArray(M))return;let z=M.filter((j,O)=>O!==k);await this.updateManager.updateProperty(C,A,z),this.loadObject(C)})}),this.contentContainer.querySelectorAll("[data-logic-convert]").forEach(E=>{E.addEventListener("click",async _=>{var U,X;let R=_.target,C=R.dataset.objectId,A=R.dataset.propertyPath,k=Number((U=R.dataset.index)!=null?U:-1);if(!C||!A||k<0)return;let L=window.getEditableObjectConfig,I=L==null?void 0:L(C);if(!I)return;let M=this.updateManager.getNestedProperty(I,A);if(!Array.isArray(M))return;let z=M[k];if(typeof z!="string")return;let T=window,j=(X=T==null?void 0:T.__HANDLER_LOGIC_META)==null?void 0:X[z],O=this.getDefaultPropsForLogic(z,j),F=[...M];F[k]={id:z,props:O},await this.updateManager.updateProperty(C,A,F),this.loadObject(C)})});let h=(S=this.root)==null?void 0:S.querySelector("[data-inspector-advanced]");h==null||h.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let b=(x=this.root)==null?void 0:x.querySelector("[data-convert-toggle]");b==null||b.addEventListener("click",()=>{var _;let E=(_=this.root)==null?void 0:_.querySelector("[data-convert-menu]");E==null||E.classList.toggle("hidden")});let y=(w=this.contentContainer)==null?void 0:w.querySelector("[data-inspector-add-component-btn]"),v=(P=this.contentContainer)==null?void 0:P.querySelector("[data-inspector-component-select]");y==null||y.addEventListener("click",async()=>{let E=v.value;E&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,E)})}getMotionDefaults(){var i,n,a,s;let e=window.__editableConfig,t=e==null?void 0:e.schemas;return t instanceof Map?(n=(i=t.get("motion"))==null?void 0:i.defaults)!=null?n:{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 i=window.getEditableObjectConfig,n=i==null?void 0:i(e);if(!n)return;let a=this.getMotionDefaults(),s={...(l=n.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,i=t==null?void 0:t(e);if(!i)return;let n=this.getMotionDefaults(),a={...(o=i.motion)!=null?o:n},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 i=window.getEditableObjectConfig,n=i==null?void 0:i(e);if(!n){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};n[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};n[t]={...l},await this.updateManager.updateProperty(e,t,n[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,i){var a,s;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((s=(a=i.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 n=Object.keys(t);return n.length===0||n.length===1&&n[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
|
|
1103
|
+
`}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 h=(S=this.root)==null?void 0:S.querySelector("[data-inspector-advanced]");h==null||h.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=`
|
|
1008
1104
|
<div class="inspector-empty">
|
|
1009
1105
|
<span class="inspector-empty-icon">\u26A0\uFE0F</span>
|
|
1010
1106
|
<span class="inspector-empty-text">${e}</span>
|
|
1011
1107
|
</div>
|
|
1012
|
-
`)}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}getDefaultLogicId(){try{let e=window,t=Array.isArray(e==null?void 0:e.__HANDLER_LOGIC_OPTIONS)?e.__HANDLER_LOGIC_OPTIONS:[],
|
|
1108
|
+
`)}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}getDefaultLogicId(){try{let e=window,t=Array.isArray(e==null?void 0:e.__HANDLER_LOGIC_OPTIONS)?e.__HANDLER_LOGIC_OPTIONS:[],n=["SwerveMove","DragSnap","JoystickMove","DragToWin"],i=[...t,...n].map(a=>String(a)).filter(a=>a.trim().length>0);return i.length?i[0]:"SwerveMove"}catch{return"SwerveMove"}}getDefaultPropsForLogic(e,t){return{DragToWin:{targetDrags:3},DragSnap:{targetId:"",snapRadius:100,snapDuration:.5,returnOnMiss:!0,returnDuration:.3,ease:"power2.out"},SwerveMove:{speed:5,sensitivity:1,directionMode:"dominantAxis",axis:"both",bounds:{left:-400,right:400,top:-300,bottom:300}},JoystickMove:{speed:200,zone:"bottom-center",offsetX:0,offsetY:-50,inputId:""},Tap:{maxTapDuration:300,maxTapDistance:10,tapCount:1,tapTimeout:500},Swipe:{inputId:"",direction:"any",minDistance:50,maxDuration:1e3},Hold:{holdDuration:500,visualFeedback:!0,feedbackColor:16777215},Collectable:{targetId:"",collectRadius:50,particleEffect:"",autoDestroy:!0,collectSound:""},Spawner:{templateId:"",spawnTemplates:[],spawnPattern:"continuous",spawnRate:1e3,poolSize:20,positionSource:"spawner",targetId:"",targetOffset:{x:0,y:0},customPosition:{x:0,y:0},randomBounds:{x:[-100,100],y:[-100,100]},spawnPoints:[],spawnPointMode:"cycle",movementMode:"velocity",velocity:{x:0,y:-300},lifetime:2e3},Damageable:{hitTemplateId:"",hitRadius:50,hp:1,invulnMs:150,flashAlpha:.3,flashDurationMs:100,hitScale:1,hitScaleDurationMs:120,knockback:{x:0,y:0},hpLabelId:"",autoDestroy:!0,hitEffect:"",destroyEffect:"",particleScale:1,particleColor:"",destroySound:"",hitEvent:"",destroyEvent:"",hitPopupText:"",hitPopupColor:"#ffffff",hitPopupFontSize:20,hitPopupDurationMs:600,hitPopupOffset:{x:0,y:-20},hitPopupRise:30,hitPopupTemplateId:""}}[e]||{}}getSectionIcon(e){return{identity:"\u{1F194}",transform:"\u{1F4D0}",render:"\u{1F3A8}",ui:"\u{1F4AC}",logic:"\u{1F3AE}",gameplay:"\u{1F3AE}",interaction:"\u{1F446}",audio:"\u{1F50A}",effects:"\u2728",motion:"\u{1F3AC}"}[e]||"\u{1F4E6}"}clear(){this.selectedObjectId=null,this.contentContainer&&(this.contentContainer.innerHTML=`
|
|
1013
1109
|
<div class="inspector-empty">
|
|
1014
1110
|
<span class="inspector-empty-icon">\u{1F3AF}</span>
|
|
1015
1111
|
<span class="inspector-empty-text">Select an object to inspect</span>
|
|
1016
1112
|
</div>
|
|
1017
|
-
`)}};var
|
|
1018
|
-
`)||"None",t=r.brandDna?`Colors: ${JSON.stringify(r.brandDna.colors)}, Style: ${r.brandDna.style||"not specified"}`:"Not provided",
|
|
1019
|
-
`),
|
|
1113
|
+
`)}};var ts=Xe(require("jszip"),1);function Yi(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 Fn(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 Yi(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 Ie(r){var e,t;try{let n=await Yi(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 Ki(r){return Yi(r).then(e=>e).catch(()=>null)}function Xi(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 nt(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],f=!1;for(let h of l)if(Math.sqrt(Math.pow(u-h.r,2)+Math.pow(g-h.g,2)+Math.pow(m-h.b,2))<e){f=!0;break}f&&(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 ve(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(ve(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 Ji(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(ve(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(ve(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(ve(r.brand_dna)&&ve(r.brand_dna.colors))return r.brand_dna;if(ve(r.colors)){let e={colors:r.colors};return typeof r.style=="string"&&(e.style=r.style),ve(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 Zi(r,e={}){var s,o,l;let t=r.filter(ve),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(...Ji(c.layers,"visual element")),"assets"in c&&a.push(...Ji(c.assets,"visual element")),ve(c.endgame)&&"assets"in c.endgame&&a.push(...Ji(c.endgame.assets,"endgame"));return{version:"1.0",brand_name:n,brand_dna:i,assets:el(a)}}var Vr=require("@google/genai");async function Bn(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}),f="",h=(s=(a=(i=m.candidates)==null?void 0:i[0])==null?void 0:a.content)==null?void 0:s.parts;if(h)for(let b of h)b.text&&(f+=b.text);if(!f.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${f.length}`),f}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 it(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(`
|
|
1114
|
+
`)||"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(`
|
|
1115
|
+
`),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=`
|
|
1020
1116
|
BRAND CONTENT:
|
|
1021
1117
|
${s.join(`
|
|
1022
1118
|
`)}
|
|
@@ -1027,14 +1123,14 @@ GAME CONTEXT:
|
|
|
1027
1123
|
${r.gamePrompt||"Simple game"}
|
|
1028
1124
|
|
|
1029
1125
|
GAME OBJECTS (need assets):
|
|
1030
|
-
${
|
|
1126
|
+
${n}
|
|
1031
1127
|
|
|
1032
1128
|
BRAND ASSETS PROVIDED:
|
|
1033
1129
|
${e}
|
|
1034
1130
|
|
|
1035
1131
|
BRAND DNA:
|
|
1036
1132
|
${t}
|
|
1037
|
-
${
|
|
1133
|
+
${i}
|
|
1038
1134
|
VISUAL REFERENCE: [See attached flat design image]
|
|
1039
1135
|
|
|
1040
1136
|
TASK:
|
|
@@ -1078,7 +1174,7 @@ OUTPUT ONLY VALID JSON (no markdown, no explanation):
|
|
|
1078
1174
|
}
|
|
1079
1175
|
]
|
|
1080
1176
|
}
|
|
1081
|
-
`.trim()}function
|
|
1177
|
+
`.trim()}function Kr(r){var i,a;let e=(i=r.brandDna)!=null&&i.colors?`Primary: ${r.brandDna.colors.primary}, Secondary: ${r.brandDna.colors.secondary||"N/A"}, Accent: ${r.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",t=((a=r.brandDna)==null?void 0:a.style)||"modern gaming style",n=r.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
|
|
1082
1178
|
TASK: ${r.prompt}
|
|
1083
1179
|
|
|
1084
1180
|
BRAND STYLE:
|
|
@@ -1087,7 +1183,7 @@ BRAND STYLE:
|
|
|
1087
1183
|
|
|
1088
1184
|
CHANGE_STRENGTH: 8/10
|
|
1089
1185
|
REFERENCE: ${r.hasReference?"provided (use as style guide for colors and aesthetics)":"none"}
|
|
1090
|
-
${
|
|
1186
|
+
${n}
|
|
1091
1187
|
|
|
1092
1188
|
OUTPUT CONSTRAINTS (MUST FOLLOW):
|
|
1093
1189
|
- Do NOT add extra text unless specifically requested
|
|
@@ -1099,7 +1195,7 @@ OUTPUT CONSTRAINTS (MUST FOLLOW):
|
|
|
1099
1195
|
|
|
1100
1196
|
OUTPUT:
|
|
1101
1197
|
Generate the requested asset matching the brand style.${r.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
|
|
1102
|
-
`.trim()}function
|
|
1198
|
+
`.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 Bn(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 Qi(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 Ie(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 it(r.apiKey,a,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await nt(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 Ie(a);s&&(i.dataUrl=s.dataUrl)}}}var Un=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`
|
|
1103
1199
|
<div class="scene-panel brand-vision-panel panel-accent-violet" data-panel="brand-vision">
|
|
1104
1200
|
<div class="scene-panel-header" data-panel-handle>
|
|
1105
1201
|
<div class="panel-title">
|
|
@@ -1215,15 +1311,15 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1215
1311
|
</div>
|
|
1216
1312
|
<div class="panel-resize-handle" data-panel-resize></div>
|
|
1217
1313
|
</div>
|
|
1218
|
-
`}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,i,
|
|
1219
|
-
\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,
|
|
1220
|
-
`:l.brand_dna||l.colors?
|
|
1221
|
-
`:
|
|
1222
|
-
`}catch{
|
|
1223
|
-
`}try{this.normalizedManifest=
|
|
1224
|
-
\u{1F4E6} Normalized manifest: ${s} assets`,
|
|
1225
|
-
\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,
|
|
1226
|
-
\u274C Failed to normalize manifest`}t.value="",this.setStatus("manifest",
|
|
1314
|
+
`}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 f="/dashboard";window.location.pathname!==f&&(window.location.href=f)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(f=>{f.addEventListener("click",()=>{let h=f.dataset.visionTab;this.switchTab(h)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",f=>{let h=f.target.value;this.switchUploadMethod(h)}),(i=this.root.querySelector("[data-vision-upload-manifest]"))==null||i.addEventListener("click",()=>{var f,h;(h=(f=this.root)==null?void 0:f.querySelector("[data-vision-manifest-input]"))==null||h.click()}),(a=this.root.querySelector("[data-vision-upload-zip]"))==null||a.addEventListener("click",()=>{var f,h;(h=(f=this.root)==null?void 0:f.querySelector("[data-vision-zip-input]"))==null||h.click()}),(s=this.root.querySelector("[data-vision-zip-input]"))==null||s.addEventListener("change",f=>{this.handleZipUpload(f)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",f=>{this.handleManifestUpload(f)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var f,h;(h=(f=this.root)==null?void 0:f.querySelector("[data-vision-assets-input]"))==null||h.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",f=>{this.handleAssetsUpload(f)}),(p=this.root.querySelector("[data-vision-upload-flat]"))==null||p.addEventListener("click",()=>{var f,h;(h=(f=this.root)==null?void 0:f.querySelector("[data-vision-flat-input]"))==null||h.click()}),(d=this.root.querySelector("[data-vision-flat-input]"))==null||d.addEventListener("change",f=>{this.handleFlatDesignUpload(f)}),(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",f=>{let h=f.target;if(!h)return;let b=h.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;y&&(h.closest("[data-mapping-apply-one]")&&this.applyOne(y),h.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(y),h.closest("[data-mapping-edit-one]")&&this.openEditorForOne(y),h.closest("[data-mapping-generate-one]")&&this.generateOne(y),h.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),e==null||e.addEventListener("change",f=>{let h=f.target;if(!h||!this.mappingResult)return;let b=h.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(S=>S.game_object===y);v&&(h.matches("[data-mapping-action]")&&(v.action=String(h.value||"KEEP"),v.status="Edited",this.renderMappings()),h.matches("[data-mapping-brand-asset]")&&(v.brand_asset=String(h.value||""),v.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",f=>{let h=f.target;if(!h||!this.mappingResult||!h.matches("[data-mapping-prompt]"))return;let b=h.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(S=>S.game_object===y);v&&(v.generation_prompt=String(h.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(h){console.warn(`FileReader failed for ${d}, using fallback:`,h),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 f=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}:`,f),f.success){console.log(`\u2705 Saved PNG to library: ${d} (${g}) at ${f.path}`);let h=new File([p],d,{type:"image/png"});a.set(d,h)}else console.warn(`\u274C Failed to save ${d}:`,f.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=Zi(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
|
|
1315
|
+
\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}
|
|
1316
|
+
`:l.brand_dna||l.colors?i+=`\u2705 Brand: ${s.name}
|
|
1317
|
+
`:i+=`\u2705 Loaded: ${s.name}
|
|
1318
|
+
`}catch{i+=`\u274C Error in ${s.name}
|
|
1319
|
+
`}try{this.normalizedManifest=Zi(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+=`
|
|
1320
|
+
\u{1F4E6} Normalized manifest: ${s} assets`,i+=`
|
|
1321
|
+
\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+=`
|
|
1322
|
+
\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 Ie(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 Qi(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?`
|
|
1227
1323
|
<div class="vision-raw-block">
|
|
1228
1324
|
<div class="inspector-text-sm" style="white-space: pre-wrap;">
|
|
1229
1325
|
\u26A0\uFE0F AI response was not valid JSON (${this.analysisParseError||"unknown error"}).
|
|
@@ -1233,7 +1329,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1233
1329
|
</div>
|
|
1234
1330
|
`:"";e.innerHTML=`
|
|
1235
1331
|
${s}
|
|
1236
|
-
${this.mappingResult.mappings.map(l=>{var b;let c=
|
|
1332
|
+
${this.mappingResult.mappings.map(l=>{var b;let c=n[l.game_object]||"",p=l.brand_asset||"",d=(b=t==null?void 0:t.assets)==null?void 0:b.find(y=>y.id===p),u=(d==null?void 0:d.dataUrl)||"",g=l.output_dataUrl||"",m=l.action==="GENERATE"?g:l.action==="APPLY"?u:"",f=!!m,h=`
|
|
1237
1333
|
<select class="inspector-input" data-mapping-brand-asset style="flex:1; padding:6px 8px;">
|
|
1238
1334
|
<option value="">Select brand asset\u2026</option>
|
|
1239
1335
|
${a.replace(`value="${p}"`,`value="${p}" selected`)}
|
|
@@ -1285,8 +1381,8 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1285
1381
|
</div>
|
|
1286
1382
|
</div>
|
|
1287
1383
|
`}).join("")}
|
|
1288
|
-
`}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(
|
|
1289
|
-
`)}var
|
|
1384
|
+
`}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 Qi(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(()=>(X(),He));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(`
|
|
1385
|
+
`)}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"],Gn=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`
|
|
1290
1386
|
<div class="scene-panel customize-panel panel-accent-blue" data-panel="customize-settings">
|
|
1291
1387
|
<div class="scene-panel-header" data-panel-handle>
|
|
1292
1388
|
<div class="panel-title">
|
|
@@ -1344,17 +1440,17 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1344
1440
|
</div>
|
|
1345
1441
|
<div class="panel-resize-handle" data-panel-resize></div>
|
|
1346
1442
|
</div>
|
|
1347
|
-
`}initialize(e,t){var
|
|
1443
|
+
`}initialize(e,t){var i,a,s,o,l,c;this.options=t,this.root=e.querySelector('[data-panel="customize-settings"]'),this.assetsContainer=(i=this.root)==null?void 0:i.querySelector("[data-customize-assets]"),this.colorsContainer=(a=this.root)==null?void 0:a.querySelector("[data-customize-colors]"),this.fontsContainer=(s=this.root)==null?void 0:s.querySelector("[data-customize-fonts]"),this.textsContainer=(o=this.root)==null?void 0:o.querySelector("[data-customize-texts]"),this.audioContainer=(l=this.root)==null?void 0:l.querySelector("[data-customize-audio]");let n=(c=this.root)==null?void 0:c.querySelector("[data-customize-apply]");n==null||n.addEventListener("click",()=>this.handleApply()),this.setupRenderModeHandlers(),this.setupResizeHandle(),this.refresh()}setupRenderModeHandlers(){var n,i;let e=(n=this.root)==null?void 0:n.querySelector('[data-render-mode="endgame-png"]'),t=(i=this.root)==null?void 0:i.querySelector('[data-render-mode="splash-png"]');e==null||e.addEventListener("change",()=>{this.applyEndgamePngMode(e.checked)}),t==null||t.addEventListener("change",()=>{this.applySplashPngMode(t.checked)})}applyEndgamePngMode(e){let t=window.getEditableObjectConfig,n=window.applyEditableObjectConfig;if(typeof t!="function"||typeof n!="function")return;let i=["ui_endgame_title_1","ui_endgame_subtitle_1","ui_endgame_logo_1","ui_endgame_cta_1"];for(let a of i){let s=t(a);s&&(s.ui||(s.ui={}),s.ui.renderMode=e?"png":"text",e&&(s.render||(s.render={}),s.render.asset||(s.render.asset={type:"image",path:""}),s.render.asset.type="image"),n(a,s))}console.log("[CustomizePanel] EndGame PNG mode:",e?"enabled":"disabled")}applySplashPngMode(e){let t=window.applyEditableEngineConfig;typeof t=="function"&&(t({splash:{type:e?"image":"text",image_path:e?"library/splash/splash.png":""}}),console.log("[CustomizePanel] Splash PNG mode:",e?"enabled":"disabled"))}openAiEditor(e,t,n,i){this.openAiModal(e,n,i),t&&this.aiPromptInput&&(this.aiPromptInput.value=t,this.setAiStatus("Prompt loaded."))}refresh(){var t,n,i,a,s,o,l,c;let e=this.getEngineSnapshot();if(console.log("[CustomizePanel] Refreshing with snapshot:",!!e),!e){this.scheduleRetry();return}console.log("[CustomizePanel] Snapshot assets count:",Object.keys(e.assets||{}).length),this.renderAssets(e.assets),this.renderColors((n=(t=e.runtime)==null?void 0:t.theme)!=null?n:{}),this.renderFonts((a=(i=e.runtime)==null?void 0:i.fonts)!=null?a:{}),this.renderTexts((o=(s=e.runtime)==null?void 0:s.ui)!=null?o:{}),this.renderAudio((c=(l=e.runtime)==null?void 0:l.audio)!=null?c:{})}getEngineSnapshot(){let e=window.getEditableEngineConfig;return typeof e!="function"?null:e()}renderAssets(e){if(!this.assetsContainer)return;this.assetsContainer.innerHTML="";let t=Object.entries(e!=null?e:{});if(!t.length){this.assetsContainer.innerHTML='<div class="customize-empty">No assets found.</div>',this.scheduleRetry();return}this.clearRetry(),t.forEach(([n,i])=>{var u;let a=document.createElement("div");a.className="customize-row";let s=document.createElement("span");s.className="customize-key",s.textContent=n;let o=document.createElement("input");o.type="text",o.value=i!=null?i:"",o.className="customize-input",o.dataset.assetKey=n,o.addEventListener("input",()=>{this.handleAssetValueChange(n,o)});let l=document.createElement("div");l.className="customize-actions";let c=document.createElement("button");c.type="button",c.className="customize-icon-btn",c.title="Preview asset",c.innerHTML=`
|
|
1348
1444
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
|
1349
1445
|
<path d="M12 5c5.2 0 9.2 3.7 10 6.8-.8 3.1-4.8 6.8-10 6.8S2.8 14.9 2 11.8C2.8 8.7 6.8 5 12 5z" />
|
|
1350
1446
|
<circle cx="12" cy="12" r="3.2" />
|
|
1351
1447
|
</svg>
|
|
1352
|
-
`,c.addEventListener("click",()=>{this.previewAsset(
|
|
1448
|
+
`,c.addEventListener("click",()=>{this.previewAsset(n,o.value,o.dataset.assetType,d)});let p=document.createElement("button");p.type="button",p.className="customize-icon-btn",p.title="Upload asset",p.innerHTML=`
|
|
1353
1449
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
|
1354
1450
|
<path d="M12 3l4 4h-3v6h-2V7H8l4-4z" />
|
|
1355
1451
|
<path d="M5 14v4h14v-4h2v6H3v-6h2z" />
|
|
1356
1452
|
</svg>
|
|
1357
|
-
`;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,
|
|
1453
|
+
`;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 Fn(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,f,h;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=`
|
|
1358
1454
|
<div class="ai-modal-card">
|
|
1359
1455
|
<div class="ai-modal-header">
|
|
1360
1456
|
<div>
|
|
@@ -1425,7 +1521,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1425
1521
|
</div>
|
|
1426
1522
|
</div>
|
|
1427
1523
|
</div>
|
|
1428
|
-
`;let a=n.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),n.addEventListener("click",b=>{b.target===n&&this.closeAiModal()}),this.aiModal=n,this.aiKeyInput=n.querySelector("[data-ai-key]"),this.aiModelSelect=n.querySelector("[data-ai-model]"),this.aiPromptInput=n.querySelector("[data-ai-prompt]"),this.aiStrengthInput=n.querySelector("[data-ai-strength]"),this.aiStrengthValue=n.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=n.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=n.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=n.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=n.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=n.querySelector("[data-ai-ref-input]"),this.aiReferenceName=n.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=n.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=n.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=n.querySelector("[data-ai-generate]"),this.aiApplyBtn=n.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=n.querySelector("[data-ai-save-library]"),this.aiCropBtn=n.querySelector("[data-ai-crop]"),this.aiDownloadBtn=n.querySelector("[data-ai-download]"),this.aiPreviewImg=n.querySelector("[data-ai-preview]"),this.aiStatusEl=n.querySelector("[data-ai-status]"),this.aiLoadingEl=n.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=n.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=n.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let s=n.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()}),(f=this.aiCropBtn)==null||f.addEventListener("click",()=>{this.handleAiCrop()}),(h=this.aiDownloadBtn)==null||h.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(n),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,f,h,b,y,v,S,x,w,P,E,_,R,C,A,k;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",i=(b=(h=(f=this.aiPromptInput)==null?void 0:f.value)==null?void 0:h.trim())!=null?b:"",n=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,a=n,s=n,o=Number((x=(S=this.aiStrengthInput)==null?void 0:S.value)!=null?x:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!i){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((w=l==null?void 0:l.value)==null?void 0:w.trim())||((P=this.aiBaseValue)==null?void 0:P.trim())||"";if(!c&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let L=null,I=(E=this.getSelectedAssetKey())!=null?E:"unknown",M=(_=this.aiUseOutputToggle)!=null&&_.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((R=this.aiUseOutputToggle)!=null&&R.checked&&this.aiOutputDataUrl){let X=Yn(this.aiOutputDataUrl,"ai-output.png");if(X){let re=await Ie(X);re&&(L={input:{base64:re.base64,mimeType:re.mimeType},dataUrl:re.dataUrl,width:re.width,height:re.height})}}if(L||(L=await this.getImageDataFromAsset(c)),!L){this.setAiStatus("Unable to load the base image.");return}let z=[L.input],T=!1;if(this.aiReferenceFile){let X=await Ie(this.aiReferenceFile);X?(z.push({base64:X.base64,mimeType:X.mimeType}),T=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let j=ts(i,{includeReference:T,includeMagenta:a,changeLevel:o}),O=(A=(C=this.aiReferenceFile)==null?void 0:C.name)!=null?A:"none";console.info("[AI] Final prompt:",j),console.info("[AI] Image sources:",{assetKey:I,base:M,reference:O});let F=Ur(L.width,L.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let U=await tt(e,j,z,{aspectRatio:F,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",U==null?void 0:U.length),this.aiRawOutputDataUrl=U,await this.refreshAiOutputFromRaw()}catch(L){console.error("[CustomizePanel] AI Generate Error:",L),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((k=this.aiStatusEl)==null?void 0:k.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var n,a,s,o;if(!this.aiRawOutputDataUrl)return;let e=(a=(n=this.aiRemoveBgToggle)==null?void 0:n.checked)!=null?a:!1,t=Number((o=(s=this.aiBgToleranceInput)==null?void 0:s.value)!=null?o:"30"),i=this.aiRawOutputDataUrl;if(e){let l=await et(this.aiRawOutputDataUrl,t);l&&(i=l)}this.setAiOutput(i),this.setAiStatus("Ready.")}setAiOutput(e){var i,n;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(i=this.previewModal)==null?void 0:i.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(n=this.activePreviewKey)!=null?n: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,i,n;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=((i=this.aiContext)==null?void 0:i.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),s=((n=this.aiContext)==null?void 0:n.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 i=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,n=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:n,filename:`${i}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${i}.png. Refreshing library...`);let p=window.addAssetToRegistry;typeof p=="function"&&(console.log("[CustomizePanel] Adding to registry category:",n),p(n,`${i}.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||""),f=this.getSelectedAssetInput();if(f&&(f.value=c.path,this.handleAssetValueChange((o=f.dataset.assetKey)!=null?o:"",f)),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,n)}else this.applyObjectPropertyValue(g,m,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let h=window.__highlightLibrarySlot;typeof h=="function"&&g&&(console.log("[CustomizePanel] Highlighting slot in library:",g,n),setTimeout(()=>{h(g,n)},500)),this.setAiStatus(`\u2705 Saved and applied ${i}.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,i=e||this.aiTargetKey||"",n=window.getEditableAssets;if(typeof n=="function"){let o=n();if(o!=null&&o.slots){let l=o.slots.find(c=>t&&c.objectId===t||c.currentAsset===i||c.slotId===i||c.currentAsset&&c.currentAsset.includes(i)||i.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let a=i.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 i=t();if(!(i!=null&&i.slots))return null;let n=i.slots.find(a=>a.currentAsset===e||a.slotId===e);return(n==null?void 0:n.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let i=t();if(!(i!=null&&i.slots))return null;let n=i.slots.find(s=>s.currentAsset===e||s.slotId===e);if(!n)return null;let a=n.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:"",i=await this.getImageDimensions(t);if(!i){this.setAiStatus("Unable to read target dimensions.");return}let n=Yn(this.aiOutputDataUrl,"ai-output.png");if(!n)return;let a=await this.showManualCropModal(n,i,t);if(!a)return;let s=await Wn(a);s&&this.setAiOutput(s)}handleAiDownload(){var i;if(!this.aiOutputDataUrl)return;let e=(i=this.getSelectedAssetKey())!=null?i:"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,i){console.log("[CustomizePanel] Handling asset upload for:",i);let n=t.value,a=e;if(e.type.startsWith("image/")){let p=await this.getImageDimensions(n);if(p){let d=await this.showManualCropModal(e,p,n);if(!d)return;a=d}}let s=await Wn(a);if(!s){console.error("[CustomizePanel] Failed to convert file to data URL");return}let l=`${i.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,c=this.inferCategoryFromAssetKey(i);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(i,t);let m=this.inferObjectIdFromAssetKey(i),f=this.inferPathFromAssetKey(i);if(m&&f){let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(f)||/\\.(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,f,d.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let h=window.__highlightLibrarySlot;typeof h=="function"&&m&&setTimeout(()=>{h(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,i,n){if(!t)return;let a=this.resolveAssetUrls(t);if(a.length===0)return;let s=i||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=n!=null?n: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 i=t.replace(/^\.?\//,""),n=[];return i.startsWith("raw/")?n=[`/${i}`,`/assets/${i}`]:i.startsWith("assets/")?n=[`/${i}`]:n=[`/raw/${i}`,`/assets/raw/${i}`,`/assets/${i}`,`/${i}`],console.log("[CustomizePanel] Resolved to possible paths:",n),n}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,i,n){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
|
|
1524
|
+
`;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()}),(f=this.aiCropBtn)==null||f.addEventListener("click",()=>{this.handleAiCrop()}),(h=this.aiDownloadBtn)==null||h.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,f,h,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=(h=(f=this.aiPromptInput)==null?void 0:f.value)==null?void 0:h.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||""),f=this.getSelectedAssetInput();if(f&&(f.value=c.path,this.handleAssetValueChange((o=f.dataset.assetKey)!=null?o:"",f)),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 h=window.__highlightLibrarySlot;typeof h=="function"&&g&&(console.log("[CustomizePanel] Highlighting slot in library:",g,i),setTimeout(()=>{h(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),f=this.inferPathFromAssetKey(n);if(m&&f){let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(f)||/\\.(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,f,d.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let h=window.__highlightLibrarySlot;typeof h=="function"&&m&&setTimeout(()=>{h(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=`
|
|
1429
1525
|
<div class="asset-preview-card">
|
|
1430
1526
|
<div class="asset-preview-header">
|
|
1431
1527
|
<div class="asset-preview-title">${e}</div>
|
|
@@ -1441,12 +1537,12 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1441
1537
|
<img class="asset-preview-ai-image" alt="AI output preview">
|
|
1442
1538
|
</div>
|
|
1443
1539
|
</div>
|
|
1444
|
-
`;let s=a.querySelector(".asset-preview-body"),o=a.querySelector(".asset-preview-close"),l=a.querySelector(".asset-preview-change"),c=a.querySelector(".asset-preview-ai"),p=a.querySelector("[data-asset-ai-preview]");if(o==null||o.addEventListener("click",()=>this.closePreviewModal()),c==null||c.addEventListener("click",()=>{console.log("[CustomizePanel] AI Edit clicked for:",e),this.openAiModal(e,t)}),l==null||l.addEventListener("click",()=>{console.log("[CustomizePanel] Change clicked for:",e),this.activePreviewFileInput&&this.activePreviewFileInput.click()}),a.addEventListener("click",d=>{d.target===a&&this.closePreviewModal()}),s)if(
|
|
1540
|
+
`;let s=a.querySelector(".asset-preview-body"),o=a.querySelector(".asset-preview-close"),l=a.querySelector(".asset-preview-change"),c=a.querySelector(".asset-preview-ai"),p=a.querySelector("[data-asset-ai-preview]");if(o==null||o.addEventListener("click",()=>this.closePreviewModal()),c==null||c.addEventListener("click",()=>{console.log("[CustomizePanel] AI Edit clicked for:",e),this.openAiModal(e,t)}),l==null||l.addEventListener("click",()=>{console.log("[CustomizePanel] Change clicked for:",e),this.activePreviewFileInput&&this.activePreviewFileInput.click()}),a.addEventListener("click",d=>{d.target===a&&this.closePreviewModal()}),s)if(i==="image"){let d=document.createElement("img");this.loadWithFallback(d,n),s.appendChild(d)}else if(i==="audio"){let d=document.createElement("audio");d.controls=!0,this.loadWithFallback(d,n),s.appendChild(d)}else if(i==="json"){let d=document.createElement("pre");this.fetchWithFallback(n).then(u=>{d.textContent=u!=null?u:"Unable to load JSON."}),s.appendChild(d)}else{let d=document.createElement("a");d.href=n[0],d.target="_blank",d.rel="noreferrer",d.textContent="Open asset",s.appendChild(d)}document.body.appendChild(a),this.previewModal=a,this.updateAiModalPreview(p,e)}loadWithFallback(e,t){if(t.length===0)return;let n=0,i=()=>{n>=t.length||(e.src=t[n],n+=1)};e.addEventListener("error",i),i()}async fetchWithFallback(e){for(let t of e)try{let n=await fetch(t);if(!n.ok)continue;return await n.text()}catch{}return null}applyObjectPropertyValue(e,t,n){let i=window.getEditableObjectConfig,a=window.applyEditableObjectConfig;if(typeof i!="function"||typeof a!="function")return;let s=i(e);if(!s)return;let o=JSON.parse(JSON.stringify(s)),l=t.split("."),c=o;for(let p=0;p<l.length-1;p++){let d=l[p];c[d]=c[d]||{},c=c[d]}c[l[l.length-1]]=n,a(e,o)}applyTextColorToObject(e,t){let i={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"}}[e];i&&this.applyObjectPropertyValue(i.objectId,i.property,t)}closePreviewModal(e){this.previewModal&&(this.previewModal.remove(),this.previewModal=null),e||(this.activePreviewKey=null,this.activePreviewValue=null,this.activePreviewFileInput=null)}updatePreviewIfOpen(e,t,n){var a;if(!this.previewModal||this.activePreviewKey!==e)return;let i=t!=null?t:"";this.activePreviewValue!==i&&this.previewAsset(e,i,n,(a=this.activePreviewFileInput)!=null?a:void 0)}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refresh()},350))}clearRetry(){this.retryTimer&&(window.clearTimeout(this.retryTimer),this.retryTimer=null)}setupResizeHandle(){if(!this.root)return;let e=this.root.querySelector("[data-panel-resize]");if(!e)return;let t=window.localStorage.getItem("customizePanelWidth"),n=t?Number(t):NaN;Number.isFinite(n)&&n>0&&(this.root.style.width=`${n}px`);let i=a=>{var u,g;a.preventDefault();let s=a.clientX,o=(g=(u=this.root)==null?void 0:u.getBoundingClientRect().width)!=null?g:0,l=260,c=620,p=m=>{let f=m.clientX-s,h=Math.min(c,Math.max(l,o+f));this.root&&(this.root.style.width=`${h}px`)},d=()=>{var f,h;window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d);let m=(h=(f=this.root)==null?void 0:f.getBoundingClientRect().width)!=null?h:0;m>0&&window.localStorage.setItem("customizePanelWidth",String(Math.round(m)))};window.addEventListener("pointermove",p),window.addEventListener("pointerup",d)};e.addEventListener("pointerdown",i)}async getImageDimensions(e){let t=this.resolveAssetUrls(e);if(t.length===0)return null;for(let n of t){let i=await this.loadImage(n);if(i!=null&&i.naturalWidth&&(i!=null&&i.naturalHeight))return{width:i.naturalWidth,height:i.naturalHeight}}return null}async loadImage(e){return await new Promise(t=>{let n=new Image;n.onload=()=>t(n),n.onerror=()=>t(null),n.src=e})}async showManualCropModal(e,t,n){let i=t.width/t.height,a=URL.createObjectURL(e),s=await this.loadImage(a);try{URL.revokeObjectURL(a)}catch{}if(!(s!=null&&s.naturalWidth)||!(s!=null&&s.naturalHeight))return null;let o=await this.loadImageForValue(n);return await new Promise(l=>{let c=document.createElement("div");c.className="asset-crop-modal";let p=Math.min(860,window.innerWidth-60),m=Math.max(220,Math.floor((p-32-16)/2)),f=Math.min(520,window.innerHeight-240),h=m,b=h/i;b>f&&(b=f,h=b*i),c.innerHTML=`
|
|
1445
1541
|
<div class="asset-crop-card" style="width:${p}px;">
|
|
1446
1542
|
<div class="asset-crop-header">
|
|
1447
1543
|
<div>
|
|
1448
1544
|
<div class="asset-crop-title">Crop to match current asset</div>
|
|
1449
|
-
<div class="asset-crop-subtitle">${t.width}\xD7${t.height}px \u2022 ${
|
|
1545
|
+
<div class="asset-crop-subtitle">${t.width}\xD7${t.height}px \u2022 ${i.toFixed(3)} ratio</div>
|
|
1450
1546
|
</div>
|
|
1451
1547
|
<button class="asset-crop-close" type="button">Close</button>
|
|
1452
1548
|
</div>
|
|
@@ -1471,7 +1567,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1471
1567
|
<button class="asset-crop-apply" type="button">Apply Crop</button>
|
|
1472
1568
|
</div>
|
|
1473
1569
|
</div>
|
|
1474
|
-
`;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),S=c.querySelector(".asset-crop-zoom"),
|
|
1570
|
+
`;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),S=c.querySelector(".asset-crop-zoom"),C=c.querySelector(".asset-crop-zoom-value"),k=c.querySelector(".asset-crop-close"),z=c.querySelector(".asset-crop-cancel"),w=c.querySelector(".asset-crop-apply"),x=c.querySelector(".asset-crop-reset");if(!y||!v||!S||!C){l(null);return}let M=y.getContext("2d"),A=v.getContext("2d");if(!M||!A){l(null);return}let E=s.naturalWidth,I=s.naturalHeight,L=Math.max(y.width/E,y.height/I),_=1,P=0,R=0,T=!1,j=0,O=0,H=0,F=0,W=()=>{let D=L*_,je=Math.max(0,(E*D-y.width)/2),We=Math.max(0,(I*D-y.height)/2);P=Math.min(je,Math.max(-je,P)),R=Math.min(We,Math.max(-We,R))},J=()=>{let D=L*_;M.clearRect(0,0,y.width,y.height);let je=y.width/2-E*D/2+P,We=y.height/2-I*D/2+R;if(M.drawImage(s,je,We,E*D,I*D),A.clearRect(0,0,v.width,v.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let Ke=Math.max(v.width/o.naturalWidth,v.height/o.naturalHeight),pi=v.width/2-o.naturalWidth*Ke/2,mt=v.height/2-o.naturalHeight*Ke/2;A.drawImage(o,pi,mt,o.naturalWidth*Ke,o.naturalHeight*Ke)}else A.fillStyle="rgba(255, 255, 255, 0.04)",A.fillRect(0,0,v.width,v.height),A.strokeStyle="rgba(255, 255, 255, 0.08)",A.strokeRect(4,4,v.width-8,v.height-8);let ft=v.width/y.width*(L*_),Ye=P*(v.width/y.width),Vt=R*(v.height/y.height),ci=v.width/2-E*ft/2+Ye,di=v.height/2-I*ft/2+Vt;A.save(),A.globalAlpha=.7,A.drawImage(s,ci,di,E*ft,I*ft),A.restore()},qt=()=>{P=0,R=0,W(),J()};S.addEventListener("input",()=>{_=Number(S.value),C.textContent=`${_.toFixed(2)}\xD7`,W(),J()}),y.addEventListener("pointerdown",D=>{T=!0,j=D.clientX,O=D.clientY,H=P,F=R,y.setPointerCapture(D.pointerId)}),y.addEventListener("pointermove",D=>{T&&(P=H+(D.clientX-j),R=F+(D.clientY-O),W(),J())}),y.addEventListener("pointerup",D=>{T=!1,y.releasePointerCapture(D.pointerId)}),y.addEventListener("pointerleave",()=>{T=!1});let qe=()=>{c.remove()},Ve=()=>{qe(),l(null)},li=async()=>{let D=document.createElement("canvas");D.width=t.width,D.height=t.height;let je=D.getContext("2d");if(!je){qe(),l(null);return}let We=_,Ye=Math.max(D.width/E,D.height/I)*We,Vt=D.width/y.width,ci=P*Vt,di=R*Vt,Ke=D.width/2-E*Ye/2+ci,pi=D.height/2-I*Ye/2+di;je.drawImage(s,Ke,pi,E*Ye,I*Ye);let mt=await new Promise(Vs=>{D.toBlob(Ws=>Vs(Ws),e.type||"image/png")});if(qe(),!mt){l(null);return}l(new File([mt],e.name,{type:mt.type}))};k==null||k.addEventListener("click",Ve),z==null||z.addEventListener("click",Ve),x==null||x.addEventListener("click",qt),w==null||w.addEventListener("click",()=>{li()}),c.addEventListener("click",D=>{D.target===c&&Ve()}),document.body.appendChild(c),qt()})}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 qn=class{constructor(){this.root=null;this.options=null}render(){return`
|
|
1475
1571
|
<div class="scene-panel loading-screen-panel panel-accent-purple" data-panel="loading-screen">
|
|
1476
1572
|
<div class="scene-panel-header" data-panel-handle>
|
|
1477
1573
|
<div class="panel-title">
|
|
@@ -1537,10 +1633,10 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1537
1633
|
</div>
|
|
1538
1634
|
</div>
|
|
1539
1635
|
</div>
|
|
1540
|
-
`}initialize(e,t){var y,v,S,x,w,P,E,_,R,C,A,k,L,I,M,z;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let n=(()=>{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=n.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=n.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=(x=this.root)==null?void 0:x.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((w=n.overlay_alpha)!=null?w: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=(P=this.root)==null?void 0:P.querySelector("#loading-text");c&&(c.value=n.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=(E=this.root)==null?void 0:E.querySelector("#loading-text-scale"),d=(_=this.root)==null?void 0:_.querySelector("#loading-text-scale-value");p&&(p.value=String((R=n.text_scale)!=null?R:.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=(C=this.root)==null?void 0:C.querySelector("#loading-enabled");u&&(u.checked=n.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=(A=this.root)==null?void 0:A.querySelector("#loading-blur-enabled");g&&(g.checked=n.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=(k=this.root)==null?void 0:k.querySelector("#loading-blur-strength"),f=(L=this.root)==null?void 0:L.querySelector("#loading-blur-strength-value");m&&(m.value=String((I=n.blur_strength)!=null?I:8),f&&(f.textContent=m.value),m.addEventListener("input",()=>{var T,j;f&&(f.textContent=m.value),(j=(T=this.options)==null?void 0:T.onUpdateLoading)==null||j.call(T,{blur_strength:Number(m.value)})}));let h=(M=this.root)==null?void 0:M.querySelector("#loading-show-btn"),b=(z=this.root)==null?void 0:z.querySelector("#loading-hide-btn");h==null||h.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(n.type==="image"?"image":"color")}updateFieldVisibility(e){var n,a;let t=(n=this.root)==null?void 0:n.querySelector("#loading-color-field"),i=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),i&&(i.style.display="none")):(t&&(t.style.display=""),i&&(i.style.display=""))}refresh(){}};var kt=require("pixi.js");Ze();K();async function ns(r,e,t){var i,n;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 kt.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),(i=c[u])!=null&&i.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=((n=g.getDisplayObject)==null?void 0:n.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 as(r,e){var t,i,n;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(h=>h.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 kt.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(h=>h.startsWith(g)||h.includes(g));for(let h of m)oe[h]=d,console.log("[LIBRARY] \u2705 Reset AssetTextures."+h),(i=u[h])!=null&&i.texture&&(u[h].texture=d,console.log("[LIBRARY] \u2705 Reset CustomAssets."+h+" to default"));let f=window.gameObjectManager;if(f)for(let h of m){let b=f.get(h);if(b){let y=((n=b.getDisplayObject)==null?void 0:n.call(b))||b.pixiObject||b;y!=null&&y.texture&&(y.texture=d,console.log("[LIBRARY] \u2705 Reset display object:",h))}}}catch(a){console.error("[LIBRARY] Error resetting asset:",a)}}async function rs(r,e,t,i){var n,a,s,o,l,c,p,d,u,g,m,f,h,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:i});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let S=Date.now(),x=`/raw/library/${i}/${t}?t=${S}`;console.log("[LIBRARY] Loading texture from:",x);let w=await kt.Assets.load(x);if(!w){console.error("[LIBRARY] Failed to load texture:",x);return}console.log("[LIBRARY] \u2705 Texture loaded"),oe[v]=w,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let P=window.CustomAssets;P!=null&&P[v]&&(P[v].texture=w,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let E=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!E),E){let R=Array.from(((n=E.keys)==null?void 0:n.call(E))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",R);let C=E.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!C),C){let A=((a=C.getDisplayObject)==null?void 0:a.call(C))||C.pixiObject||C.pixi||C,k=(s=A==null?void 0:A.constructor)==null?void 0:s.name;if(console.log("[LIBRARY] displayObject:",A),console.log("[LIBRARY] displayObject type:",k),console.log("[LIBRARY] has texture?",!!(A!=null&&A.texture)),A!=null&&A.texture)A.texture=w,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(k==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:L}=await import("pixi.js"),I=A.parent,M=(l=(o=I==null?void 0:I.getChildIndex)==null?void 0:o.call(I,A))!=null?l:0,z={x:A.x,y:A.y},T={x:(p=(c=A.anchor)==null?void 0:c.x)!=null?p:.5,y:(u=(d=A.anchor)==null?void 0:d.y)!=null?u:.5},j={x:(m=(g=A.scale)==null?void 0:g.x)!=null?m:1,y:(h=(f=A.scale)==null?void 0:f.y)!=null?h:1},O=(b=A.alpha)!=null?b:1,F=(y=A.visible)!=null?y:!0,U=new L(w);U.anchor.set(T.x,T.y),U.position.set(z.x,z.y),U.scale.set(j.x,j.y),U.alpha=O,U.visible=F,I&&(I.removeChild(A),I.addChildAt(U,M),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),C.pixiObject&&(C.pixiObject=U),C.pixi&&(C.pixi=U),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(A!=null&&A.children){let L=A.children.find(I=>I.texture);L?(L.texture=w,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let _=`raw/library/${i}/${t}`;le({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 ss(r,e,t,i){var n;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:i});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 kt.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=((n=d.getDisplayObject)==null?void 0:n.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 _t=require("pixi.js");var Zn=require("pixi.js"),Me=()=>window.debugConfig||{},os=()=>window.resolveAnchorVec2||(r=>({x:.5,y:.5})),ls=()=>window.resolveScreenAnchorPoint||(()=>new Zn.Point),cs=()=>window.resolveScreenRatioPoint||(()=>new Zn.Point);function ds(r){Bi(r)&&(r.objectDebugRaf||(r.objectDebugRaf=window.requestAnimationFrame(()=>Ui(r))))}function ps(r){r.objectDebugRaf&&(window.cancelAnimationFrame(r.objectDebugRaf),r.objectDebugRaf=null),Mt(r)}function Bi(r){return r.isDebugOpen}function Ui(r){var a,s,o;if(!Bi(r)){r.objectDebugRaf=null;return}r.objectDebugRaf=window.requestAnimationFrame(()=>Ui(r));let e=Qn(r);if(!e){It(r,null),Mt(r);return}let t=ea(r,e);if(!t){It(r,null),Mt(r);return}let i=new _t.Point;(a=t.getGlobalPosition)==null||a.call(t,i);let n=ta(r,t);It(r,{instanceId:e,worldX:i.x,worldY:i.y,configX:(s=n==null?void 0:n.x)!=null?s:null,configY:(o=n==null?void 0:n.y)!=null?o:null}),r.highlightObject?ra(r,t):oa(r),r.highlightAnchor&&n?sa(r,n):la(r)}function Qn(r){var n;let e=r.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,i=(n=t==null?void 0:t.get)==null?void 0:n.call(t,e);return Array.isArray(i)&&i.length>0?i[0]:e}function ea(r,e){var n,a;let t=window.gameObjectManager,i=(n=t==null?void 0:t.get)==null?void 0:n.call(t,e);return i?((a=i.getDisplayObject)==null?void 0:a.call(i))||i.pixiObject||i:null}function Pt(r){let e=r.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function ta(r,e){var s,o;let t=Pt(r);if(!t)return null;let i=(s=t.transform)!=null?s:{},n=ia(r);if(!n)return null;if(i.position_ratio!=null)return cs()(n.width,n.height,i.position_ratio);let a=(o=i.anchor)!=null?o:"center";return ls()(n.width,n.height,a)}function ia(r){var a;let e=(a=r.container)==null?void 0:a.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),i=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(i)&&i>0)return{width:t,height:i};let n=window.gameApp;return n!=null&&n.renderer?{width:n.renderer.width,height:n.renderer.height}:null}function na(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 _t.Graphics,r.objectBoundsGfx.zIndex=999999,e.stage.addChild(r.objectBoundsGfx)),r.objectBoundsGfx):null}function aa(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 _t.Graphics,r.objectAnchorGfx.zIndex=1e6,e.stage.addChild(r.objectAnchorGfx)),r.objectAnchorGfx):null}function ra(r,e){var n;let t=na(r);if(!t)return;let i=(n=e.getBounds)==null?void 0:n.call(e);i&&(t.clear(),t.rect(i.x,i.y,i.width,i.height).stroke({width:2,color:16726832,alpha:.9}))}function sa(r,e){let t=aa(r);if(!t)return;let i=6;t.clear(),t.moveTo(e.x-i,e.y),t.lineTo(e.x+i,e.y),t.moveTo(e.x,e.y-i),t.lineTo(e.x,e.y+i),t.stroke({width:2,color:3066993,alpha:.9})}function oa(r){r.objectBoundsGfx&&r.objectBoundsGfx.clear()}function la(r){r.objectAnchorGfx&&r.objectAnchorGfx.clear()}function Mt(r){r.objectBoundsGfx&&(r.objectBoundsGfx.destroy(),r.objectBoundsGfx=null),r.objectAnchorGfx&&(r.objectAnchorGfx.destroy(),r.objectAnchorGfx=null)}function It(r,e){r.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function us(r,e){return e.split(".").reduce((t,i)=>t?t[i]:void 0,r)}function gs(r,e,t){var s;let i=e.split("."),n=i.pop(),a=r;for(let o of i)a[o]=(s=a[o])!=null?s:{},a=a[o];a[n]=t}function ca(r){var i,n,a,s,o;if(!r)return!1;if((i=r.transform)!=null&&i.offset)return!0;let e=((a=(n=r.identity)==null?void 0:n.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 qi(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 hs(r){window.location.reload()}function Vi(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 fs(r,e){var t,i,n;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(()=>(hi(),Dr)),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),Gi(r,u),(i=r.configViewer)==null||i.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,s),Gi(r,s),(n=r.configViewer)==null||n.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function Gi(r,e){var d,u,g,m,f,h,b,y,v,S;if(!r.container)return;let t=r.container.querySelector("#config-pos-x"),i=r.container.querySelector("#config-pos-y"),n=r.container.querySelector("#config-scale"),a=r.container.querySelector("#config-anchor-x"),s=r.container.querySelector("#config-anchor-y"),l=ca(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)),i&&(i.value=String((m=l==null?void 0:l.y)!=null?m:0)),n&&(n.value=String((h=(f=e.transform)==null?void 0:f.scale)!=null?h: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=os()(c);a&&(a.value=String(p.x)),s&&(s.value=String(p.y))}function ms(r){var l,c,p,d,u,g,m,f,h,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",i=(d=(p=r.container.querySelector("#config-pos-y"))==null?void 0:p.value)!=null?d:"0",n=(g=(u=r.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",a=(f=(m=r.container.querySelector("#config-anchor-x"))==null?void 0:m.value)!=null?f:"0.5",s=(b=(h=r.container.querySelector("#config-anchor-y"))==null?void 0:h.value)!=null?b:"0.5",o=`${e}:
|
|
1541
|
-
position: (${t}, ${
|
|
1542
|
-
scale: ${
|
|
1543
|
-
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 da(r,e){var d,u,g,m,f,h,b,y,v,S,x;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 i=Number((u=(d=r.container.querySelector("#config-pos-x"))==null?void 0:d.value)!=null?u:0),n=Number((m=(g=r.container.querySelector("#config-pos-y"))==null?void 0:g.value)!=null?m:0),a=Number((h=(f=r.container.querySelector("#config-scale"))==null?void 0:f.value)!=null?h: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:i,posY:n,scale:a,anchorX:s,anchorY:o});let{applyConfigOverride:l}=await Promise.resolve().then(()=>(K(),He));l({objectId:t,path:"transform.position",value:{x:i,y:n}},{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=Pt(r);ca(c)&&l({objectId:t,path:"transform.offset",value:{x:i,y:n}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let p=window.applyEditableObjectConfig;if(typeof p=="function"){let w=(x=window.getEditableObjectConfig)==null?void 0:x.call(window,t);w?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",t),p(t,w)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",t)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function bs(r,e,t){let{applyConfigOverride:i}=await Promise.resolve().then(()=>(K(),He));Object.entries(e.assets).forEach(([l,c])=>{i({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{i({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{i({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{i({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{i({path:`runtime.audio.${l}`,value:c},{silent:!0})});let n=window.applyEditableEngineConfig;if(typeof n=="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 f=0;f<g.length-1;f++){let h=g[f];m[h]=(u=m[h])!=null?u:{},m=m[h]}m[g[g.length-1]]=d}else c[p]=d}),l.ui=c,n({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 ys(r){r.selectedObjectId&&(r.objectAutoApplyTimer&&window.clearTimeout(r.objectAutoApplyTimer),r.objectAutoApplyTimer=window.setTimeout(()=>{r.objectAutoApplyTimer=null,da(r,{silent:!0})},150))}var sl=3e3;function jt(r,e,t){let i=t!=null?t:r.offsetParent;if(!i)return;e.style.cursor="move";let n=!1,a=0,s=0,o=0,l=0,c=0,p=0,d=g=>{if(!n)return;let m=i.getBoundingClientRect();r.style.left=`${g.clientX-m.left-c}px`,r.style.top=`${g.clientY-m.top-p}px`},u=()=>{n&&(n=!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 f=r.getBoundingClientRect(),h=i.getBoundingClientRect();console.log("[DRAG] Panel:",r.className),console.log("[DRAG] Container:",i.className),console.log("[DRAG] panelRect:",{left:f.left,top:f.top,width:f.width,height:f.height}),console.log("[DRAG] containerRect:",{left:h.left,top:h.top,width:h.width,height:h.height}),console.log("[DRAG] mouse:",{x:g.clientX,y:g.clientY}),c=g.clientX-f.left,p=g.clientY-f.top,console.log("[DRAG] offset:",{x:c,y:p});let b=f.left-h.left,y=f.top-h.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),n=!0,r.classList.add("dragging"),window.addEventListener("pointermove",d),window.addEventListener("pointerup",u)})}function vs(r,e,t,i=280,n=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,f=Math.max(i,a+g),h=Math.max(n,s+m);r.style.width=`${f}px`,(y=r.closest(".preview-shell"))!=null&&y.classList.contains("layout-fixed")||(r.style.height=`${h}px`),t==null||t(f,h)},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 pa(r,e){var f,h,b,y;let t=(b=(h=(f=r.container)==null?void 0:f.querySelector("#debug-overlay"))!=null?h:r.debugOverlay)!=null?b:e.offsetParent;if(!t||(y=r.container)!=null&&y.classList.contains("layout-fixed"))return;let i=t.getBoundingClientRect(),n=e.getBoundingClientRect(),a=12,s=Math.max(250,Math.floor(i.width-a*2)),o=Math.max(200,Math.floor(i.height-a*2));n.width>s&&(e.style.width=`${s}px`),n.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-i.left,p=l.top-i.top,d=Math.max(a,i.width-l.width-a),u=Math.max(a,i.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 it(r){var i,n;if(!r.container)return;let e=r.container.querySelector("#debug-workbench");if(!e)return;if(pa(r,e),(i=r.container)!=null&&i.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:(n=r.container)!=null&&n.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function Wi(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 n,a;let i=(n=r.container)==null?void 0:n.querySelector("#debug-workbench");if(i){let s=(a=r.container)==null?void 0:a.classList.contains("layout-fixed");t.width&&(i.style.width=t.width),t.height&&!s?i.style.height=t.height:s&&(i.style.height=""),t.left&&(i.style.left=t.left,i.style.right="auto"),t.top&&(i.style.top=t.top,i.style.bottom="auto"),pa(r,i)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function ua(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",pa(r,e),it(r))}function ws(r){var n,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)}),(n=e.querySelector("#debug-close"))==null||n.addEventListener("click",()=>{var o;return(o=r.toggleDebug)==null?void 0:o.call(r,!1)}),(a=e.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>qi(r)),(s=e.querySelector("#debug-export"))==null||s.addEventListener("click",()=>Vi(r)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;r.activeTab=l,ga(r),it(r)})}),fa(r,e),ha(r,e)}function ga(r){if(!r.container)return;let e=r.container;e.querySelectorAll(".workbench-tab").forEach(n=>{let a=n.dataset.tab;n.classList.toggle("active",a===r.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(n=>{let a=n.dataset.tabPanel;n.classList.toggle("active",a===r.activeTab)})}function ha(r,e){ne(r,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),ne(r,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),ne(r,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),ne(r,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),ne(r,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),ne(r,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),ne(r,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),ne(r,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),ne(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 n=Me();n.layout&&(n.layout.debug_rect_visible=!!t.checked)});let i=e.querySelector("#debug-rect-color");i==null||i.addEventListener("input",()=>{let n=i.value.replace("#",""),a=parseInt(n,16),s=Me();s.layout&&(s.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function xs(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"),jt(e,t,r.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{it(r),ua(r,e)},10)}));let i=r.container.querySelector('[data-panel="scene-objects"]'),n=i==null?void 0:i.querySelector("[data-panel-handle]"),a=i==null?void 0:i.querySelector("[data-panel-resize-v]");i&&n&&(!i.style.left&&!i.style.right&&!i.style.top&&!i.style.bottom&&(i.style.left="16px",i.style.top="72px"),jt(i,n,r.debugOverlay),n.addEventListener("pointerup",()=>{setTimeout(()=>{ua(r,i)},10)})),i&&a&&vs(i,a);let s=r.container.querySelector('[data-panel="scene-tools-corner"]'),o=s==null?void 0:s.querySelector("[data-panel-handle]");s&&o&&jt(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&&jt(l,c,r.debugOverlay),Wi(r)}function fa(r,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(i=>{i.addEventListener("click",()=>{let n=i.closest(".scene-panel");n&&n.classList.toggle("collapsed")})})}function ne(r,e,t,i,n){let a=e.querySelector(`#${t}`),s=e.querySelector(n);if(!a||!s)return;let o=us(Me(),i);typeof o=="number"&&(a.value=String(o),s.textContent=String(o)),a.addEventListener("input",()=>{let l=Number(a.value);s.textContent=String(l),gs(Me(),i,l)})}K();var Yi=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:i,overrides:n}=e,a={};for(let p of n){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`
|
|
1636
|
+
`}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"),f=(L=this.root)==null?void 0:L.querySelector("#loading-blur-strength-value");m&&(m.value=String((_=i.blur_strength)!=null?_:8),f&&(f.textContent=m.value),m.addEventListener("input",()=>{var T,j;f&&(f.textContent=m.value),(j=(T=this.options)==null?void 0:T.onUpdateLoading)==null||j.call(T,{blur_strength:Number(m.value)})}));let h=(P=this.root)==null?void 0:P.querySelector("#loading-show-btn"),b=(R=this.root)==null?void 0:R.querySelector("#loading-hide-btn");h==null||h.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(h=>h.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(h=>h.startsWith(g)||h.includes(g));for(let h of m)oe[h]=d,console.log("[LIBRARY] \u2705 Reset AssetTextures."+h),(n=u[h])!=null&&n.texture&&(u[h].texture=d,console.log("[LIBRARY] \u2705 Reset CustomAssets."+h+" to default"));let f=window.gameObjectManager;if(f)for(let h of m){let b=f.get(h);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:",h))}}}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,f,h,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:(h=(f=E.scale)==null?void 0:f.y)!=null?h: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,f,h,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((h=(f=e.transform)==null?void 0:f.scale)!=null?h: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,f,h,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=(f=(m=r.container.querySelector("#config-anchor-x"))==null?void 0:m.value)!=null?f:"0.5",s=(b=(h=r.container.querySelector("#config-anchor-y"))==null?void 0:h.value)!=null?b:"0.5",o=`${e}:
|
|
1637
|
+
position: (${t}, ${n})
|
|
1638
|
+
scale: ${i}
|
|
1639
|
+
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,f,h,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((h=(f=r.container.querySelector("#config-scale"))==null?void 0:f.value)!=null?h: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 f=0;f<g.length-1;f++){let h=g[f];m[h]=(u=m[h])!=null?u:{},m=m[h]}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 f=r.getBoundingClientRect(),h=n.getBoundingClientRect();console.log("[DRAG] Panel:",r.className),console.log("[DRAG] Container:",n.className),console.log("[DRAG] panelRect:",{left:f.left,top:f.top,width:f.width,height:f.height}),console.log("[DRAG] containerRect:",{left:h.left,top:h.top,width:h.width,height:h.height}),console.log("[DRAG] mouse:",{x:g.clientX,y:g.clientY}),c=g.clientX-f.left,p=g.clientY-f.top,console.log("[DRAG] offset:",{x:c,y:p});let b=f.left-h.left,y=f.top-h.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,f=Math.max(n,a+g),h=Math.max(i,s+m);r.style.width=`${f}px`,(y=r.closest(".preview-shell"))!=null&&y.classList.contains("layout-fixed")||(r.style.height=`${h}px`),t==null||t(f,h)},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 f,h,b,y;let t=(b=(h=(f=r.container)==null?void 0:f.querySelector("#debug-overlay"))!=null?h: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`
|
|
1544
1640
|
<div class="config-persistence-panel">
|
|
1545
1641
|
<!-- Status Footer (Always Visible) -->
|
|
1546
1642
|
<div class="persistence-status-footer">
|
|
@@ -1550,7 +1646,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1550
1646
|
</div>
|
|
1551
1647
|
<div class="status-footer-row">
|
|
1552
1648
|
<span class="status-footer-label">Overrides:</span>
|
|
1553
|
-
<span class="status-footer-value">${
|
|
1649
|
+
<span class="status-footer-value">${n} staged</span>
|
|
1554
1650
|
</div>
|
|
1555
1651
|
<div class="status-footer-row">
|
|
1556
1652
|
<span class="status-footer-label">Assets:</span>
|
|
@@ -1573,7 +1669,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
|
|
|
1573
1669
|
${t?`
|
|
1574
1670
|
<div class="status-box">
|
|
1575
1671
|
<span class="status-badge">UNAPPLIED</span>
|
|
1576
|
-
<span class="status-text">${
|
|
1672
|
+
<span class="status-text">${n} staging changes</span>
|
|
1577
1673
|
</div>
|
|
1578
1674
|
<div class="status-action-hint">Review below before applying to project</div>
|
|
1579
1675
|
`:`
|
|
@@ -1698,11 +1794,11 @@ This will:
|
|
|
1698
1794
|
\u2022 Create a new version snapshot
|
|
1699
1795
|
\u2022 Include all current changes
|
|
1700
1796
|
\u2022 Clear staged overrides after save
|
|
1701
|
-
\u2022 Set the new version as active`))try{let m=localStorage.getItem("handler_last_version_name")||"",h=((g=prompt("Version name (e.g. v1.2.0, test_2024):",m))!=null?g:"").trim();if(!h){alert("Version name is required.");return}localStorage.setItem("handler_last_version_name",h),e.textContent="\u23F3 Creating version...",e.setAttribute("disabled","true"),await
|
|
1797
|
+
\u2022 Set the new version as active`))try{let m=localStorage.getItem("handler_last_version_name")||"",h=((g=prompt("Version name (e.g. v1.2.0, test_2024):",m))!=null?g:"").trim();if(!h){alert("Version name is required.");return}localStorage.setItem("handler_last_version_name",h),e.textContent="\u23F3 Creating version...",e.setAttribute("disabled","true"),await un(h),te(),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?
|
|
1702
1798
|
|
|
1703
1799
|
This will write all staged changes to ${d}.
|
|
1704
1800
|
|
|
1705
|
-
After applying, staged overrides will be cleared.`))try{t.textContent="\u23F3 Applying...",t.setAttribute("disabled","true");let g=De(),m={};for(let[b,y]of Object.entries(g.objects)){let v=y,S=b;/^(json\.|ui\.|effects\.|engine\.)/.test(S)||(S=`json.${b}`),v&&typeof v=="object"&&(v.identity||(v.identity={}),v.identity.id=S),m[`objects/${S}.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 f=this.currentVersion?"/api/apply-current":"/api/apply-direct",h=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:m,assets:{},hadCacheAtApply:!0})});if(!h.ok){let b=await h.json();throw new Error(b.error||"Apply to current source failed")}
|
|
1801
|
+
After applying, staged overrides will be cleared.`))try{t.textContent="\u23F3 Applying...",t.setAttribute("disabled","true");let g=De(),m={};for(let[b,y]of Object.entries(g.objects)){let v=y,S=b;/^(json\.|ui\.|effects\.|engine\.)/.test(S)||(S=`json.${b}`),v&&typeof v=="object"&&(v.identity||(v.identity={}),v.identity.id=S),m[`objects/${S}.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 f=this.currentVersion?"/api/apply-current":"/api/apply-direct",h=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:m,assets:{},hadCacheAtApply:!0})});if(!h.ok){let b=await h.json();throw new Error(b.error||"Apply to current source failed")}te(),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
|
|
1706
1802
|
|
|
1707
1803
|
This will DIRECTLY MODIFY base configuration files.
|
|
1708
1804
|
|
|
@@ -1712,25 +1808,25 @@ This is ONLY for active development.
|
|
|
1712
1808
|
|
|
1713
1809
|
Make sure your project is under Git version control.
|
|
1714
1810
|
|
|
1715
|
-
Continue?`))try{
|
|
1811
|
+
Continue?`))try{n.textContent="\u23F3 Writing to base...",n.setAttribute("disabled","true");let u=De(),g={};for(let[f,h]of Object.entries(u.objects)){let b=h,y=f;/^(json\.|ui\.|effects\.|engine\.)/.test(y)||(y=`json.${f}`),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[f,h]of Object.entries(u.scenes)){let b=f.startsWith("scene.")?f:`scene.${f}`;g[`scenes/${b}.json`]=h}let m=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:g,assets:{}})});if(!m.ok){let f=await m.json();throw new Error(f.error||"Apply to base failed")}te(),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;Ct(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.")&&(te(),Tt(),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?")&&Tt()});let p=this.container.querySelector("#reset-to-original-btn");p==null||p.addEventListener("click",async()=>{await gn()})}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=`
|
|
1716
1812
|
<div class="notify-icon">\u2705</div>
|
|
1717
1813
|
<div class="notify-content">
|
|
1718
|
-
<strong>${
|
|
1814
|
+
<strong>${n}</strong>
|
|
1719
1815
|
<span>Project files updated.</span>
|
|
1720
1816
|
</div>
|
|
1721
|
-
`,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
|
|
1817
|
+
`,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=Te();if(t.hasChanges){if(!confirm(`Switch to version "${e||"original"}"?
|
|
1722
1818
|
|
|
1723
1819
|
You have ${t.overrideCount} staged changes that will be discarded.
|
|
1724
1820
|
|
|
1725
1821
|
Options:
|
|
1726
1822
|
OK = Discard staged overrides and switch
|
|
1727
|
-
Cancel = Stay on current version`)){let l=(
|
|
1823
|
+
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")}te(),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
|
|
1728
1824
|
|
|
1729
1825
|
This will DIRECTLY MODIFY your base configuration files WITHOUT creating a snapshot.
|
|
1730
1826
|
|
|
1731
1827
|
This cannot be undone unless you have git commits or backups.
|
|
1732
1828
|
|
|
1733
|
-
Are you absolutely sure?`))try{let t=De(),
|
|
1829
|
+
Are you absolutely sure?`))try{let t=De(),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")}te(),this.showSuccessNotification(),this.refreshPanel()}catch(t){console.error("[ConfigPersistence] Direct apply failed:",t),alert(`\u274C Direct apply failed: ${t.message}`)}}};var zt=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 An;this.sceneToolsPanel=new Cn;this.nudgePanel=new Tn;this.inspectorPanel=new Nn;this.libraryPanel=new It;this.libraryPanelDocked=new It;this.brandVisionPanel=new Un;this.customizeSettingsPanel=new Gn;this.configPersistencePanel=new Zn;this.loadingScreenPanel=new qn}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 Vn(this)}updateObjectVisuals(){return Wn(this)}getSelectedInstanceId(){return ta(this)}getDisplayObjectById(e){return na(this,e)}getSelectedObjectConfig(){return Ot(this)}getConfigAnchorWorldPoint(e){return ia(this,e)}getScreenSize(){return aa(this)}ensureBoundsGfx(){return ra(this)}ensureAnchorGfx(){return sa(this)}drawBounds(e){return oa(this,e)}drawAnchor(e){return la(this,e)}clearBounds(){return ca(this)}clearAnchor(){return da(this)}clearObjectVisuals(){return _t(this)}updateObjectInfo(e){return Pt(this,e)}resetDebugConfig(){return Kn(this)}applyDebugConfig(){return fs(this)}exportDebugConfig(){return Xn(this)}loadObjectConfig(e){return ms(this,e)}fillConfigViewer(e){return Yn(this,e)}copyConfigValues(){return bs(this)}applyObjectConfig(e){return ua(this,e)}applyCustomizeSettings(e,t){return ys(this,e,t)}scheduleObjectAutoApply(){return vs(this)}setupDebugEventListeners(){return xs(this)}setupDebugInputListeners(e){return ma(this,e)}setupPanelLayout(){return Es(this)}setupCollapsiblePanels(e){return ba(this,e)}setupRangeInput(e,t,n,i){return ae(this,e,t,n,i)}updateWorkbenchTabs(){return fa(this)}saveWorkbenchState(){return at(this)}loadWorkbenchState(){return Jn(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,f,h,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=((f=l==null?void 0:l.y)!=null?f:0)+s,{applyConfigOverride:d}=await Promise.resolve().then(()=>(X(),He));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,S=(y=(b=(h=v==null?void 0:v.objects)==null?void 0:h.get)==null?void 0:b.call(h,this.selectedObjectId))!=null?y:o;await u(this.selectedObjectId,S)}window.dispatchEvent(new CustomEvent("inspector:refresh"))},onScale:async a=>{var d,u,g,m,f;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(()=>(X(),He));c({objectId:this.selectedObjectId,path:"transform.scale",value:l},{silent:!0,emitEvent:!0});let p=window.applyEditableObjectConfig;if(typeof p=="function"){let h=window.__editableConfig,b=(f=(m=(g=h==null?void 0:h.objects)==null?void 0:g.get)==null?void 0:m.call(g,this.selectedObjectId))!=null?f: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`
|
|
1734
1830
|
<div class="debug-overlay hidden" id="debug-overlay">
|
|
1735
1831
|
<div class="debug-workbench" id="debug-workbench">
|
|
1736
1832
|
<div class="workbench-header" id="workbench-handle">
|
|
@@ -1777,7 +1873,7 @@ Are you absolutely sure?`))try{let t=De(),i={};for(let[a,s]of Object.entries(t.o
|
|
|
1777
1873
|
${this.sceneToolsPanel.render()}
|
|
1778
1874
|
${this.nudgePanel.render()}
|
|
1779
1875
|
</div>
|
|
1780
|
-
`}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
|
|
1876
|
+
`}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),f=g+e*i,h=m+t*i;d.value=String(f),u.value=String(h),(c=this.configViewer)==null||c.style.setProperty("display","block"),this.scheduleObjectAutoApply();return}}let a=window.getEditableObjectConfig;if(typeof a!="function")return;let s=new ke;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,f=Array.isArray(g)?g[1]:g.y||0,h=m+e*i,b=f+t*i;await s.updateProperty(d,"transform.position",[h,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`
|
|
1781
1877
|
Analyze these screenshots of a brand or game and extract its "Brand DNA".
|
|
1782
1878
|
|
|
1783
1879
|
Provide a concise summary (2-3 sentences) covering:
|
|
@@ -1794,9 +1890,9 @@ Palette: [#RRGGBB, #RRGGBB, ...]
|
|
|
1794
1890
|
${r?`
|
|
1795
1891
|
ADDITIONAL RULES/NOTES:
|
|
1796
1892
|
${r}`:""}
|
|
1797
|
-
`.trim()}function
|
|
1893
|
+
`.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 Bn(n,s,o,{model:a}),c=e,p=[],d=l.split(`
|
|
1798
1894
|
`);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(`
|
|
1799
|
-
Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0,10)},t},setSummary(
|
|
1895
|
+
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 Ue="handler_api_key_";var rt=class{static setKey(e,t,n){try{let i={key:this.encryptKey(t),created:Date.now(),lastUsed:Date.now(),label:n||e},a=`${Ue}${e}`;localStorage.setItem(a,JSON.stringify(i))}catch(i){console.error("[ApiKeyStorage] Failed to store API key:",i)}}static getKey(e){try{let t=`${Ue}${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=`${Ue}${e}`;return localStorage.getItem(t)!==null}static removeKey(e){try{let t=`${Ue}${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(Ue)){let i=n.substring(Ue.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(Ue)&&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}}},ya=()=>rt.getKey("gemini"),va=(r,e)=>rt.setKey("gemini",r,e),dl=()=>rt.hasKey("gemini");window.ApiKeyStorage=rt;window.getGeminiApiKey=ya;window.setGeminiApiKey=va;window.hasGeminiApiKey=dl;var xa=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=`
|
|
1800
1896
|
<div class="ai-modal-card">
|
|
1801
1897
|
<div class="ai-modal-header">
|
|
1802
1898
|
<div class="ai-modal-actions">
|
|
@@ -1875,17 +1971,17 @@ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0
|
|
|
1875
1971
|
<button class="ai-btn primary" data-action="apply" disabled>Apply</button>
|
|
1876
1972
|
</div>
|
|
1877
1973
|
</div>
|
|
1878
|
-
`,this.modal=e,this.attachEventListeners(),this.updatePromptFromDna()}attachEventListeners(){var
|
|
1974
|
+
`,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}
|
|
1879
1975
|
|
|
1880
|
-
Style guidelines: ${
|
|
1881
|
-
<div class="ai-gallery-item ${
|
|
1882
|
-
<img class="ai-gallery-thumb" src="${t}" alt="Generated ${
|
|
1883
|
-
<div class="ai-gallery-label">#${
|
|
1976
|
+
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 Fn(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 it(a,this.currentPrompt,s,{aspectRatio:"1:1"}),l=await nt(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)=>`
|
|
1977
|
+
<div class="ai-gallery-item ${n===this.selectedImageIndex?"active":""}" data-index="${n}">
|
|
1978
|
+
<img class="ai-gallery-thumb" src="${t}" alt="Generated ${n+1}" />
|
|
1979
|
+
<div class="ai-gallery-label">#${n+1}</div>
|
|
1884
1980
|
</div>
|
|
1885
|
-
`).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=
|
|
1981
|
+
`).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=ya();if(e)return e;try{let t=this.analyzer.getResult();if(t&&t.apiKey)return va(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}},wa=null;window.__openAiEditor=function(r,e,t,n){wa||(wa=new xa),wa.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"))}})};Sa();var Aa=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=`
|
|
1886
1982
|
<div class="asset-preview-card">
|
|
1887
1983
|
<div class="asset-preview-header">
|
|
1888
|
-
<div class="asset-preview-title">${
|
|
1984
|
+
<div class="asset-preview-title">${i}</div>
|
|
1889
1985
|
<button class="asset-preview-close" data-action="close">\xD7</button>
|
|
1890
1986
|
</div>
|
|
1891
1987
|
|
|
@@ -1903,13 +1999,13 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
1903
1999
|
${t==="image"?'<button class="asset-preview-ai" data-action="edit">\u2728 AI Edit</button>':""}
|
|
1904
2000
|
</div>
|
|
1905
2001
|
</div>
|
|
1906
|
-
`,this.modal=a,this.attachEventListeners()}renderAssetContent(e,t){if(!e)return'<div class="asset-preview-placeholder">No asset selected</div>';switch(t){case"image":return`<img src="${this.resolveAssetUrl(e)}" alt="Asset preview" style="max-width: 100%; max-height: 400px; object-fit: contain;" />`;case"audio":let
|
|
2002
|
+
`,this.modal=a,this.attachEventListeners()}renderAssetContent(e,t){if(!e)return'<div class="asset-preview-placeholder">No asset selected</div>';switch(t){case"image":return`<img src="${this.resolveAssetUrl(e)}" alt="Asset preview" style="max-width: 100%; max-height: 400px; object-fit: contain;" />`;case"audio":let i=this.resolveAssetUrl(e);return`
|
|
1907
2003
|
<audio controls style="width: 100%;">
|
|
1908
|
-
<source src="${
|
|
1909
|
-
<source src="${
|
|
2004
|
+
<source src="${i}" type="audio/mpeg">
|
|
2005
|
+
<source src="${i}" type="audio/wav">
|
|
1910
2006
|
Your browser does not support the audio element.
|
|
1911
2007
|
</audio>
|
|
1912
|
-
`;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",
|
|
2008
|
+
`;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(()=>(Sa(),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 Aa().open(r)};var Ca=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=`
|
|
1913
2009
|
<div class="asset-crop-card">
|
|
1914
2010
|
<div class="asset-crop-header">
|
|
1915
2011
|
<div>
|
|
@@ -1960,7 +2056,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
1960
2056
|
<button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
|
|
1961
2057
|
</div>
|
|
1962
2058
|
</div>
|
|
1963
|
-
`,this.modal=e,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var i;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(i=this.options)!=null&&i.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,i=this.cropX+this.cropWidth/2,n=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,i-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,n-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let e=this.panX,t=this.panY,i=this.cropWidth*this.scale,n=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,i,n),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,i,n),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+i-a,t],[e,t+n-a],[e+i-a,t+n-a]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,a,a)})}updatePreview(){if(!this.modal||!this.image)return;let e=this.modal.querySelector(".asset-crop-preview-canvas");if(!e)return;let t=e.getContext("2d");if(!t)return;let i=150;e.width=i,e.height=i;let n=i/this.cropWidth,a=i/this.cropHeight,s=Math.min(n,a),o=this.cropWidth*s,l=this.cropHeight*s,c=(i-o)/2,p=(i-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",i=>{let n=parseFloat(i.target.value);this.setZoom(n)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",i=>{let n=i.target.value;this.setAspectRatio(n)}),this.modal.addEventListener("click",i=>{switch(i.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",i=>{i.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,i=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,i=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var n;if(!this.image||!((n=this.options)!=null&&n.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let i=e.toDataURL("image/png");this.options.onCrop(i),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(r){new Sa().open(r)};K();var Ki=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,i=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+i,this.applyFrameDrag(),this.updateDragCursor()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd),this.updateDragCursor())};this.options=e,this.currentPreset=Be(e.defaultDevice||fi.id),this.debugPanel=new Ot,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 n,a;let i=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=Be(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:i}),t.suppressCallback||(a=(n=this.options).onDeviceChange)==null||a.call(n,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark"),requestAnimationFrame(()=>this.updatePanelPositions())}setLayoutMode(e){if(this.layoutMode===e)return;this.layoutMode=e,this.container.classList.toggle("layout-fixed",e==="fixed"),this.container.classList.toggle("layout-draggable",e==="draggable"),Array.from(this.container.querySelectorAll("[data-layout-toggle]")).forEach(n=>n.classList.toggle("active",n.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(n=>{n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}updateDockState(){let e=this.container.querySelector("#bottom-dock");e==null||e.classList.remove("hidden");let t=this.container.querySelector("#console-messages"),i=this.container.querySelector("#dock-console-content");t&&i&&t.parentElement!==i&&i.appendChild(t)}makeBottomDockResizable(e,t){let i,n,a=o=>{let l=o.clientY-i,c=Math.max(100,Math.min(800,n-l));e.style.height=`${c}px`;let 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(),i=o.clientY,n=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",s),e.classList.add("resizing")})}makeSidebarResizable(e,t,i){let n,a,s=l=>{let c=i==="left"?l.clientX-n:n-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=i==="left"?`${p}px`:d.style.gridTemplateColumns.split(" ")[0]||"300px",m=i==="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(),n=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=`
|
|
2059
|
+
`,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=`
|
|
1964
2060
|
<div class="preview-toolbar">
|
|
1965
2061
|
<div class="preview-toolbar-left">
|
|
1966
2062
|
<span class="preview-logo">PREVIEWER</span>
|
|
@@ -1969,11 +2065,11 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
1969
2065
|
<div class="preview-toolbar-center">
|
|
1970
2066
|
<div class="device-selector-wrapper">
|
|
1971
2067
|
<select class="device-dropdown" id="device-select">
|
|
1972
|
-
${
|
|
1973
|
-
<optgroup label="${
|
|
1974
|
-
${
|
|
1975
|
-
<option value="${
|
|
1976
|
-
${
|
|
2068
|
+
${Vi.map(n=>`
|
|
2069
|
+
<optgroup label="${n.label}">
|
|
2070
|
+
${n.devices.map(i=>`
|
|
2071
|
+
<option value="${i.id}" ${i.id===this.currentPreset.id?"selected":""}>
|
|
2072
|
+
${i.label} (${i.width}\xD7${i.height})
|
|
1977
2073
|
</option>
|
|
1978
2074
|
`).join("")}
|
|
1979
2075
|
</optgroup>
|
|
@@ -2062,12 +2158,12 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
2062
2158
|
|
|
2063
2159
|
<div class="preview-stage hidden" data-preview-stage="compare">
|
|
2064
2160
|
<div class="compare-grid" data-compare-grid>
|
|
2065
|
-
${this.comparePresets.map(
|
|
2066
|
-
<div class="compare-viewport" data-viewport="${
|
|
2161
|
+
${this.comparePresets.map(n=>`
|
|
2162
|
+
<div class="compare-viewport" data-viewport="${n.id}">
|
|
2067
2163
|
<div class="compare-header">
|
|
2068
2164
|
<div class="compare-title">
|
|
2069
|
-
<span class="compare-title-text">${
|
|
2070
|
-
<span class="compare-meta">${
|
|
2165
|
+
<span class="compare-title-text">${n.label}</span>
|
|
2166
|
+
<span class="compare-meta">${n.ratio} | ${n.width}x${n.height}</span>
|
|
2071
2167
|
</div>
|
|
2072
2168
|
<button class="compare-focus" data-compare-focus type="button">Focus</button>
|
|
2073
2169
|
</div>
|
|
@@ -2130,7 +2226,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
2130
2226
|
</div>
|
|
2131
2227
|
|
|
2132
2228
|
</div>
|
|
2133
|
-
`,this.setupEventListeners(e),e}setupEventListeners(e){var g,m,f,h,b,y,v,S;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",x=>{if(this.viewMode==="compare")return;let w=x.target.value;this.setDevice(w)});let i=e.querySelector("#theme-select");i==null||i.addEventListener("change",x=>{let w=x.target.value;this.setTheme(w)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(x=>{x.addEventListener("click",()=>{let w=x.dataset.viewToggle;w&&this.setViewMode(w)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(x=>{x.addEventListener("click",()=>{let w=x.dataset.layoutToggle;w&&this.setLayoutMode(w)})}),(g=e.querySelector("#rotate-btn"))==null||g.addEventListener("click",()=>this.toggleRotation()),(m=e.querySelector("#zoom-in-btn"))==null||m.addEventListener("click",()=>this.adjustUserZoom(.1)),(f=e.querySelector("#zoom-out-btn"))==null||f.addEventListener("click",()=>this.adjustUserZoom(-.1)),(h=e.querySelector("#refresh-btn"))==null||h.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(x=>{x.addEventListener("click",()=>{let w=x.dataset.dockTab;if(!w)return;l.forEach(E=>E.classList.remove("active")),x.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(E=>{let _=E.dataset.dockPanel;E.classList.toggle("active",_===w)})})}),(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`,i=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=i,this.gameContainer.style.width=t,this.gameContainer.style.height=i,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=i,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=i,this.gameContainer.dataset.screenWidth=String(e.width),this.gameContainer.dataset.screenHeight=String(e.height),this.container.style.setProperty("--preview-screen-width",String(e.width)),this.container.style.setProperty("--preview-screen-height",String(e.height))}fitToScreen(e){if(!this.previewContainer)return;let t=this.getEffectivePreset(),i=this.getFitBounds(),n=Math.max(0,i.width),a=Math.max(0,i.height);if(n<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=n/t.width,o=a/t.height;if(this.autoScale=Math.max(.01,Math.min(s,o)),!this.hasInitialFit){this.hasInitialFit=!0;let l=.6;this.userScaleMultiplier=l/this.autoScale}e!=null&&e.keepVisibleScale&&e.keepVisibleScale>0&&(this.userScaleMultiplier=e.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),requestAnimationFrame(()=>this.updatePanelPositions()),this.emitScreenChange()}applyTransform(){let e=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${e})`;let t=this.container.querySelector("#zoom-label");t&&(t.textContent=`${Math.round(e*100)}%`),requestAnimationFrame(()=>this.updatePanelPositions())}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`,requestAnimationFrame(()=>this.updatePanelPositions())}updatePanelPositions(){if(!this.gameReady||this.viewMode==="compare")return;let e=this.container.querySelector('[data-panel="scene-tools-corner"]'),t=this.container.querySelector('[data-panel="nudge-panel"]');if(this.layoutMode==="fixed"){let i=this.container.querySelector(".preview-container");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}else{let i=this.container.querySelector(".preview-main");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}e&&(e.style.zIndex="100"),t&&(t.style.position="absolute",t.style.left="50%",t.style.top="16px",t.style.transform="translateX(calc(-50% + 200px))",t.style.zIndex="100")}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",e=>{let t=!this.gameContainer.contains(e.target);!this.isSpaceKeyPressed&&!t||e.button===0&&(e.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=e.clientX,this.frameDragStartY=e.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}setupSpaceKeyListener(){window.addEventListener("keydown",e=>{e.code==="Space"&&!this.isInputFocused()&&(this.isSpaceKeyPressed||(this.isSpaceKeyPressed=!0,this.updateDragCursor(),e.preventDefault()))}),window.addEventListener("keyup",e=>{e.code==="Space"&&(this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd())}),window.addEventListener("blur",()=>{this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd()})}isInputFocused(){let e=document.activeElement;if(!e)return!1;let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"||e.isContentEditable}setupShortcutListeners(){window.addEventListener("keydown",e=>{if(this.isInputFocused())return;let t=navigator.platform.toUpperCase().indexOf("MAC")>=0,i=e.ctrlKey||e.metaKey,n=e.shiftKey;if(i&&e.key==="s"&&!n){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(i&&e.key==="z"&&!n){e.preventDefault(),si();return}if(i&&(e.key==="z"&&n||e.key==="y"&&!n)){e.preventDefault(),oi();return}})}setupUnsavedChangesIndicator(){let e=this.container.querySelector("#preview-save-shortcut-text");e&&(e.textContent=`(${this.getShortcutKey()} + S)`),window.addEventListener("config:changed",()=>{this.updateUnsavedChangesIndicator()}),this.updateUnsavedChangesIndicator();let t=this.container.querySelector("#preview-save-btn");t==null||t.addEventListener("click",()=>{let i=document.querySelector("#apply-current-btn");i&&i.getAttribute("disabled")===null&&i.click()})}updateUnsavedChangesIndicator(){let t=Te().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let i=this.container.querySelector("#preview-unsaved-star"),n=this.container.querySelector("#preview-save-btn");i&&(i.style.display=t?"inline-block":"none"),n&&(n.style.display=t?"inline-flex":"none")}}updateDragCursor(){this.isSpaceKeyPressed?(this.frameDragger.style.cursor="grab",this.frameDragActive&&(this.frameDragger.style.cursor="grabbing")):this.frameDragger.style.cursor=""}adjustUserZoom(e){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+e)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var t,i;if(this.viewMode==="compare")return;let e=this.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:e}),(i=(t=this.options).onDeviceChange)==null||i.call(t,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let e=this.getEffectivePreset(),t={width:e.width,height:e.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:e.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:t})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let i=window.gameApp;if(!(i!=null&&i.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var i;let t=new WeakSet;try{return JSON.stringify(e,(n,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((i=e.constructor)!=null&&i.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...i)=>{let n=i.map(s=>typeof s=="object"?this.safeStringify(s):String(s)).join(" ");this.consoleMessages.push({type:t,message:n,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let a=this.container.querySelector("#console-badge");if(a){let s=this.consoleMessages.filter(o=>o.type==="error").length;a.textContent=s>0?`${s}!`:"0",a.classList.toggle("has-errors",s>0)}};console.log=(...t)=>{this.originalConsole.log(...t),e("log",...t)},console.warn=(...t)=>{this.originalConsole.warn(...t),e("warn",...t)},console.error=(...t)=>{this.originalConsole.error(...t),e("error",...t)},console.info=(...t)=>{this.originalConsole.info(...t),e("info",...t)}}appendConsoleMessage(e){let t=this.container.querySelector("#console-messages");if(!t)return;let i=document.createElement("div");i.className=`console-msg type-${e.type}`;let n=e.timestamp.toLocaleTimeString();i.innerHTML=`<span class="time">${this.escapeHtml(n)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(i),t.scrollTop=t.scrollHeight}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}toggleConsole(e){var t;if(this.layoutMode==="fixed"){let i=this.container.querySelector('[data-dock-tab="console"]');if(i){i.click();let n=this.container.querySelector("#bottom-dock");n==null||n.classList.remove("hidden")}return}this.isConsoleOpen=e!=null?e:!this.isConsoleOpen,(t=this.consolePanel)==null||t.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let e=this.container.querySelector("#console-messages");e&&(e.innerHTML="");let t=this.container.querySelector("#console-badge");t&&(t.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(t=>{let i=t.dataset.viewport;if(!i)return;let n=this.comparePresets.find(d=>d.id===i);if(!n)return;let a=t.querySelector("[data-compare-slot]"),s=t.querySelector("[data-compare-ghost]"),o=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),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(i);return}t.classList.contains("is-active")||this.activateCompareViewport(i)}),this.compareViewports.set(i,{preset:n,root:t,slot:a,ghost:s,wrapper:o,frame:l,canvas:c,focus: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 i=this.container.querySelector("#rotate-btn");if(i&&(i.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 i=this.autoScale*this.userScaleMultiplier,n=this.activeCompareId;n&&n!==e&&this.captureCompareSnapshot(n),this.activeCompareId=e,this.currentPreset=t.preset,this.isLandscape=!1,t.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,l)=>{o.root.classList.toggle("is-active",l===e),o.ghost.classList.toggle("hidden",l===e),o.focus&&(o.focus.textContent=l===e?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:i}),(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,i=`${t.width}px`,n=`${t.height}px`;e.frame.style.width=i,e.frame.style.height=n,e.canvas&&(e.canvas.width=t.width,e.canvas.height=t.height)})}fitCompareGhosts(){this.compareViewports.forEach(e=>{let t=e.root.querySelector(".compare-body");if(!t)return;let i=Math.max(0,t.clientWidth-24),n=Math.max(0,t.clientHeight-24);if(i<=0||n<=0)return;let a=i/e.preset.width,s=n/e.preset.height,o=Math.max(.01,Math.min(a,s));e.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let i=this.gameContainer.querySelector("canvas");if(!i)return;let n=t.canvas.getContext("2d");if(!n)return;let a=t.canvas.width,s=t.canvas.height,o=Math.min(a/i.width,s/i.height),l=i.width*o,c=i.height*o,p=(a-l)/2,d=(s-c)/2;n.clearRect(0,0,a,s),n.drawImage(i,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 Aa(r={}){let e=new Ki(r);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}K();function Ca(r){try{if(r&&typeof r.keys=="function")return Array.from(r.keys())}catch{}return[]}function As(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,i=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);r.eventMode=i?"static":"none",r.interactive=i,i&&(r.cursor=t.draggable?"move":"pointer")}function Cs(r,e){var l,c,p;if(!r||!e)return;let t=e.transform||{};pl(r,e);let i=t.position||{},n=t.offset||{},a=(typeof i.x=="number"?i.x:0)+(typeof n.x=="number"?n.x:0),s=(typeof i.y=="number"?i.y:0)+(typeof n.y=="number"?n.y:0);(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 Ts(r){if(typeof window=="undefined")return;let e=r==null?void 0:r.objects,t=Ca(e),i=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 n=new Map;t.forEach(a=>n.set(a,[a])),window.__editableObjectInstances=n,window.refreshEditableConfigIndex=()=>Ts(window.__editableConfig),window.getEditableObjectList=()=>{var a;return i(Ca((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return Ca((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 i=String(t||"").trim();return i?/^(data:|blob:|https?:)/.test(i)||i.startsWith("/")?i:`/${i.replace(/^\.\//,"")}`:""},e=async(t,i)=>{var a,s,o;let n=r(i);if(n)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(Ze(),xr))]),p=Date.now(),d=/^(data:|blob:)/.test(n)?n:n+(n.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,f=(s=m==null?void 0:m.get)==null?void 0:s.call(m,t);if(f){let h=((o=f.getDisplayObject)==null?void 0:o.call(f))||f.pixiObject||f.pixi||f;if(h!=null&&h.texture)h.texture=u;else if(h!=null&&h.children){let b=h.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 i=Y();Array.isArray(i)&&i.length&&(window.__editableConfig=t,Ce(i,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let i=Y();Array.isArray(i)&&i.length&&(window.__editableConfig=t,Ce(i,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let i=window.__editableConfig;if(!(i!=null&&i.engine))return;let n=[];if(t.runtime)for(let[a,s]of Object.entries(t.runtime))n.push({path:`runtime.${a}`,value:s});if(t.assets)for(let[a,s]of Object.entries(t.assets))n.push({path:`assets.${a}`,value:s}),typeof s=="string"&&e(a,s);if(t.splash)for(let[a,s]of Object.entries(t.splash))n.push({path:`splash.${a}`,value:s});if(t.loading)for(let[a,s]of Object.entries(t.loading))n.push({path:`loading.${a}`,value:s});if(t.start)for(let[a,s]of Object.entries(t.start))n.push({path:`start.${a}`,value:s});n.length&&Ce(n,{silent:!0,persist:!0,emitEvent:!0})}}function Xi(r){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:i}=r;t&&(t.onObjectRebuildRequired=async(a,s)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${a} due to type change...`);let o=t.get(a),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,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=As(d);Cs(u,s)}}catch(p){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",p)}});let n={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=As(l);Cs(u,s)}let c=[a];i==null||i(a,s,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,Ts(a))}};return n.rebuildIndexes(),n}K();var Is=Ye(require("lottie-web"),1);mn(hn);typeof window!="undefined"&&!window.lottie&&(window.lottie=Is.default);var at=null,gl=async()=>{if(!at){let r=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(r==null?void 0:r["handler.config"])||(r==null?void 0:r["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let i=atob(e.split(",")[1]);at=JSON.parse(i)}else at=JSON.parse(e);return at}catch(i){console.warn("[CONFIG] Failed to parse inline handler.config.json:",i)}at=await(await fetch("./handler.config.json")).json()}return at},Ia,zt,Ms,rt,La,ka;function hl(r){Ia=r.initGame,zt=r.CustomAssets,Ms=r.updateScreenState,rt=r.globalResponsiveMultipliers,La=r.layout,ka=r.clearResponsiveElements}var Ji="web_embed",Rt="https://example.com",Ls={profile_id:Ji},_e=null,ce=null,Ta={width:0,height:0},fl=!0,ml=async()=>{var c,p,d,u;document.title="Handler Pixi Game";let r=await gl();Ls={...r.ids||{},profile_id:Ji},Rt=r.destination_url||((p=(c=r.export_profiles)==null?void 0:c[Ji])==null?void 0:p.destination_url)||Rt,Oe.init({ids:Ls,profile:Ji,destinationUrl:Rt});let e=Oe.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),ce=Aa({onDeviceChange:m=>{console.log(`[PREVIEW] Device switched to ${m.width}x${m.height}, restarting game...`),ks()},onRefresh:ks});let g=ce.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",m=>{var v,S,x,w,P,E,_,R,C,A,k;let f=window.gameApp,h=window.gameObjectManager,{width:b,height:y}=m.detail;if(Ta.width=b,Ta.height=y,Ms(b,y),!(!f||!f.renderer)){h&&o(f,h);try{f.renderer.resize(b,y);let L=f.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&&h&&La)try{let L=(v=window.__mainContainer)!=null?v:f.stage,I=(_=(E=(w=window.__tutorialLabel)!=null?w:(x=(S=h.get("label_1"))==null?void 0:S.getDisplayObject)==null?void 0:x.call(S))!=null?E:(P=h.get("label_1"))==null?void 0:P.pixiObject)!=null?_:h.get("label_1"),M=h.get("background_1"),z=(k=(A=(C=window.__background)!=null?C:(R=M==null?void 0:M.getDisplayObject)==null?void 0:R.call(M))!=null?A:M==null?void 0:M.pixiObject)!=null?k:M;if(L){let T=L===f.stage;La({mainContainer:L,label:I,background:z,backgroundTexture:(z==null?void 0:z.texture)||null,app:f},t,0,Ta,h,{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 i=await Ia(e,t,Rt,ce);_e=i.app;let n=i.gameObjectManager;window.gameApp=_e,window.gameObjectManager=n;try{window.__liveEditBridge=Xi({getConfig:()=>window.__editableConfig,gameObjectManager:n,assets:zt})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}ce&&ce.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(rt.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(_e,n);async function s(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,S=await fetch(v,{cache:"no-cache"});if(!S.ok)return null;let x=await S.text();try{return JSON.parse(x)}catch{return null}},m=await g("configs/flow/app.flow.json");if(!m||typeof m!="object")return;let f=m.screens;if(!f||typeof f!="object")return;let h={},b={};for(let[y,v]of Object.entries(f)){let S=v==null?void 0:v.source;if(typeof S!="string")continue;let x=await g(S),w=x==null?void 0:x.elements;if(!Array.isArray(w))continue;let P=w.map(E=>E==null?void 0:E.instance_id).filter(E=>typeof E=="string");h[y]=P;for(let E of P)b[E]||(b[E]=y)}window.__HANDLER_APP_FLOW=m,window.__HANDLER_SCREEN_INDEX={screenToInstances:h,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: ${rt.scale.toFixed(3)}`),g.stage){let h=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((S,x)=>{if(S&&S.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(S&&S.scale){let w=S.scale.x||1,P=S.scale.y||1;S.__originalScale||(S.__originalScale={x:w,y:P},console.log(`${v}[RESPONSIVE] Stored original scale for child[${x}]: ${w.toFixed(3)}, ${P.toFixed(3)}`));let E=S.__originalScale.x*rt.scale,_=S.__originalScale.y*rt.scale;typeof S.scale.set=="function"?S.scale.set(E,_):(S.scale.x=E,S.scale.y=_),console.log(`${v}[RESPONSIVE] Child[${x}] scale: ${w.toFixed(3)}\u2192${S.scale.x.toFixed(3)} (type: ${S.constructor.name})`),h(S,y+1)}else S&&console.log(`${v}[RESPONSIVE] Child[${x}] has no scale (type: ${S.constructor.name})`)})};var f=h;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),h(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){rt.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let m=window.gameApp,f=window.gameObjectManager;m&&f?(o(m,f),m.renderer&&(m.renderer.render(m.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!m}) or gameObjectManager (${!!f}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,Oe.start()},ks=async()=>{var e,t,i,n;console.log("[PREVIEW] Restarting game in 1 seconds...");let r=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(r){let a=((t=r.getDisplayObject)==null?void 0:t.call(r))||r;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((i=a.scale.x)!=null?i:1).toFixed(3)}, y: ${((n=a.scale.y)!=null?n:1).toFixed(3)}`)}if(ce){ce.notifyGameDestroyed();try{ka&&ka()}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()),_e){try{_e.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}_e=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof zt.resetScene=="function"&&zt.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{ye("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=V(o)),Ia(a,o,Rt).then(l=>{_e=l.app,window.gameApp=_e,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=Xi({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:zt})}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)}};hi();K();var de={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},_s=1.25,Ps={fontFamily:"Inter, system-ui, sans-serif"};var Zi=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=`
|
|
2229
|
+
`,this.setupEventListeners(e),e}setupEventListeners(e){var g,m,f,h,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)),(f=e.querySelector("#zoom-out-btn"))==null||f.addEventListener("click",()=>this.adjustUserZoom(-.1)),(h=e.querySelector("#refresh-btn"))==null||h.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,f=(s=m==null?void 0:m.get)==null?void 0:s.call(m,t);if(f){let h=((o=f.getDisplayObject)==null?void 0:o.call(f))||f.pixiObject||f.pixi||f;if(h!=null&&h.texture)h.texture=u;else if(h!=null&&h.children){let b=h.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 f=window.gameApp,h=window.gameObjectManager,{width:b,height:y}=m.detail;if(ka.width=b,ka.height=y,Ps(b,y),!(!f||!f.renderer)){h&&o(f,h);try{f.renderer.resize(b,y);let L=f.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&&h&&Ia)try{let L=(v=window.__mainContainer)!=null?v:f.stage,_=(x=(w=(k=window.__tutorialLabel)!=null?k:(C=(S=h.get("label_1"))==null?void 0:S.getDisplayObject)==null?void 0:C.call(S))!=null?w:(z=h.get("label_1"))==null?void 0:z.pixiObject)!=null?x:h.get("label_1"),P=h.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===f.stage;Ia({mainContainer:L,label:_,background:R,backgroundTexture:(R==null?void 0:R.texture)||null,app:f},t,0,ka,h,{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 f=m.screens;if(!f||typeof f!="object")return;let h={},b={};for(let[y,v]of Object.entries(f)){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");h[y]=z;for(let w of z)b[w]||(b[w]=y)}window.__HANDLER_APP_FLOW=m,window.__HANDLER_SCREEN_INDEX={screenToInstances:h,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 h=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})`),h(S,y+1)}else S&&console.log(`${v}[RESPONSIVE] Child[${C}] has no scale (type: ${S.constructor.name})`)})};var f=h;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),h(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,f=window.gameObjectManager;m&&f?(o(m,f),m.renderer&&(m.renderer.render(m.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!m}) or gameObjectManager (${!!f}) 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=`
|
|
2134
2230
|
position: fixed;
|
|
2135
2231
|
inset: 0;
|
|
2136
2232
|
display: flex;
|
|
@@ -2146,14 +2242,14 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
2146
2242
|
display: flex;
|
|
2147
2243
|
flex-direction: column;
|
|
2148
2244
|
align-items: center;
|
|
2149
|
-
`;let
|
|
2245
|
+
`;let n=document.createElement("div");n.style.cssText=`
|
|
2150
2246
|
position: absolute;
|
|
2151
2247
|
top: -96px;
|
|
2152
2248
|
width: 96px;
|
|
2153
2249
|
height: 96px;
|
|
2154
2250
|
opacity: 0.9;
|
|
2155
2251
|
transform: scale(0.9);
|
|
2156
|
-
`,
|
|
2252
|
+
`,n.innerHTML='<div class="boxLoading"></div>',t.appendChild(n);let i=document.createElement("div");i.style.cssText=`
|
|
2157
2253
|
width: 100%;
|
|
2158
2254
|
position: relative;
|
|
2159
2255
|
display: flex;
|
|
@@ -2209,7 +2305,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
2209
2305
|
width: 1.5px;
|
|
2210
2306
|
background-color: black;
|
|
2211
2307
|
height: ${u%4===0?"6px":"2px"};
|
|
2212
|
-
`,c.appendChild(g)}
|
|
2308
|
+
`,c.appendChild(g)}i.appendChild(a),i.appendChild(o),i.appendChild(c);let p=document.createElement("div");return p.id="handler-load-centered",p.style.cssText=`
|
|
2213
2309
|
position: absolute;
|
|
2214
2310
|
top: 48px;
|
|
2215
2311
|
width: 600px;
|
|
@@ -2233,7 +2329,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
2233
2329
|
align-items: center;
|
|
2234
2330
|
justify-content: center;
|
|
2235
2331
|
animation-delay: ${[1.05,.875,.7,.525,.35,.175,0][g]}s;
|
|
2236
|
-
`,p.appendChild(m)}),t.appendChild(
|
|
2332
|
+
`,p.appendChild(m)}),t.appendChild(i),t.appendChild(p),this.authSeq=document.createElement("div"),this.authSeq.style.cssText=`
|
|
2237
2333
|
position: absolute;
|
|
2238
2334
|
bottom: 48px;
|
|
2239
2335
|
font-size: 8px;
|
|
@@ -2329,7 +2425,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
|
|
|
2329
2425
|
0%, 100% { opacity: 1; }
|
|
2330
2426
|
50% { opacity: 0.3; }
|
|
2331
2427
|
}
|
|
2332
|
-
`,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 Ma=Ja.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"]);Xa();var Hs={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"},Ns=Math.random().toString(36).slice(2),lt=null,st={...Hs},Fs="web_embed",Oa={},Dt,_a=!1,$t=!1,Nt=!1,Bs=!1,Da=1,en=0,an=!1,we=!1,ot="",ct=Math.floor(window.innerWidth),dt=Math.floor(window.innerHeight),Ra=ct>dt,xe=!1,Ht=!1,js=!1,Os=!1,Pa=!1,tn=null,Ge=null,za=!1,$a=!1,Qi=new Map;function Us(){if(!Ge)return null;let r=Date.now()-Ge;return!Number.isFinite(r)||r<0?null:r}function ja(r){if(za)return;let e=Us();e!==null&&(za=!0,$("session_time",{duration_ms:e,reason:r}))}function Rs(){if(lt)return lt;let r=document.createElement("div");return r.id="handler-root",r.setAttribute("data-handler-root","true"),document.body.appendChild(r),lt=r,r}function nn(r){switch(r){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return r}}function Gs(r,e){return{event_name:r,ts:Date.now(),session_id:Ns,deployment_id:st.deployment_id,variant_id:st.variant_id,export_profile_id:st.profile_id,instance_id:st.instance_id||"default",env:Fs==="mraid"?"mraid":"web",attribution:Dt,payload:e}}function $(r,e){let t=nn(r),i=Gs(t,e);pn(i,!!Oa.analytics),Vt(t,i),t!==r&&Vt(r,i)}function Ft(){tn&&(tn(ct,dt),tn=null)}function pt(r){Da=r,$("volume",r)}function ut(r){r&&(Bs=!0),!Nt&&(Nt=!0,$("pause"),pt(0))}function Bt(r){!r&&Bs||Nt&&(Nt=!1,$("resume"),pt(Da))}function Pe(r,e){ct=Math.floor(r||window.innerWidth),dt=Math.floor(e||window.innerHeight),Ra=ct>dt,$("resize",{width:ct,height:dt})}function yl(){if(cr())try{let r=mraid.getMaxSize();Pe(r.width,r.height);let e=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?Bt():ut()};if(mraid.addEventListener("viewableChange",e),mraid.addEventListener("stateChange",e),mraid.addEventListener("sizeChange",()=>{let t=mraid.getMaxSize();Pe(t.width,t.height)}),mraid.getAudioVolume){let t=mraid.getAudioVolume();pt(t?1:0)}if(mraid.addEventListener("audioVolumeChange",t=>{t!==null&&pt(t>0?1:0)}),mraid.addEventListener("error",(t,i)=>{console.warn("mraid error:",t,"action:",i)}),an=!0,mraid.isViewable()&&mraid.getState()!=="hidden")xe=!0,$("boot"),$("view"),$("ready"),we=!0,Ft();else{let t=()=>{xe=!0,$("boot"),$("view"),$("ready"),we=!0,Ft()};mraid.addEventListener("ready",t)}}catch(r){console.warn("MRAID hook skipped",r)}}function vl(){if(dr())try{let r=dapi.getScreenSize();Pe(r.width,r.height),dapi.addEventListener("viewableChange",t=>{t.isViewable?Bt():ut()}),dapi.addEventListener("adResized",t=>{let i=dapi.getScreenSize();Pe(t.width||i.width,t.height||i.height)});let e=dapi.getAudioVolume();if(pt(e?1:0),dapi.addEventListener("audioVolumeChange",t=>pt(t?1:0)),an=!0,dapi.isViewable())xe=!0,$("boot"),$("view"),$("ready"),we=!0,Ft();else{let t=()=>{xe=!0,$("boot"),$("view"),$("ready"),we=!0,Ft()};dapi.addEventListener("ready",t)}}catch(r){console.warn("DAPI hook skipped",r)}}function zs(){let r=()=>{xe||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(xe=!0,$("boot"),$("view"),$("ready"),we=!0,Ft(),Ht&&(Ht=!1,ae.start()))};window.addEventListener("resize",()=>Pe()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(Bt(),r()):ut()}),document.readyState==="complete"||document.readyState==="interactive"?r():window.addEventListener("load",r),an=!0}function wl(){let r=e=>{typeof TouchEvent!="undefined"&&e instanceof TouchEvent&&(js=!0),!(js&&e instanceof MouseEvent)&&(en+=1,$a||($a=!0,$("first_interaction",{count:en})),$("interaction",en))};document.addEventListener("mousedown",r),document.addEventListener("touchstart",r)}function $s(r){var i,n,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{(i=window.ExitApi)==null||i.exit();return}catch{}if(e==="mraid"&&typeof mraid!="undefined")mraid.open(r||"");else if(e==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(Je())(a=(n=window.TJ_API)==null?void 0:n.click)==null||a.call(n);else if(pr())(o=(s=window.FbPlayableAd)==null?void 0:s.onCTAClick)==null||o.call(s);else if(fr())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(hr())try{(d=(p=window.smxTracking)==null?void 0:p.redirect)==null||d.call(p)}catch(f){console.warn("Smadex redirect failed",f)}else if(ur()){let f=window.ExitApi;f&&typeof f.exit=="function"?f.exit(r||ot||""):r&&window.open(r)}else Xe()?(u=window.install)==null||u.call(window):gr()?(g=window.openAppStore)==null||g.call(window):un()?(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 i=new Image;i.src=t};if(r==="bigabid"){let t=window.BIGABID_BIDTIMEMACROS;if(!t)return;J("view",()=>e(t.mraid_viewable)),J("start",()=>e(t.game_viewable)),J("engagement",()=>e(t.engagement));let i=()=>e(t.complete);J("complete",i),qt("engagement",n=>{var a;((a=n==null?void 0:n.payload)==null?void 0:a.count)>3&&i()}),J("cta_click",()=>e(t.click))}else if(r==="inmobi"){let t=window.INMOBI_DSPMACROS;if(!t)return;J("view",()=>e(t.Ad_Load_Start)),J("start",()=>e(t.Ad_Viewable)),J("engagement",()=>e(t.First_Engagement)),J("complete",()=>e(t.Gameplay_Complete)),J("cta_click",()=>e(t.DSP_Click)),J("start",()=>{[5,10,15,20,25,30].forEach(i=>setTimeout(()=>e(t[`Spent_${i}_Seconds`]),i*1e3))})}}function El(){if(!Je())return;let r=window.TJ_API;r&&r.setPlayableAPI&&r.setPlayableAPI({skipAd:()=>{try{ae.finish()}catch(e){console.warn("Tapjoy skip failed",e)}}})}function Ds(){var e,t,i;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),(i=r==null?void 0:r.gameplayFinished)==null||i.call(r)}function Sl(){Xe()&&(window.mintGameStart=()=>{Bt(!0),Pe()},window.mintGameClose=()=>{ut(!0)})}function Al(){if(!gn())return;let r=window.NUC;!r||!r.trigger||(ae.on("cta_click",()=>{var e,t;return(t=(e=r.trigger).convert)==null?void 0:t.call(e,ot)}),ae.on("complete",()=>{var e,t;return(t=(e=r.trigger).tryAgain)==null?void 0:t.call(e)}))}var ae={init(r={},e){var t;if(Fs=r.profile||"web_embed",Oa=r.consent||{},st={...Hs,...r.ids||{}},lt=r.rootEl||lt,Dt=void 0,Ua((t=r.telemetry)!=null&&t.endpoint?r.telemetry:null),Ge=null,za=!1,$a=!1,Qi.clear(),ot=r.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),e&&(tn=e),$("init"),document.body.oncontextmenu=()=>!1,Rs(),Tl(lt),mr(),yl(),vl(),!an){if(document.readyState==="complete")zs();else if(!Os){Os=!0;let i=()=>{zs(),window.removeEventListener("load",i),document.removeEventListener("DOMContentLoaded",i)};window.addEventListener("load",i),document.addEventListener("DOMContentLoaded",i)}}wl(),xl(),El(),Sl(),Al(),console.log(`%c @handler/playable-sdk %c v${Ma} `,"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"),Ht&&(Ht=!1,ae.start()),we=!0),we=xe},getRoot(){return Rs()},get version(){return Ma},get maxWidth(){return ct},get maxHeight(){return dt},get isLandscape(){return Ra},get isReady(){return we},get isStarted(){return _a},get isPaused(){return Nt},get isFinished(){return $t},get volume(){return Da},get interactions(){return en},on(r,e){qt(nn(r),e)},off(r,e){dn(nn(r),e)},start(){var r,e;if(!_a){if(!xe){Ht=!0;return}if(_a=!0,Ge||(Ge=Date.now()),$("start"),Pe(),Xe())ut(),(r=window.gameReady)==null||r.call(window);else if(Je()){let t=window.TJ_API;(e=t==null?void 0:t.setPlayableBuild)==null||e.call(t,{orientation:Ra?"landscape":"portrait",buildID:Ma})}}},finish(){var r,e;$t||($t=!0,$("complete"),ja("complete"),Xe()?(r=window.gameEnd)==null||r.call(window):un()?(e=parent==null?void 0:parent.postMessage)==null||e.call(parent,"complete","*"):Je()&&Ds())},install(r){if(!$t){$t=!0,Je()?(Ds(),setTimeout(()=>ae.install(r),300)):($("complete"),setTimeout(()=>ae.install(r),0));return}Pa||(Pa=!0,setTimeout(()=>Pa=!1,500),$("cta_click"),$("conversion"),ja("cta"),$s(r||ot))},emit(r,e){let t=nn(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 i=Gs(t,e);pn(i,!!Oa.analytics),Vt(t,i)},gameStart(){ae.start()},gameEnd(){ae.finish()},ctaClick(r,e){$("cta_click",{url:r||ot,manual:!0}),(e==null?void 0:e.open)!==!1&&$s(r||ot)},ctaShow(r){$("cta_show",r)},ctaDismiss(r){$("cta_dismiss",r)},getGameTimeMs(){return Us()},endSession(r="manual"){ja(r)},setAttribution(r){Dt=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(`${Ns}:${r}`))%e.length,i=e[t];return Dt={...Dt||{},experiment_id:r},st.variant_id=i,$("ab_assign",{experiment_id:r,variant_id:i}),i},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&&Qi.set(r,Date.now())},timerEnd(r,e="custom",t){if(!r)return;let i=Qi.get(r);if(!i)return;Qi.delete(r);let n=Date.now()-i;if(!(!Number.isFinite(n)||n<0)){if(e==="custom"){$("engagement",{action:"timer",key:r,duration_ms:n,...t});return}$(e,{key:r,duration_ms:n,...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(Xe())(r=window.gameRetry)==null||r.call(window);else if(gn()){let i=window.NUC;(t=(e=i==null?void 0:i.trigger)==null?void 0:e.tryAgain)==null||t.call(e)}$("engagement",{action:"retry"})},pause(){ut(!0)},resume(){Bt(!0)},resize(r,e){Pe(r,e)}},Oe=ae;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=`
|
|
2428
|
+
`,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(f){console.warn("Smadex redirect failed",f)}else if(gr()){let f=window.ExitApi;f&&typeof f.exit=="function"?f.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=`
|
|
2333
2429
|
(function(){
|
|
2334
2430
|
var events = ['touchstart','touchend','mousedown','keydown'];
|
|
2335
2431
|
function unlock(){
|