@mirage-engine/core 0.3.4 → 0.3.6

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.
@@ -1,5 +1,5 @@
1
- (function(b,T){typeof exports=="object"&&typeof module!="undefined"?T(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],T):(b=typeof globalThis!="undefined"?globalThis:b||self,T(b.MirageEngine={},b.THREE))})(this,function(b,T){"use strict";var at=Object.defineProperty,ct=Object.defineProperties;var lt=Object.getOwnPropertyDescriptors;var Ue=Object.getOwnPropertySymbols;var ht=Object.prototype.hasOwnProperty,dt=Object.prototype.propertyIsEnumerable;var pe=(b,T,S)=>T in b?at(b,T,{enumerable:!0,configurable:!0,writable:!0,value:S}):b[T]=S,Z=(b,T)=>{for(var S in T||(T={}))ht.call(T,S)&&pe(b,S,T[S]);if(Ue)for(var S of Ue(T))dt.call(T,S)&&pe(b,S,T[S]);return b},_e=(b,T)=>ct(b,lt(T));var g=(b,T,S)=>(pe(b,typeof T!="symbol"?T+"":T,S),S);var Be=(b,T,S)=>new Promise((v,te)=>{var N=R=>{try{L(S.next(R))}catch(O){te(O)}},re=R=>{try{L(S.throw(R))}catch(O){te(O)}},L=R=>R.done?v(R.value):Promise.resolve(R.value).then(N,re);L((S=S.apply(b,T)).next())});function S(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const v=S(T),te={INCLUDE_TREE:"include-tree",EXCLUDE_TREE:"exclude-tree",INCLUDE_SELF:"include-self",EXCLUDE_SELF:"exclude-self",END:"end"},N={NAME:"data-mirage-dom",KEY:"mirageDom",VALUES:{HIDE:"hide",SHOW:"show"}},re={TRAVELER:"traveler",NATIVE:"native",CAPTURE_1:"1",CAPTURE_2:"2",CAPTURE_3:"3",CAPTURE_4:"4",CAPTURE_5:"5"},L={NAME:"data-mirage-travel",KEY:"mirageTravel",VALUES:re,MAX_LAYERS:Object.keys(re).length-1},R={NAME:"data-mirage-filter",KEY:"mirageFilter",VALUES:te},O={NAME:"data-mirage-select",KEY:"mirageSelect",VALUES:te},me={NAME:"data-mirage-shader",KEY:"mirageShader"},Fe={NAME:"data-mirage-sandwich",KEY:"mirageSandwich",VALUES:{FRONT:"front"}},ie=0,$=1,Q=2,ve=4,se=8,ae=16;function Ne(s){const e=s.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return e?{r:parseInt(e[1])/255,g:parseInt(e[2])/255,b:parseInt(e[3])/255}:{r:1,g:1,b:1}}function ye(s){const e={};if(s.opacity&&(e.opacity=parseFloat(s.opacity)),s.backgroundColor&&s.backgroundColor!=="rgba(0, 0, 0, 0)"){const t=Ne(s.backgroundColor);e.backgroundColor=[t.r,t.g,t.b]}if(s.backgroundImage?e.backgroundImage=s.backgroundImage:s.background&&(e.backgroundImage=s.background),s.borderRadius&&(e.borderRadius=parseFloat(s.borderRadius)),s.width&&(e.width=parseFloat(s.width)),s.height&&(e.height=parseFloat(s.height)),s.transform&&s.transform!=="none"){const t=new DOMMatrix(s.transform);e.x=t.m41,e.y=t.m42,e.z=t.m43}return e}class be{constructor(e,t){g(this,"target");g(this,"observer");g(this,"pendingDeletions",new Set);g(this,"pendingStyles",new Map);g(this,"isDomDirty",!1);g(this,"isRunning",!1);g(this,"pendingMask",ie);g(this,"mutationTimer",null);g(this,"cssTimer",null);g(this,"resizeConfig");g(this,"resizeTimer",null);g(this,"isResizing",!1);g(this,"lastScrollX",0);g(this,"lastScrollY",0);g(this,"scrollTimer",null);g(this,"onBeforeRender",new Set);g(this,"onLayoutChange",new Set);g(this,"onStyleChange",new Set);g(this,"onScrollChange",new Set);g(this,"onRender",new Set);g(this,"onTransitionFinished",e=>{this.target.contains(e.target)&&this.mutationTimer===null&&(this.cssTimer&&clearTimeout(this.cssTimer),this.pendingStyles.size==0&&(this.pendingMask|=$|Q,this.cssTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.cssTimer=null},50)))});g(this,"onWindowResize",()=>{if(!this.resizeConfig.enabled){this.isDomDirty=!0;return}this.isResizing||(this.isResizing=!0,this.resizeConfig.onStart&&this.resizeConfig.onStart()),this.resizeTimer&&clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.resizeConfig.onEnd&&this.resizeConfig.onEnd(),this.isResizing=!1,this.resizeTimer=null},this.resizeConfig.delay)});g(this,"renderLoop",()=>{if(!this.isRunning)return;this.onBeforeRender.forEach(r=>r()),this.isDomDirty&&(this.isDomDirty=!1,this.onLayoutChange.forEach(r=>r(this.pendingMask,this.pendingDeletions)),this.pendingDeletions.clear(),this.pendingMask=ie);const e=window.scrollX,t=window.scrollY;(e!==this.lastScrollX||t!==this.lastScrollY)&&(this.onScrollChange.forEach(r=>r(e,t)),this.lastScrollX=e,this.lastScrollY=t,this.scrollTimer&&clearTimeout(this.scrollTimer),this.scrollTimer=window.setTimeout(()=>{this.pendingMask|=$,this.isDomDirty=!0,this.scrollTimer=null},150)),this.pendingStyles.size>0&&(this.onStyleChange.forEach(r=>r(this.pendingStyles)),this.pendingStyles.clear()),this.onRender.forEach(r=>r()),requestAnimationFrame(this.renderLoop)});var i,o;this.target=e;const r=(i=t.resizeDebounce)!=null?i:!0;r===!1?this.resizeConfig={enabled:!1,delay:0}:r===!0?this.resizeConfig={enabled:!0,delay:150}:this.resizeConfig={enabled:!0,delay:(o=r.delay)!=null?o:150,onStart:r.onStart,onEnd:r.onEnd},this.observer=new MutationObserver(n=>{let a=ie;for(const l of n)if(l.type==="childList")a|=se,l.removedNodes.length>0&&l.removedNodes.forEach(c=>{c instanceof HTMLElement&&this.pendingDeletions.add(c)});else if(l.type==="attributes")if(l.attributeName==="style"){a|=$|Q;const c=l.target,d=ye(c.style);this.pendingStyles.set(c,d)}else l.attributeName==="class"?a|=$|Q:l.attributeName&&l.attributeName.startsWith("data-")&&(a|=$|Q,l.attributeName.startsWith("data-mirage")&&(a|=se));else l.type==="characterData"&&(a|=ae|$);if(a!==ie){if(this.pendingMask|=a,a&se){this.clearTimers(),this.isDomDirty=!0;return}this.mutationTimer&&clearTimeout(this.mutationTimer),this.mutationTimer=window.setTimeout(()=>{this.mutationTimer=null,this.isDomDirty=!0},200)}})}start(){this.isRunning||(this.isRunning=!0,this.observer.observe(this.target,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),this.target.addEventListener("transitionend",this.onTransitionFinished),this.target.addEventListener("animationend",this.onTransitionFinished),window.addEventListener("resize",this.onWindowResize),this.isDomDirty=!0,this.lastScrollX=window.scrollX,this.lastScrollY=window.scrollY,this.renderLoop())}stop(){this.isRunning=!1,this.observer.disconnect(),this.clearTimers(),this.target.removeEventListener("transitionend",this.onTransitionFinished),this.target.removeEventListener("animationend",this.onTransitionFinished),window.removeEventListener("resize",this.onWindowResize)}clearTimers(){this.mutationTimer&&(clearTimeout(this.mutationTimer),this.mutationTimer=null),this.cssTimer&&(clearTimeout(this.cssTimer),this.cssTimer=null),this.scrollTimer&&(clearTimeout(this.scrollTimer),this.scrollTimer=null)}}const X=1,j=2,Xe=0,A={BASE:0,SELECTED:1,getCaptureLayer:s=>31-s,HIDDEN:31},le=Object.values(R.VALUES);class Ee{static getBaseline(e){if(this.cache.has(e))return this.cache.get(e);const t=this.calculateBaselineFromDOM(e);return this.cache.set(e,t),t}static calculateBaselineFromDOM(e){if(typeof document=="undefined")return 0;const t=document.createElement("div"),r=document.createElement("span"),i=document.createElement("img");t.style.visibility="hidden",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.font=e,t.style.margin="0",t.style.padding="0",t.style.border="none",r.style.margin="0",r.style.padding="0",r.style.border="none",r.style.lineHeight="normal",i.width=1,i.height=1,i.style.verticalAlign="baseline",r.appendChild(document.createTextNode("Hidden Text")),t.appendChild(r),t.appendChild(i),document.body.appendChild(t);const o=i.offsetTop-r.offsetTop;return document.body.removeChild(t),o}}g(Ee,"cache",new Map);class ze extends v.MeshBasicMaterial{constructor(t,r,i,o,n=2){super({transparent:!0,side:v.FrontSide,color:16777215});g(this,"canvas");g(this,"ctx");g(this,"qualityFactor");if(this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),!this.ctx)throw new Error("[Mirage] Failed to create canvas context");this.qualityFactor=n,this.map=new v.CanvasTexture(this.canvas),this.map.colorSpace=v.LinearSRGBColorSpace,this.map.minFilter=v.LinearFilter,this.map.magFilter=v.LinearFilter,this.updateText(t,r,i,o)}wrapText(t,r){const i=t.split(`
2
- `),o=[];return i.forEach(n=>{const a=n.match(/[^\s\-]+\-?|\-|\s+/g)||[];if(a.length===0){o.push("");return}let l=a[0];for(let c=1;c<a.length;c++){const d=a[c];this.ctx.measureText(l+d).width<=r+2?l+=d:(l&&o.push(l),l=d.trimStart())}l&&o.push(l)}),o}updateText(t,r,i,o,n){n!==void 0&&(this.qualityFactor=n);const l=(window.devicePixelRatio||1)*this.qualityFactor,c=i*l,d=o*l;this.canvas.width!==c||this.canvas.height!==d?(this.canvas.width=c,this.canvas.height=d):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.setTransform(l,0,0,l,0,0),this.ctx.font=r.font,this.ctx.fillStyle=r.color,this.ctx.textBaseline="alphabetic",this.ctx.globalAlpha=1;const h=this.wrapText(t,i),u=r.lineHeight,p=Ee.getBaseline(r.font);h.forEach((f,m)=>{const C=m*u+p;let k=0;r.textAlign==="center"?k=i/2:r.textAlign==="right"&&(k=i),this.ctx.textAlign=r.textAlign,this.ctx.fillText(f,k,C)}),this.map&&(this.map.needsUpdate=!0)}dispose(){this.map&&this.map.dispose(),super.dispose()}}function ee(s){return typeof s=="number"?s:parseFloat(s)||0}function ne(s){if(!s||s==="transparent")return{color:new v.Color(16777215),alpha:0};const e=s.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);if(e){const t=parseInt(e[1],10),r=parseInt(e[2],10),i=parseInt(e[3],10),o=e[4]!==void 0?parseFloat(e[4]):1;return{color:new v.Color(`rgb(${t}, ${r}, ${i})`),alpha:o}}return{color:new v.Color(s),alpha:1}}function Ye(s){const e=[];let t="",r=0;for(let i=0;i<s.length;i++){const o=s[i];if(o==="(")r++;else if(o===")")r--;else if(o===","&&r===0){e.push(t.trim()),t="";continue}t+=o}return t&&e.push(t.trim()),e}function Ve(s){if(!s||typeof s!="string"||!s.includes("linear-gradient"))return null;const e=s.match(/linear-gradient\((.*)\)/);if(!e)return null;const t=e[1],r=Ye(t);let i=Math.PI,o=0;const n=r[0].trim();if(n.startsWith("to "))n==="to top"?i=0:n==="to right"?i=Math.PI/2:n==="to bottom"?i=Math.PI:n==="to left"?i=Math.PI*1.5:n==="to top right"||n==="to right top"?i=Math.PI/4:n==="to bottom right"||n==="to right bottom"?i=Math.PI*.75:n==="to bottom left"||n==="to left bottom"?i=Math.PI*1.25:(n==="to top left"||n==="to left top")&&(i=Math.PI*1.75),o=1;else if(n.endsWith("deg")||n.endsWith("rad")||n.endsWith("turn")){const l=parseFloat(n);n.endsWith("deg")?i=l*(Math.PI/180):n.endsWith("rad")?i=l:n.endsWith("turn")&&(i=l*Math.PI*2),o=1}const a=[];for(let l=o;l<r.length&&!(a.length>=8);l++){const c=r[l].trim(),d=c.lastIndexOf(" ");let h=c,u=null;if(d!==-1&&!c.endsWith(")")){const f=c.substring(d+1);(f.endsWith("%")||f.endsWith("px")||!isNaN(parseFloat(f)))&&(h=c.substring(0,d).trim(),u=f)}const p=ne(h);a.push({color:p.color,alpha:p.alpha,rawStop:u,stop:0})}if(a.length>0){for(let c=0;c<a.length;c++)a[c].rawStop!==null&&(a[c].stop=parseFloat(a[c].rawStop)/100);a[0].rawStop===null&&(a[0].stop=0),a.length>1&&a[a.length-1].rawStop===null&&(a[a.length-1].stop=1);let l=0;for(let c=1;c<a.length;c++)if(a[c].rawStop!==null||c===a.length-1){const d=c-l;if(d>1){const h=a[l].stop,p=(a[c].stop-h)/d;for(let f=1;f<d;f++)a[l+f].stop=h+p*f}l=c}}return{angle:i,stops:a}}const We=`varying vec2 vUv;
1
+ (function(y,T){typeof exports=="object"&&typeof module!="undefined"?T(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],T):(y=typeof globalThis!="undefined"?globalThis:y||self,T(y.MirageEngine={},y.THREE))})(this,function(y,T){"use strict";var at=Object.defineProperty,ct=Object.defineProperties;var lt=Object.getOwnPropertyDescriptors;var Oe=Object.getOwnPropertySymbols;var ht=Object.prototype.hasOwnProperty,dt=Object.prototype.propertyIsEnumerable;var pe=(y,T,S)=>T in y?at(y,T,{enumerable:!0,configurable:!0,writable:!0,value:S}):y[T]=S,Z=(y,T)=>{for(var S in T||(T={}))ht.call(T,S)&&pe(y,S,T[S]);if(Oe)for(var S of Oe(T))dt.call(T,S)&&pe(y,S,T[S]);return y},_e=(y,T)=>ct(y,lt(T));var g=(y,T,S)=>(pe(y,typeof T!="symbol"?T+"":T,S),S);var Be=(y,T,S)=>new Promise((v,te)=>{var N=R=>{try{L(S.next(R))}catch(U){te(U)}},re=R=>{try{L(S.throw(R))}catch(U){te(U)}},L=R=>R.done?v(R.value):Promise.resolve(R.value).then(N,re);L((S=S.apply(y,T)).next())});function S(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const v=S(T),te={INCLUDE_TREE:"include-tree",EXCLUDE_TREE:"exclude-tree",INCLUDE_SELF:"include-self",EXCLUDE_SELF:"exclude-self",END:"end"},N={NAME:"data-mirage-dom",KEY:"mirageDom",VALUES:{HIDE:"hide",SHOW:"show"}},re={TRAVELER:"traveler",NATIVE:"native",CAPTURE_1:"1",CAPTURE_2:"2",CAPTURE_3:"3",CAPTURE_4:"4",CAPTURE_5:"5"},L={NAME:"data-mirage-travel",KEY:"mirageTravel",VALUES:re,MAX_LAYERS:Object.keys(re).length-1},R={NAME:"data-mirage-filter",KEY:"mirageFilter",VALUES:te},U={NAME:"data-mirage-select",KEY:"mirageSelect",VALUES:te},me={NAME:"data-mirage-shader",KEY:"mirageShader"},Fe={NAME:"data-mirage-sandwich",KEY:"mirageSandwich",VALUES:{FRONT:"front"}},ie=0,$=1,Q=2,ve=4,se=8,ae=16;function Ne(s){const e=s.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return e?{r:parseInt(e[1])/255,g:parseInt(e[2])/255,b:parseInt(e[3])/255}:{r:1,g:1,b:1}}function be(s){const e={};if(s.opacity&&(e.opacity=parseFloat(s.opacity)),s.backgroundColor&&s.backgroundColor!=="rgba(0, 0, 0, 0)"){const t=Ne(s.backgroundColor);e.backgroundColor=[t.r,t.g,t.b]}if(s.backgroundImage?e.backgroundImage=s.backgroundImage:s.background&&(e.backgroundImage=s.background),s.borderRadius&&(e.borderRadius=parseFloat(s.borderRadius)),s.width&&(e.width=parseFloat(s.width)),s.height&&(e.height=parseFloat(s.height)),s.transform&&s.transform!=="none"){const t=new DOMMatrix(s.transform);e.x=t.m41,e.y=t.m42,e.z=t.m43}return e}class ye{constructor(e,t){g(this,"target");g(this,"observer");g(this,"pendingDeletions",new Set);g(this,"pendingStyles",new Map);g(this,"isDomDirty",!1);g(this,"isRunning",!1);g(this,"pendingMask",ie);g(this,"mutationTimer",null);g(this,"cssTimer",null);g(this,"resizeConfig");g(this,"resizeTimer",null);g(this,"isResizing",!1);g(this,"lastScrollX",0);g(this,"lastScrollY",0);g(this,"scrollTimer",null);g(this,"onBeforeRender",new Set);g(this,"onLayoutChange",new Set);g(this,"onStyleChange",new Set);g(this,"onScrollChange",new Set);g(this,"onRender",new Set);g(this,"onTransitionFinished",e=>{this.target.contains(e.target)&&this.mutationTimer===null&&(this.cssTimer&&clearTimeout(this.cssTimer),this.pendingStyles.size==0&&(this.pendingMask|=$|Q,this.cssTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.cssTimer=null},50)))});g(this,"onWindowResize",()=>{if(!this.resizeConfig.enabled){this.isDomDirty=!0;return}this.isResizing||(this.isResizing=!0,this.resizeConfig.onStart&&this.resizeConfig.onStart()),this.resizeTimer&&clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.resizeConfig.onEnd&&this.resizeConfig.onEnd(),this.isResizing=!1,this.resizeTimer=null},this.resizeConfig.delay)});g(this,"renderLoop",()=>{if(!this.isRunning)return;this.onBeforeRender.forEach(r=>r()),this.isDomDirty&&(this.isDomDirty=!1,this.onLayoutChange.forEach(r=>r(this.pendingMask,this.pendingDeletions)),this.pendingDeletions.clear(),this.pendingMask=ie);const e=window.scrollX,t=window.scrollY;(e!==this.lastScrollX||t!==this.lastScrollY)&&(this.onScrollChange.forEach(r=>r(e,t)),this.lastScrollX=e,this.lastScrollY=t,this.scrollTimer&&clearTimeout(this.scrollTimer),this.scrollTimer=window.setTimeout(()=>{this.pendingMask|=$,this.isDomDirty=!0,this.scrollTimer=null},150)),this.pendingStyles.size>0&&(this.onStyleChange.forEach(r=>r(this.pendingStyles)),this.pendingStyles.clear()),this.onRender.forEach(r=>r()),requestAnimationFrame(this.renderLoop)});var i,a;this.target=e;const r=(i=t.resizeDebounce)!=null?i:!0;r===!1?this.resizeConfig={enabled:!1,delay:0}:r===!0?this.resizeConfig={enabled:!0,delay:150}:this.resizeConfig={enabled:!0,delay:(a=r.delay)!=null?a:150,onStart:r.onStart,onEnd:r.onEnd},this.observer=new MutationObserver(n=>{let o=ie;for(const l of n)if(l.type==="childList")o|=se,l.removedNodes.length>0&&l.removedNodes.forEach(c=>{c instanceof HTMLElement&&this.pendingDeletions.add(c)});else if(l.type==="attributes")if(l.attributeName==="style"){o|=$|Q;const c=l.target,d=be(c.style);this.pendingStyles.set(c,d)}else l.attributeName==="class"?o|=$|Q:l.attributeName&&l.attributeName.startsWith("data-")&&(o|=$|Q,l.attributeName.startsWith("data-mirage")&&(o|=se));else l.type==="characterData"&&(o|=ae|$);if(o!==ie){if(this.pendingMask|=o,o&se){this.clearTimers(),this.isDomDirty=!0;return}this.mutationTimer&&clearTimeout(this.mutationTimer),this.mutationTimer=window.setTimeout(()=>{this.mutationTimer=null,this.isDomDirty=!0},200)}})}start(){this.isRunning||(this.isRunning=!0,this.observer.observe(this.target,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),this.target.addEventListener("transitionend",this.onTransitionFinished),this.target.addEventListener("animationend",this.onTransitionFinished),window.addEventListener("resize",this.onWindowResize),this.isDomDirty=!0,this.lastScrollX=window.scrollX,this.lastScrollY=window.scrollY,this.renderLoop())}stop(){this.isRunning=!1,this.observer.disconnect(),this.clearTimers(),this.target.removeEventListener("transitionend",this.onTransitionFinished),this.target.removeEventListener("animationend",this.onTransitionFinished),window.removeEventListener("resize",this.onWindowResize)}clearTimers(){this.mutationTimer&&(clearTimeout(this.mutationTimer),this.mutationTimer=null),this.cssTimer&&(clearTimeout(this.cssTimer),this.cssTimer=null),this.scrollTimer&&(clearTimeout(this.scrollTimer),this.scrollTimer=null)}}const X=1,j=2,Xe=0,D={BASE:0,SELECTED:1,getCaptureLayer:s=>31-s,HIDDEN:31},le=Object.values(R.VALUES);class Ee{static getBaseline(e){if(this.cache.has(e))return this.cache.get(e);const t=this.calculateBaselineFromDOM(e);return this.cache.set(e,t),t}static calculateBaselineFromDOM(e){if(typeof document=="undefined")return 0;const t=document.createElement("div"),r=document.createElement("span"),i=document.createElement("img");t.style.visibility="hidden",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.font=e,t.style.margin="0",t.style.padding="0",t.style.border="none",r.style.margin="0",r.style.padding="0",r.style.border="none",r.style.lineHeight="normal",i.width=1,i.height=1,i.style.verticalAlign="baseline",r.appendChild(document.createTextNode("Hidden Text")),t.appendChild(r),t.appendChild(i),document.body.appendChild(t);const a=i.offsetTop-r.offsetTop;return document.body.removeChild(t),a}}g(Ee,"cache",new Map);class ze extends v.MeshBasicMaterial{constructor(t,r,i,a,n=2){super({transparent:!0,side:v.FrontSide,color:16777215});g(this,"canvas");g(this,"ctx");g(this,"qualityFactor");if(this.canvas=document.createElement("canvas"),this.ctx=this.canvas.getContext("2d"),!this.ctx)throw new Error("[Mirage] Failed to create canvas context");this.qualityFactor=n,this.map=new v.CanvasTexture(this.canvas),this.map.colorSpace=v.LinearSRGBColorSpace,this.map.minFilter=v.LinearFilter,this.map.magFilter=v.LinearFilter,this.updateText(t,r,i,a)}wrapText(t,r){const i=t.split(`
2
+ `),a=[];return i.forEach(n=>{const o=n.match(/[^\s\-]+\-?|\-|\s+/g)||[];if(o.length===0){a.push("");return}let l=o[0];for(let c=1;c<o.length;c++){const d=o[c];this.ctx.measureText(l+d).width<=r+2?l+=d:(l&&a.push(l),l=d.trimStart())}l&&a.push(l)}),a}updateText(t,r,i,a,n){n!==void 0&&(this.qualityFactor=n);const l=(window.devicePixelRatio||1)*this.qualityFactor,c=i*l,d=a*l;this.canvas.width!==c||this.canvas.height!==d?(this.canvas.width=c,this.canvas.height=d):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.setTransform(l,0,0,l,0,0),this.ctx.font=r.font,this.ctx.fillStyle=r.color,this.ctx.textBaseline="alphabetic",this.ctx.globalAlpha=1;const h=this.wrapText(t,i),u=r.lineHeight,p=Ee.getBaseline(r.font);h.forEach((f,m)=>{const C=m*u+p;let k=0;r.textAlign==="center"?k=i/2:r.textAlign==="right"&&(k=i),this.ctx.textAlign=r.textAlign,this.ctx.fillText(f,k,C)}),this.map&&(this.map.needsUpdate=!0)}dispose(){this.map&&this.map.dispose(),super.dispose()}}function ee(s){return typeof s=="number"?s:parseFloat(s)||0}function ne(s){if(!s||s==="transparent")return{color:new v.Color(16777215),alpha:0};const e=s.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);if(e){const t=parseInt(e[1],10),r=parseInt(e[2],10),i=parseInt(e[3],10),a=e[4]!==void 0?parseFloat(e[4]):1;return{color:new v.Color(`rgb(${t}, ${r}, ${i})`),alpha:a}}return{color:new v.Color(s),alpha:1}}function Ye(s){const e=[];let t="",r=0;for(let i=0;i<s.length;i++){const a=s[i];if(a==="(")r++;else if(a===")")r--;else if(a===","&&r===0){e.push(t.trim()),t="";continue}t+=a}return t&&e.push(t.trim()),e}function Ve(s){if(!s||typeof s!="string"||!s.includes("linear-gradient"))return null;const e=s.match(/linear-gradient\((.*)\)/);if(!e)return null;const t=e[1],r=Ye(t);let i=Math.PI,a=0;const n=r[0].trim();if(n.startsWith("to "))n==="to top"?i=0:n==="to right"?i=Math.PI/2:n==="to bottom"?i=Math.PI:n==="to left"?i=Math.PI*1.5:n==="to top right"||n==="to right top"?i=Math.PI/4:n==="to bottom right"||n==="to right bottom"?i=Math.PI*.75:n==="to bottom left"||n==="to left bottom"?i=Math.PI*1.25:(n==="to top left"||n==="to left top")&&(i=Math.PI*1.75),a=1;else if(n.endsWith("deg")||n.endsWith("rad")||n.endsWith("turn")){const l=parseFloat(n);n.endsWith("deg")?i=l*(Math.PI/180):n.endsWith("rad")?i=l:n.endsWith("turn")&&(i=l*Math.PI*2),a=1}const o=[];for(let l=a;l<r.length&&!(o.length>=8);l++){const c=r[l].trim(),d=c.lastIndexOf(" ");let h=c,u=null;if(d!==-1&&!c.endsWith(")")){const f=c.substring(d+1);(f.endsWith("%")||f.endsWith("px")||!isNaN(parseFloat(f)))&&(h=c.substring(0,d).trim(),u=f)}const p=ne(h);o.push({color:p.color,alpha:p.alpha,rawStop:u,stop:0})}if(o.length>0){for(let c=0;c<o.length;c++)o[c].rawStop!==null&&(o[c].stop=parseFloat(o[c].rawStop)/100);o[0].rawStop===null&&(o[0].stop=0),o.length>1&&o[o.length-1].rawStop===null&&(o[o.length-1].stop=1);let l=0;for(let c=1;c<o.length;c++)if(o[c].rawStop!==null||c===o.length-1){const d=c-l;if(d>1){const h=o[l].stop,p=(o[c].stop-h)/d;for(let f=1;f<d;f++)o[l+f].stop=h+p*f}l=c}}return{angle:i,stops:o}}const We=`varying vec2 vUv;
3
3
  varying vec4 vScreenPos;
4
4
  void main() {
5
5
  vUv = uv;
@@ -141,15 +141,15 @@ uniform vec2 uTextureOffset;`,Ge=`vec2 screenUv = (vScreenPos.xy / vScreenPos.w)
141
141
  vec2 resultUv = screenUv;
142
142
 
143
143
  `,qe=`vec4 texColor = texture2D(uTexture, resultUv);
144
- baseColor = blendSrcOver(baseColor, texColor);`,we={vertexShader:We,fragmentShader:He},he={declChunk:Pe,uvChunk:Ge,baseColorChunk:qe};function $e(s,e,t,r=null,i){var U;const o=r!==null||!!s.imageSrc;let n="";const a={};if(i!=null&&i.uniforms)for(const[w,E]of Object.entries(i.uniforms))typeof E=="number"?(n+=`uniform float ${w};
145
- `,a[w]={value:E}):Array.isArray(E)?E.length===2?(n+=`uniform vec2 ${w};
146
- `,a[w]={value:new v.Vector2(...E)}):E.length===3?(n+=`uniform vec3 ${w};
147
- `,a[w]={value:new v.Vector3(...E)}):E.length===4&&(n+=`uniform vec4 ${w};
148
- `,a[w]={value:new v.Vector4(...E)}):(n+=`uniform float ${w};
149
- `,a[w]={value:E});const l=(o?he.declChunk:"")+`
144
+ baseColor = blendSrcOver(baseColor, texColor);`,we={vertexShader:We,fragmentShader:He},he={declChunk:Pe,uvChunk:Ge,baseColorChunk:qe};function $e(s,e,t,r=null,i){var O;const a=r!==null||!!s.imageSrc;let n="";const o={};if(i!=null&&i.uniforms)for(const[w,E]of Object.entries(i.uniforms))typeof E=="number"?(n+=`uniform float ${w};
145
+ `,o[w]={value:E}):Array.isArray(E)?E.length===2?(n+=`uniform vec2 ${w};
146
+ `,o[w]={value:new v.Vector2(...E)}):E.length===3?(n+=`uniform vec3 ${w};
147
+ `,o[w]={value:new v.Vector3(...E)}):E.length===4&&(n+=`uniform vec4 ${w};
148
+ `,o[w]={value:new v.Vector4(...E)}):(n+=`uniform float ${w};
149
+ `,o[w]={value:E});const l=(a?he.declChunk:"")+`
150
150
  `+n,c=s.isTraveler?he.uvChunk:`vec2 resultUv = vUv * uTextureRepeat + uTextureOffset;
151
- `,d=o?c+((i==null?void 0:i.uvModifier)||""):"",h=o?he.baseColorChunk:"",u=(i==null?void 0:i.colorModifier)||"",p=we.fragmentShader.replace("#INJECT_DECLARATIONS",l).replace("#INJECT_UV_MODIFIER",d).replace("#INJECT_BASE_COLOR",h).replace("#INJECT_COLOR_MODIFIER",u),f=ne(s.backgroundColor),m=ne(s.borderColor),C={uSize:{value:new v.Vector2(e,t)},uBgColor:{value:new v.Vector4(f.color.r,f.color.g,f.color.b,f.alpha)},uBorderColor:{value:new v.Vector4(m.color.r,m.color.g,m.color.b,m.alpha)},uBorderRadius:{value:new v.Vector4(0,0,0,0)},uBorderWidth:{value:ee(s.borderWidth)},uOpacity:{value:(U=s.opacity)!=null?U:1},uTexture:{value:null},uTextureRepeat:{value:new v.Vector2(1,1)},uTextureOffset:{value:new v.Vector2(0,0)},uGradientCount:{value:0},uGradientAngle:{value:0},uGradientColors:{value:Array.from({length:8},()=>new v.Vector4(0,0,0,0))},uGradientStops:{value:new Float32Array(8)}};Te(C.uBorderRadius.value,s.borderRadius),o&&(C.uTexture.value=r);const k=new v.ShaderMaterial({uniforms:Z(Z({},C),a),vertexShader:we.vertexShader,fragmentShader:p,transparent:!0,side:v.FrontSide});return s.backgroundImage&&de(k,{backgroundImage:s.backgroundImage}),k}function je(s,e,t,r,i){const o=ee(e.borderWidth);de(s,{width:t,height:r,borderRadius:e.borderRadius,borderWidth:o,backgroundColor:e.backgroundColor,borderColor:e.borderColor,opacity:e.opacity,texture:i,backgroundImage:e.backgroundImage})}function de(s,e){var r,i,o;if(e.width!==void 0&&e.height!==void 0&&s.uniforms.uSize.value.set(e.width,e.height),e.borderRadius!==void 0&&Te(s.uniforms.uBorderRadius.value,e.borderRadius),e.borderWidth!==void 0&&(s.uniforms.uBorderWidth.value=e.borderWidth),e.backgroundColor!==void 0)if(Array.isArray(e.backgroundColor)){const n=s.uniforms.uBgColor.value.w;s.uniforms.uBgColor.value.set(e.backgroundColor[0],e.backgroundColor[1],e.backgroundColor[2],n)}else if(typeof e.backgroundColor=="string"){const n=ne(e.backgroundColor);s.uniforms.uBgColor.value.set(n.color.r,n.color.g,n.color.b,n.alpha)}else{const n=s.uniforms.uBgColor.value.w;s.uniforms.uBgColor.value.set(e.backgroundColor.r,e.backgroundColor.g,e.backgroundColor.b,n)}if(e.borderColor!==void 0)if(Array.isArray(e.borderColor)){const n=s.uniforms.uBorderColor.value.w;s.uniforms.uBorderColor.value.set(e.borderColor[0],e.borderColor[1],e.borderColor[2],n)}else if(typeof e.borderColor=="string"){const n=ne(e.borderColor);s.uniforms.uBorderColor.value.set(n.color.r,n.color.g,n.color.b,n.alpha)}else{const n=s.uniforms.uBorderColor.value.w;s.uniforms.uBorderColor.value.set(e.borderColor.r,e.borderColor.g,e.borderColor.b,n)}e.opacity!==void 0&&(s.uniforms.uOpacity.value=e.opacity),e.bgOpacity!==void 0&&(s.uniforms.uBgColor.value.w=e.bgOpacity),e.borderOpacity!==void 0&&(s.uniforms.uBorderColor.value.w=e.borderOpacity),s.uniforms.uTexture&&e.texture!==void 0&&(s.uniforms.uTexture.value=e.texture);const t=e.texture!==void 0?e.texture:(r=s.uniforms.uTexture)==null?void 0:r.value;if(t&&(t.image instanceof ImageBitmap||t.image instanceof HTMLImageElement||t.image instanceof HTMLCanvasElement)){const n=t.image.naturalWidth||t.image.videoWidth||t.image.width,a=t.image.naturalHeight||t.image.videoHeight||t.image.height,l=(i=e.width)!=null?i:s.uniforms.uSize.value.x,c=(o=e.height)!=null?o:s.uniforms.uSize.value.y;if(n&&a&&l&&c){const d=n/a,h=l/c;if(d>h){const u=h/d;s.uniforms.uTextureRepeat.value.set(u,1),s.uniforms.uTextureOffset.value.set((1-u)/2,0)}else{const u=d/h;s.uniforms.uTextureRepeat.value.set(1,u),s.uniforms.uTextureOffset.value.set(0,(1-u)/2)}}}else s.uniforms.uTextureRepeat&&(s.uniforms.uTextureRepeat.value.set(1,1),s.uniforms.uTextureOffset.value.set(0,0));if(e.backgroundImage!==void 0){const n=Ve(e.backgroundImage);if(n){s.uniforms.uGradientCount.value=n.stops.length,s.uniforms.uGradientAngle.value=n.angle;for(let a=0;a<8;a++)if(a<n.stops.length){const l=n.stops[a];s.uniforms.uGradientColors.value[a].set(l.color.r,l.color.g,l.color.b,l.alpha),s.uniforms.uGradientStops.value[a]=l.stop}else s.uniforms.uGradientColors.value[a].set(0,0,0,0),s.uniforms.uGradientStops.value[a]=1}else s.uniforms.uGradientCount.value=0}for(const n of Object.keys(e))n!=="width"&&n!=="height"&&n!=="borderRadius"&&n!=="borderWidth"&&n!=="backgroundColor"&&n!=="borderColor"&&n!=="opacity"&&n!=="bgOpacity"&&n!=="borderOpacity"&&n!=="texture"&&n!=="backgroundImage"&&s.uniforms[n]!==void 0&&(s.uniforms[n].value!==void 0&&s.uniforms[n].value!==null&&typeof s.uniforms[n].value.set=="function"?Array.isArray(e[n])?s.uniforms[n].value.set(...e[n]):e[n]!==void 0&&(e[n].copy?s.uniforms[n].value.copy(e[n]):s.uniforms[n].value=e[n]):s.uniforms[n].value=e[n])}function Te(s,e){var a,l,c,d;if(e==null){s.set(0,0,0,0);return}if(typeof e=="number"){s.set(e,e,e,e);return}if(Array.isArray(e)){s.set(e[0],e[1],e[2],e[3]);return}const t=e.split("/")[0].trim().split(/\s+/),r=ee(t[0]),i=ee((a=t[1])!=null?a:t[0]),o=ee((l=t[2])!=null?l:t[0]),n=ee((d=(c=t[3])!=null?c:t[1])!=null?d:t[0]);s.set(r,i,o,n)}const H={create(s,e,t,r,i,o=2,n=null,a){return s==="BOX"?$e(e,r,i,n,a):s==="TEXT"?new ze(t||"",e,r,i,o):new v.MeshBasicMaterial({visible:!1})},update(s,e,t,r,i,o,n=2,a){e==="BOX"?je(s,t,i,o,a):e==="TEXT"&&s.updateText(r||"",t,i,o,n)},forceUpdateUniforms(s,e){de(s,e)}};class Ke{constructor(e,t=!0){g(this,"observer");g(this,"textures",new WeakMap);g(this,"loadStatus",new WeakMap);g(this,"elementUrls",new WeakMap);g(this,"onUpdate");this.onUpdate=e,t&&(this.observer=new IntersectionObserver(r=>{for(const i of r){const o=i.target;i.isIntersecting?this.loadTexture(o):this.disposeTexture(o)}},{rootMargin:"300px"}))}register(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return;this.elementUrls.get(e)!==t&&(this.elementUrls.set(e,t),this.observer?(this.observer.unobserve(e),this.observer.observe(e)):this.loadTexture(e))}unregister(e){e.nodeType===Node.ELEMENT_NODE&&this.observer&&this.observer.unobserve(e),this.disposeTexture(e),this.elementUrls.delete(e),this.loadStatus.delete(e)}loadTexture(e){return Be(this,null,function*(){if(this.loadStatus.get(e)||this.textures.has(e))return;const t=this.elementUrls.get(e);if(t){this.loadStatus.set(e,!0);try{let r;if(t.startsWith("data:image/svg+xml"))r=yield new Promise((o,n)=>{const a=new Image;a.onload=()=>o(a),a.onerror=n,a.src=t});else{const n=yield(yield fetch(t)).blob();r=yield createImageBitmap(n,{imageOrientation:"flipY"})}if(this.elementUrls.get(e)!==t){"close"in r&&r.close();return}const i=new v.Texture(r);r instanceof HTMLImageElement||(i.flipY=!1),i.colorSpace=v.LinearSRGBColorSpace,i.needsUpdate=!0,this.textures.set(e,i),this.onUpdate(e,i)}catch(r){console.warn("[MirageEngine] Failed to load texture:",t,r)}finally{this.elementUrls.has(e)&&this.loadStatus.set(e,!1)}}})}disposeTexture(e){const t=this.textures.get(e);t&&(t.dispose(),this.textures.delete(e),this.onUpdate(e,null)),this.loadStatus.set(e,!1)}get(e){return this.textures.get(e)}disposeAll(){this.observer&&this.observer.disconnect()}}class Je{constructor(e,t,r,i){g(this,"canvas");g(this,"scene");g(this,"camera");g(this,"renderer");g(this,"renderTargets",[]);g(this,"renderOrder",0);g(this,"qualityFactor",2);g(this,"mode","overlay");g(this,"canvasSize","viewport");g(this,"clipArea",1);g(this,"targetLayer","base");g(this,"overscan",200);g(this,"target");g(this,"mountContainer");g(this,"registry");g(this,"targetRect");g(this,"travelersByLayer",Array.from({length:L.MAX_LAYERS},()=>new Set));g(this,"textureManager");g(this,"fixedMeshes",new Set);var a,l,c,d,h;this.target=e,this.mountContainer=r,this.registry=i,this.mode=(a=t.mode)!=null?a:"overlay",this.canvasSize=(l=t.canvasSize)!=null?l:"viewport",this.clipArea=(c=t.travelerClipArea)!=null?c:1,this.targetLayer=(d=t.layer)!=null?d:"base",this.textureManager=new Ke((u,p)=>{const f=this.registry.get(u);f&&f.material instanceof v.ShaderMaterial&&H.forceUpdateUniforms(f.material,{texture:p})},this.isViewport),this.canvas=document.createElement("canvas"),this.scene=new v.Scene,this.targetRect=this.target.getBoundingClientRect();const o=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,n=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.camera=new v.OrthographicCamera(o/-2,o/2,n/2,n/-2,1,1e3),this.camera.position.z=100,this.camera.layers.set(this.getSceneLayer()),this.renderer=new v.WebGLRenderer({canvas:this.canvas,alpha:!0,antialias:!0}),v.ColorManagement.enabled=!1,this.renderer.outputColorSpace=v.LinearSRGBColorSpace,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(o,n),this.applyTextQuality((h=t.quality)!=null?h:"medium")}get isViewport(){return this.mode==="overlay"&&this.canvasSize==="viewport"}getSceneLayer(){return typeof this.targetLayer=="number"?this.targetLayer:this.targetLayer==="selected"?A.SELECTED:A.BASE}createRenderTarget(){for(let e=0;e<L.MAX_LAYERS;e++){const t=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,r=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.renderTargets.push(new v.WebGLRenderTarget(t*this.qualityFactor,r*this.qualityFactor,{minFilter:v.LinearFilter,magFilter:v.LinearFilter,format:v.RGBAFormat,stencilBuffer:!1,depthBuffer:!0}))}}applyTextQuality(e){if(typeof e=="number"){this.qualityFactor=Math.max(.1,e);return}switch(e){case"low":this.qualityFactor=1;break;case"high":this.qualityFactor=4;break;case"medium":this.qualityFactor=2;break;default:this.qualityFactor=2;break}}mount(){this.mountContainer.prepend(this.canvas),this.canvas.style.pointerEvents=this.mode==="overlay"?"none":"auto",this.updateCanvasLayout()}updateCanvasLayout(){const e=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,t=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.mode==="duplicate"?(this.canvas.style.position="",this.canvas.style.top="",this.canvas.style.left="",this.canvas.style.display="block"):(this.canvas.style.position=this.isViewport?"fixed":"absolute",this.canvas.style.top=this.isViewport?`-${this.overscan}px`:`${this.target.offsetTop}px`,this.canvas.style.left=this.isViewport?`-${this.overscan}px`:`${this.target.offsetLeft}px`,this.canvas.style.display="block")}updateUniforms(e,t){const r=this.registry.get(e);r&&(r.traverse(i=>{i.isMesh&&i.material&&H.forceUpdateUniforms(i.material,t)}),r.userData.nativeMesh&&r.userData.nativeMesh.traverse(i=>{i.isMesh&&i.material&&H.forceUpdateUniforms(i.material,t)}))}dispose(){this.renderer.dispose(),this.canvas.remove(),this.textureManager.disposeAll()}setSize(e,t){this.renderer.setSize(e,t);for(const r of this.renderTargets)r.setSize(e*this.qualityFactor,t*this.qualityFactor);this.camera.left=e/-2,this.camera.right=e/2,this.camera.top=t/2,this.camera.bottom=t/-2,this.camera.updateProjectionMatrix()}syncScene(e,t){const r=this.target.getBoundingClientRect(),i=this.isViewport?window.innerWidth+this.overscan*2:r.width,o=this.isViewport?window.innerHeight+this.overscan*2:r.height,n=this.isViewport?this.canvas.clientWidth:this.targetRect.width,a=this.isViewport?this.canvas.clientHeight:this.targetRect.height,l=Math.abs(i-n)>.1||Math.abs(o-a)>.1,c=this.mode==="overlay"&&(Math.abs(r.top-this.targetRect.top)>.1||Math.abs(r.left-this.targetRect.left)>.1);l?(this.targetRect=r,this.setSize(i,o),this.updateCanvasLayout()):c?(this.targetRect=r,this.updateCanvasLayout()):this.targetRect=r,this.renderOrder=0,this.reconcileNode(e),t.size>0&&t.forEach(d=>{const h=this.registry.get(d);if(h){this.scene.remove(h);for(const u of this.travelersByLayer)u.delete(h);this.fixedMeshes.delete(h),h.geometry.dispose(),h.userData.nativeMesh&&(this.scene.remove(h.userData.nativeMesh),Array.isArray(h.userData.nativeMesh.material)?h.userData.nativeMesh.material.forEach(u=>u.dispose()):h.userData.nativeMesh.material.dispose(),h.userData.nativeMesh.geometry.dispose()),h.traverse(u=>{u instanceof v.Mesh&&(u.geometry&&u.geometry.dispose(),u.material&&(Array.isArray(u.material)?u.material.forEach(p=>p.dispose()):u.material.dispose()))}),this.registry.remove(d),this.textureManager.unregister(d)}})}reconcileNode(e){var i;let t=this.registry.get(e.element);const r=JSON.stringify(e.shaderHooks||null);if(t&&t.userData.shaderHash!==r&&(this.scene.remove(t),t.geometry.dispose(),t.material instanceof v.Material&&t.material.dispose(),this.registry.remove(e.element),t=void 0),!t){const o=new v.PlaneGeometry(1,1),n=e.isTraveler?(i=this.renderTargets[e.captureLayer-2])==null?void 0:i.texture:this.textureManager.get(e.element),a=H.create("BOX",e.styles,"",e.rect.width,e.rect.height,this.qualityFactor,n,e.shaderHooks);t=new v.Mesh(o,a),e.type==="TEXT"&&(t.name="BG_MESH"),this.scene.add(t),this.registry.register(e.element,t),t.userData.baseMaterial=a,t.userData.domElement=e.element,t.userData.shaderHash=r}if(this.updateMeshProperties(t,e),this.updateMeshLayers(t,e),e.isTraveler)for(let o=0;o<L.MAX_LAYERS;o++)o===e.captureLayer-2?this.travelersByLayer[o].add(t):this.travelersByLayer[o].delete(t);else for(const o of this.travelersByLayer)o.delete(t);if(e.isFixed?this.fixedMeshes.add(t):this.fixedMeshes.delete(t),e.styles.imageSrc?this.textureManager.register(e.element,e.styles.imageSrc):this.textureManager.unregister(e.element),e.type==="BOX")for(const o of e.children)this.reconcileNode(o);else e.type==="TEXT"&&(this.reconcileTextChild(t,e,!1),t.userData.nativeMesh&&e.nativeStyles&&this.reconcileTextChild(t.userData.nativeMesh,e,!0))}reconcileTextChild(e,t,r){var c;const i=t.textLines||[{text:t.textContent||"",rect:t.rect}],o=r?t.nativeStyles:t.textStyles,n=JSON.stringify(o)+t.textContent+i.map(d=>d.text).join("|"),a=(c=e.userData)==null?void 0:c.textChildStyleHash;if(t.dirtyMask&ae||n!==a){e.children.filter(f=>f.name.startsWith("TEXT_CHILD")).forEach(f=>{var C;const m=f;(C=m.material.map)==null||C.dispose(),m.geometry.dispose(),e.remove(m)});const h=t.rect,u=h.x+h.width/2,p=h.y+h.height/2;i.forEach((f,m)=>{const C=H.create("TEXT",o,f.text,f.rect.width,f.rect.height,this.qualityFactor),k=new v.PlaneGeometry(1,1),U=new v.Mesh(k,C);U.name=`TEXT_CHILD_${m}`;const w=t.rect.width===0?1:f.rect.width/t.rect.width,E=t.rect.height===0?1:f.rect.height/t.rect.height;U.scale.set(w,E,1);const z=f.rect.x+f.rect.width/2,_=f.rect.y+f.rect.height/2,Y=z-u,P=-(_-p);U.position.set(t.rect.width===0?0:Y/t.rect.width,t.rect.height===0?0:P/t.rect.height,.005),e.add(U)}),e.userData.textChildStyleHash=n}e.children.forEach(d=>{if(!d.name.startsWith("TEXT_CHILD"))return;const h=d,u=t.visibility&X?A.BASE:A.HIDDEN;if(h.layers.set(u),t.visibility&j&&h.layers.enable(A.SELECTED),t.visibility&X)if(!r&&t.nativeLayer!==void 0&&t.nativeStyles!==void 0)for(let p=t.captureLayer;p<t.nativeLayer;p++)h.layers.enable(A.getCaptureLayer(p));else if(r&&t.nativeLayer!==void 0)for(let p=Math.max(t.captureLayer,t.nativeLayer);p<=L.MAX_LAYERS+1;p++)h.layers.enable(A.getCaptureLayer(p));else for(let p=t.captureLayer;p<=L.MAX_LAYERS+1;p++)h.layers.enable(A.getCaptureLayer(p))})}updateMeshProperties(e,t){var w,E,z;const{rect:r,styles:i}=t,o=this.renderer.getPixelRatio(),n=this.renderer.domElement.width/o,a=this.renderer.domElement.height/o;e.material=e.userData.baseMaterial,e.scale.set(r.width,r.height,1),e.userData.domRect={x:r.x,y:r.y,width:r.width,height:r.height};const l=.001;this.renderOrder++;const c=this.targetRect.left+window.scrollX,d=this.targetRect.top+window.scrollY;let h,u;if(this.isViewport)h=r.x-window.innerWidth/2+r.width/2,u=-r.y+window.innerHeight/2-r.height/2;else{const _=r.x-c,Y=r.y-d;h=_-n/2+r.width/2,u=-Y+a/2-r.height/2}e.position.set(h,u,i.zIndex+this.renderOrder*l);const p=r.x,f=r.y;e.userData.basePosition={x:h,y:u},e.userData.originalBasePosition={x:h,y:u},e.userData.baseSize={width:r.width,height:r.height},e.userData.baseDOM={x:p,y:f},e.userData.isFixed=t.isFixed,e.userData.initialScroll={x:window.scrollX,y:window.scrollY};const m=t.element.nodeType===Node.TEXT_NODE?t.element.parentElement:t.element,C=window.getComputedStyle(m);let k=0,U=0;if(C.transform&&C.transform!=="none"){const _=new DOMMatrix(C.transform);k=_.m41,U=_.m42}if(e.userData.baseTransform={x:k,y:U},delete e.userData.originRatioX,delete e.userData.originRatioY,H.update(e.userData.baseMaterial,"BOX",i,"",r.width,r.height,this.qualityFactor,t.isTraveler?(w=this.renderTargets[t.captureLayer-2])==null?void 0:w.texture:this.textureManager.get(t.element)),t.nativeStyles&&t.nativeRect){if(!e.userData.nativeMesh){const F=H.create("BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(E=this.renderTargets[t.captureLayer-2])==null?void 0:E.texture:this.textureManager.get(t.element),t.shaderHooks),K=new v.Mesh(e.geometry,F);t.type==="TEXT"&&(K.name="BG_MESH"),this.scene.add(K),e.userData.nativeMesh=K}const _=e.userData.nativeMesh;let Y,P;if(this.isViewport)Y=t.nativeRect.x-window.innerWidth/2+t.nativeRect.width/2,P=-t.nativeRect.y+window.innerHeight/2-t.nativeRect.height/2;else{const F=t.nativeRect.x-c,K=t.nativeRect.y-d;Y=F-n/2+t.nativeRect.width/2,P=-K+a/2-t.nativeRect.height/2}_.scale.set(t.nativeRect.width,t.nativeRect.height,1),_.position.set(Y,P,t.nativeStyles.zIndex+this.renderOrder*l),H.update(_.material,"BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(z=this.renderTargets[t.captureLayer-2])==null?void 0:z.texture:this.textureManager.get(t.element))}else e.userData.nativeMesh&&(this.scene.remove(e.userData.nativeMesh),e.userData.nativeMesh.material instanceof v.Material&&e.userData.nativeMesh.material.dispose(),delete e.userData.nativeMesh)}updateMeshLayers(e,t){const r=t.visibility&X?A.BASE:A.HIDDEN;if(e.layers.set(r),t.visibility&j&&e.layers.enable(A.SELECTED),e.userData.nativeMesh&&t.nativeLayer!==void 0){const i=e.userData.nativeMesh;if(i.layers.set(A.HIDDEN),t.visibility&X){for(let o=t.captureLayer;o<t.nativeLayer;o++)e.layers.enable(A.getCaptureLayer(o));for(let o=Math.max(t.captureLayer,t.nativeLayer);o<=L.MAX_LAYERS+1;o++)i.layers.enable(A.getCaptureLayer(o))}}else if(t.visibility&X)for(let i=t.captureLayer;i<=L.MAX_LAYERS+1;i++)e.layers.enable(A.getCaptureLayer(i))}captureRenderTarget(e,t,r){if(e.size===0||!r)return;const i=new v.Color,o=this.renderer.getClearAlpha();this.renderer.getClearColor(i),this.renderer.setClearColor(0,0),this.renderer.setRenderTarget(r),this.renderer.clear(),this.renderer.autoClear=!1,this.renderer.setScissorTest(!0),this.camera.layers.set(t);const n=new v.Vector3,a=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,l=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height,c=this.renderer.getPixelRatio();for(const d of e){n.setFromMatrixPosition(d.matrixWorld),n.project(this.camera);const h=(n.x+1)/2*a,u=(n.y+1)/2*l;let p=0,f=1;typeof this.clipArea=="number"?f=this.clipArea:this.clipArea.endsWith("%")?f=parseFloat(this.clipArea)/100:this.clipArea.endsWith("px")&&(p=parseFloat(this.clipArea));const m=d.scale.x*f+.5,C=d.scale.y*f+.5,k=h-m/2,U=u-C/2,w=(k*this.qualityFactor-p)/c,E=(U*this.qualityFactor-p)/c,z=(m*this.qualityFactor+p*2)/c,_=(C*this.qualityFactor+p*2)/c;this.renderer.setScissor(w,E,z,_),this.renderer.render(this.scene,this.camera)}this.renderer.setScissorTest(!1),this.renderer.autoClear=!0,this.renderer.setRenderTarget(null),this.camera.layers.set(this.getSceneLayer()),this.renderer.setClearColor(i,o)}render(){for(let e=0;e<L.MAX_LAYERS;e++){const t=e+1;this.captureRenderTarget(this.travelersByLayer[e],A.getCaptureLayer(t),this.renderTargets[e])}this.renderer.render(this.scene,this.camera)}syncMeshesByDOM(){const e=this.targetRect.left+window.scrollX,t=this.targetRect.top+window.scrollY,r=this.renderer.getPixelRatio(),i=this.renderer.domElement.width/r,o=this.renderer.domElement.height/r;this.scene.children.forEach(n=>{const a=n;if(!a.userData||!a.userData.domElement)return;const l=a.userData.domElement;let c;if(l.nodeType===Node.TEXT_NODE){const h=document.createRange();h.selectNode(l),c=h.getBoundingClientRect()}else c=l.getBoundingClientRect();const d=a.userData.domRect;if(!d||Math.abs(c.x-d.x)>.5||Math.abs(c.y-d.y)>.5||Math.abs(c.width-d.width)>.5||Math.abs(c.height-d.height)>.5){a.userData.domRect={x:c.x,y:c.y,width:c.width,height:c.height};let h,u;if(this.isViewport)h=c.x-window.innerWidth/2+c.width/2,u=-c.y+window.innerHeight/2-c.height/2;else{const p=c.x-e,f=c.y-t;h=p-i/2+c.width/2,u=-f+o/2-c.height/2}if(a.position.setX(h),a.position.setY(u),a.scale.set(c.width,c.height,1),a.material instanceof v.ShaderMaterial&&H.forceUpdateUniforms(a.material,{width:c.width,height:c.height}),a.userData.nativeMesh){const p=a.userData.nativeMesh;p.position.setX(h),p.position.setY(u),p.scale.set(c.width,c.height,1)}}})}}function Ze(s){const e=s.textContent||"",t=[];let r="",i=null,o=-1;const n=(c,d)=>{for(let h=0;h<c.length;h++){const u=c[h],p=document.createRange();p.setStart(s,d+h),p.setEnd(s,d+h+1);const f=p.getBoundingClientRect();if(f.width===0&&f.height===0){r+=u;continue}o===-1||Math.abs(f.top-o)>f.height/2?(r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),r=u,i={left:f.left,top:f.top,right:f.right,bottom:f.bottom},o=f.top):(r+=u,i&&(i.left=Math.min(i.left,f.left),i.top=Math.min(i.top,f.top),i.right=Math.max(i.right,f.right),i.bottom=Math.max(i.bottom,f.bottom)))}},a=e.match(/[^\s\-]+\-?|\-|\s+/g)||[];let l=0;for(const c of a){const d=document.createRange();d.setStart(s,l),d.setEnd(s,l+c.length);const h=d.getClientRects();if(h.length>1)n(c,l);else{const u=h.length===1?h[0]:d.getBoundingClientRect();if(u.width===0&&u.height===0){r+=c,l+=c.length;continue}o===-1||Math.abs(u.top-o)>u.height/2?(r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),r=c,i={left:u.left,top:u.top,right:u.right,bottom:u.bottom},o=u.top):(r+=c,i&&(i.left=Math.min(i.left,u.left),i.top=Math.min(i.top,u.top),i.right=Math.max(i.right,u.right),i.bottom=Math.max(i.bottom,u.bottom)))}l+=c.length}return r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),t.filter(c=>c.text.trim().length>0&&c.rect.width>0&&c.rect.height>0)}function Ce(s){const e=parseFloat(s.fontSize);let t=parseFloat(s.lineHeight);isNaN(t)&&(t=e*1.2);let r=parseFloat(s.letterSpacing);return isNaN(r)&&(r=0),{font:`${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`,fontSize:s.fontSize,color:s.color,textAlign:s.textAlign||"start",textBaseline:"alphabetic",direction:s.direction||"inherit",lineHeight:t,letterSpacing:r}}function xe(s,e=$|Q|ve|ae|se,t,r=1,i=0,o=2,n,a){var Re,Le,Me,De,Ae,Ie;if(s.nodeType===Node.TEXT_NODE){const y=s;if(!y.textContent||!y.textContent.trim())return null;const M=y.textContent.replace(/\s+/g," ");if(M.length===0)return null;const B=Ze(y);if(B.length===0)return null;const V=y.parentElement,I=V?window.getComputedStyle(V):null;if(!I)return null;const G=Math.min(...B.map(D=>D.rect.left)),x=Math.min(...B.map(D=>D.rect.top)),q=Math.max(...B.map(D=>D.rect.left+D.rect.width)),J=Math.max(...B.map(D=>D.rect.top+D.rect.height));return{id:Math.random().toString(36).substring(2,9),type:"TEXT",element:y,rect:{x:G+window.scrollX,y:x+window.scrollY,width:q-G,height:J-x},styles:{backgroundColor:"transparent",backgroundImage:"",opacity:V&&V.dataset[N.KEY]===N.VALUES.HIDE?1:parseFloat(I.opacity),zIndex:(isNaN(parseInt(I.zIndex))?0:parseInt(I.zIndex))+i,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},textContent:M,textLines:B.map(D=>({text:D.text.trim(),rect:{x:D.rect.left+window.scrollX,y:D.rect.top+window.scrollY,width:D.rect.width,height:D.rect.height}})),textStyles:Ce(I),dirtyMask:e,visibility:t,isTraveler:!1,captureLayer:r,isFixed:I.position==="fixed",nativeLayer:n,nativeStyles:a?Z(Z({backgroundColor:"transparent",backgroundImage:"",opacity:V&&V.dataset[N.KEY]===N.VALUES.HIDE?1:parseFloat(I.opacity),zIndex:(isNaN(parseInt(I.zIndex))?0:parseInt(I.zIndex))+i,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},Ce(I)),a):void 0,nativeRect:a?{x:G+window.scrollX,y:x+window.scrollY,width:q-G,height:J-x}:void 0,children:[]}}if(s.nodeType!==Node.ELEMENT_NODE)return null;const l=s,c=l.dataset[R.KEY];let d=t,h=t;if(c){const y=new Set(c.split(/\s+/));for(const M of y)if(!le.includes(M))throw new Error(`[MirageEngine] Invalid filter token: '${M}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(y.has(R.VALUES.END))return null;if(y.has(R.VALUES.INCLUDE_TREE)&&y.has(R.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting filters: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(y.has(R.VALUES.INCLUDE_SELF)&&y.has(R.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting filters: 'include-self' and 'exclude-self' cannot be used together on the same element.");y.has(R.VALUES.INCLUDE_TREE)?d=d|X:y.has(R.VALUES.EXCLUDE_TREE)&&(d=d&~X),h=d,y.has(R.VALUES.INCLUDE_SELF)?h=h|X:y.has(R.VALUES.EXCLUDE_SELF)&&(h=h&~X)}const u=l.dataset[O.KEY];if(u){const y=new Set(u.split(/\s+/));for(const M of y)if(!le.includes(M))throw new Error(`[MirageEngine] Invalid select token: '${M}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(y.has(O.VALUES.END))return null;if(y.has(O.VALUES.INCLUDE_TREE)&&y.has(O.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting selects: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(y.has(O.VALUES.INCLUDE_SELF)&&y.has(O.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting selects: 'include-self' and 'exclude-self' cannot be used together on the same element.");y.has(O.VALUES.INCLUDE_TREE)?d=d|j:y.has(O.VALUES.EXCLUDE_TREE)&&(d=d&~j),h=d,y.has(O.VALUES.INCLUDE_SELF)?h=h|j:y.has(O.VALUES.EXCLUDE_SELF)&&(h=h&~j)}const p=l.dataset[L.KEY];let f=!1,m=a?Z({},a):{},C=n;if(p){let y=1;const M=p.indexOf("{"),B=p.lastIndexOf("}");let V=p;if(M!==-1&&B!==-1&&B>M){V=p.substring(0,M).trim();const x=p.substring(M,B+1);try{m=new Function("return "+x)()}catch(q){console.warn(`[MirageEngine] Failed to parse travel styles JSON: ${x}`)}}const I=V.split(/\s+/);let G=!1;if(I.includes(L.VALUES.TRAVELER)){f=!0,G=!0;const x=I.find(q=>!isNaN(parseInt(q,10)));x&&(y=parseInt(x,10))}else if(I.includes(L.VALUES.NATIVE)){f=!1;const x=I.find(q=>!isNaN(parseInt(q,10)));x&&(C=parseInt(x,10))}if(G){const x=y+1;if(x<r)throw new Error(`[MirageEngine] Traveler layer (${y}) cannot be smaller than inherited capture layer (${r-1}).`);r=Math.min(x,L.MAX_LAYERS+1)}}const k=l.dataset[me.KEY];let U;k&&(U=JSON.parse(k));const w=l.getBoundingClientRect(),E=window.getComputedStyle(l);if(w.width===0||w.height===0||E.display==="none")return null;let z=l.getAttribute("data-mid");z||(z=Math.random().toString(36).substring(2,11),l.setAttribute("data-mid",z));const _=parseInt(E.zIndex),Y=(isNaN(_)?0:_)+i;let P;if(l.tagName==="IMG")P=l.src;else if(l.tagName.toLowerCase()==="svg"){const y=l.cloneNode(!0),M=m==null?void 0:m.color,B=m==null?void 0:m.fill,V=m==null?void 0:m.stroke,I=m==null?void 0:m.opacity,G=(D,ke)=>{const W=window.getComputedStyle(D),oe=ke,nt=W.fill===W.color,ot=W.stroke===W.color,ue=B||(nt?M:void 0)||W.fill;ue&&ue!=="none"&&(oe.style.fill=ue);const fe=V||(ot?M:void 0)||W.stroke;fe&&fe!=="none"&&(oe.style.stroke=fe),W.strokeWidth&&W.strokeWidth!=="0px"&&(oe.style.strokeWidth=W.strokeWidth);const Oe=M||W.color;Oe&&(oe.style.color=Oe);const ge=I||W.opacity;ge&&ge!=="1"&&(oe.style.opacity=ge);for(let ce=0;ce<D.children.length;ce++)G(D.children[ce],ke.children[ce])};G(l,y);const x=l.getBoundingClientRect(),q=window.devicePixelRatio*o;y.hasAttribute("viewBox")||y.setAttribute("viewBox",`0 0 ${x.width} ${x.height}`),y.setAttribute("width",(x.width*q).toString()),y.setAttribute("height",(x.height*q).toString());let J=new XMLSerializer().serializeToString(y);J.includes("xmlns=")||(J=J.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),P=`data:image/svg+xml;utf8,${encodeURIComponent(J)}`}else if(E.backgroundImage&&E.backgroundImage!=="none"){const y=E.backgroundImage.match(/url\(['"]?(.*?)['"]?\)/);y&&(P=y[1])}const F={backgroundColor:E.backgroundColor,backgroundImage:E.backgroundImage,opacity:l.dataset[N.KEY]===N.VALUES.HIDE?1:parseFloat(E.opacity),zIndex:Y,borderRadius:E.borderRadius,borderColor:E.borderColor,borderWidth:E.borderWidth,imageSrc:P,isTraveler:f},K=F;let it,st;const Se=[];return l.tagName.toLowerCase()!=="svg"&&Array.from(l.childNodes).forEach(y=>{const M=y.nodeType===Node.TEXT_NODE?h:d,B=xe(y,e,M,r,Y,o,C,y.nodeType===Node.TEXT_NODE&&Object.keys(m).length>0?m:void 0);B&&Se.push(B)}),{id:z,type:"BOX",element:l,rect:{x:w.left+window.scrollX,y:w.top+window.scrollY,width:w.width,height:w.height},styles:K,textContent:it,textStyles:st,dirtyMask:e,visibility:h,isTraveler:f,captureLayer:r,nativeLayer:C,nativeStyles:C!==void 0?_e(Z({},F),{backgroundColor:(Re=m.backgroundColor)!=null?Re:F.backgroundColor,backgroundImage:(Le=m.backgroundImage)!=null?Le:F.backgroundImage,opacity:(Me=m.opacity)!=null?Me:F.opacity,zIndex:m.zIndex!==void 0?m.zIndex+Y:F.zIndex,borderRadius:(De=m.borderRadius)!=null?De:F.borderRadius,borderColor:(Ae=m.borderColor)!=null?Ae:F.borderColor,borderWidth:(Ie=m.borderWidth)!=null?Ie:F.borderWidth,isTraveler:F.isTraveler}):void 0,nativeRect:C!==void 0?{x:m.x!==void 0?parseFloat(m.x):w.left+window.scrollX,y:m.y!==void 0?parseFloat(m.y):w.top+window.scrollY,width:m.width!==void 0?parseFloat(m.width):w.width,height:m.height!==void 0?parseFloat(m.height):w.height}:void 0,isFixed:E.position==="fixed",children:Se,shaderHooks:U}}function Qe(s,e){e.size!==0&&e.forEach((t,r)=>{var o,n;const i=s.get(r);!i||!i.userData.basePosition||H.forceUpdateUniforms(i.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(n=t.borderRadius)!=null?n:(o=i.userData.baseStyles)==null?void 0:o.borderRadius})})}class et{constructor(e,t,r,i){g(this,"target");g(this,"renderer");g(this,"registry");g(this,"isTravelEnabled",!1);g(this,"tracker");this.target=e,this.renderer=t,this.registry=r,this.tracker=new be(e,{resizeDebounce:i.resizeDebounce}),this.tracker.onLayoutChange.add((o,n)=>{document.querySelector(`[${L.NAME}~='${L.VALUES.TRAVELER}']`)!==null&&!this.isTravelEnabled&&(this.isTravelEnabled=!0,this.renderer.createRenderTarget());const l=xe(this.target,o,X,1,0,this.renderer.qualityFactor);l&&this.renderer.syncScene(l,n)}),this.tracker.onStyleChange.add(o=>{Qe(this.registry,o)}),this.tracker.onRender.add(()=>{this.renderer.syncMeshesByDOM(),this.renderer.render()})}start(){this.tracker.start()}stop(){this.tracker.stop()}}class tt{constructor(){g(this,"store");this.store=new WeakMap}register(e,t){this.store.set(e,t)}get(e){return this.store.get(e)}has(e){return this.store.has(e)}remove(e){this.store.delete(e)}}class rt{constructor(e,t){g(this,"renderer");g(this,"syncer");g(this,"target");g(this,"registry");var i,o,n;if(this.target=e,this.registry=new tt,!document.getElementById("mirage-engine-styles")){const a=document.createElement("style");a.id="mirage-engine-styles",a.textContent=`
151
+ `,d=a?c+((i==null?void 0:i.uvModifier)||""):"",h=a?he.baseColorChunk:"",u=(i==null?void 0:i.colorModifier)||"",p=we.fragmentShader.replace("#INJECT_DECLARATIONS",l).replace("#INJECT_UV_MODIFIER",d).replace("#INJECT_BASE_COLOR",h).replace("#INJECT_COLOR_MODIFIER",u),f=ne(s.backgroundColor),m=ne(s.borderColor),C={uSize:{value:new v.Vector2(e,t)},uBgColor:{value:new v.Vector4(f.color.r,f.color.g,f.color.b,f.alpha)},uBorderColor:{value:new v.Vector4(m.color.r,m.color.g,m.color.b,m.alpha)},uBorderRadius:{value:new v.Vector4(0,0,0,0)},uBorderWidth:{value:ee(s.borderWidth)},uOpacity:{value:(O=s.opacity)!=null?O:1},uTexture:{value:null},uTextureRepeat:{value:new v.Vector2(1,1)},uTextureOffset:{value:new v.Vector2(0,0)},uGradientCount:{value:0},uGradientAngle:{value:0},uGradientColors:{value:Array.from({length:8},()=>new v.Vector4(0,0,0,0))},uGradientStops:{value:new Float32Array(8)}};Te(C.uBorderRadius.value,s.borderRadius),a&&(C.uTexture.value=r);const k=new v.ShaderMaterial({uniforms:Z(Z({},C),o),vertexShader:we.vertexShader,fragmentShader:p,transparent:!0,side:v.FrontSide});return s.backgroundImage&&de(k,{backgroundImage:s.backgroundImage}),k}function je(s,e,t,r,i){const a=ee(e.borderWidth);de(s,{width:t,height:r,borderRadius:e.borderRadius,borderWidth:a,backgroundColor:e.backgroundColor,borderColor:e.borderColor,opacity:e.opacity,texture:i,backgroundImage:e.backgroundImage})}function de(s,e){var r,i,a;if(e.width!==void 0&&e.height!==void 0&&s.uniforms.uSize.value.set(e.width,e.height),e.borderRadius!==void 0&&Te(s.uniforms.uBorderRadius.value,e.borderRadius),e.borderWidth!==void 0&&(s.uniforms.uBorderWidth.value=e.borderWidth),e.backgroundColor!==void 0)if(Array.isArray(e.backgroundColor)){const n=s.uniforms.uBgColor.value.w;s.uniforms.uBgColor.value.set(e.backgroundColor[0],e.backgroundColor[1],e.backgroundColor[2],n)}else if(typeof e.backgroundColor=="string"){const n=ne(e.backgroundColor);s.uniforms.uBgColor.value.set(n.color.r,n.color.g,n.color.b,n.alpha)}else{const n=s.uniforms.uBgColor.value.w;s.uniforms.uBgColor.value.set(e.backgroundColor.r,e.backgroundColor.g,e.backgroundColor.b,n)}if(e.borderColor!==void 0)if(Array.isArray(e.borderColor)){const n=s.uniforms.uBorderColor.value.w;s.uniforms.uBorderColor.value.set(e.borderColor[0],e.borderColor[1],e.borderColor[2],n)}else if(typeof e.borderColor=="string"){const n=ne(e.borderColor);s.uniforms.uBorderColor.value.set(n.color.r,n.color.g,n.color.b,n.alpha)}else{const n=s.uniforms.uBorderColor.value.w;s.uniforms.uBorderColor.value.set(e.borderColor.r,e.borderColor.g,e.borderColor.b,n)}e.opacity!==void 0&&(s.uniforms.uOpacity.value=e.opacity),e.bgOpacity!==void 0&&(s.uniforms.uBgColor.value.w=e.bgOpacity),e.borderOpacity!==void 0&&(s.uniforms.uBorderColor.value.w=e.borderOpacity),s.uniforms.uTexture&&e.texture!==void 0&&(s.uniforms.uTexture.value=e.texture);const t=e.texture!==void 0?e.texture:(r=s.uniforms.uTexture)==null?void 0:r.value;if(t&&(t.image instanceof ImageBitmap||t.image instanceof HTMLImageElement||t.image instanceof HTMLCanvasElement)){const n=t.image.naturalWidth||t.image.videoWidth||t.image.width,o=t.image.naturalHeight||t.image.videoHeight||t.image.height,l=(i=e.width)!=null?i:s.uniforms.uSize.value.x,c=(a=e.height)!=null?a:s.uniforms.uSize.value.y;if(n&&o&&l&&c){const d=n/o,h=l/c;if(d>h){const u=h/d;s.uniforms.uTextureRepeat.value.set(u,1),s.uniforms.uTextureOffset.value.set((1-u)/2,0)}else{const u=d/h;s.uniforms.uTextureRepeat.value.set(1,u),s.uniforms.uTextureOffset.value.set(0,(1-u)/2)}}}else s.uniforms.uTextureRepeat&&(s.uniforms.uTextureRepeat.value.set(1,1),s.uniforms.uTextureOffset.value.set(0,0));if(e.backgroundImage!==void 0){const n=Ve(e.backgroundImage);if(n){s.uniforms.uGradientCount.value=n.stops.length,s.uniforms.uGradientAngle.value=n.angle;for(let o=0;o<8;o++)if(o<n.stops.length){const l=n.stops[o];s.uniforms.uGradientColors.value[o].set(l.color.r,l.color.g,l.color.b,l.alpha),s.uniforms.uGradientStops.value[o]=l.stop}else s.uniforms.uGradientColors.value[o].set(0,0,0,0),s.uniforms.uGradientStops.value[o]=1}else s.uniforms.uGradientCount.value=0}for(const n of Object.keys(e))n!=="width"&&n!=="height"&&n!=="borderRadius"&&n!=="borderWidth"&&n!=="backgroundColor"&&n!=="borderColor"&&n!=="opacity"&&n!=="bgOpacity"&&n!=="borderOpacity"&&n!=="texture"&&n!=="backgroundImage"&&s.uniforms[n]!==void 0&&(s.uniforms[n].value!==void 0&&s.uniforms[n].value!==null&&typeof s.uniforms[n].value.set=="function"?Array.isArray(e[n])?s.uniforms[n].value.set(...e[n]):e[n]!==void 0&&(e[n].copy?s.uniforms[n].value.copy(e[n]):s.uniforms[n].value=e[n]):s.uniforms[n].value=e[n])}function Te(s,e){var o,l,c,d;if(e==null){s.set(0,0,0,0);return}if(typeof e=="number"){s.set(e,e,e,e);return}if(Array.isArray(e)){s.set(e[0],e[1],e[2],e[3]);return}const t=e.split("/")[0].trim().split(/\s+/),r=ee(t[0]),i=ee((o=t[1])!=null?o:t[0]),a=ee((l=t[2])!=null?l:t[0]),n=ee((d=(c=t[3])!=null?c:t[1])!=null?d:t[0]);s.set(r,i,a,n)}const z={create(s,e,t,r,i,a=2,n=null,o){return s==="BOX"?$e(e,r,i,n,o):s==="TEXT"?new ze(t||"",e,r,i,a):new v.MeshBasicMaterial({visible:!1})},update(s,e,t,r,i,a,n=2,o){e==="BOX"?je(s,t,i,a,o):e==="TEXT"&&s.updateText(r||"",t,i,a,n)},forceUpdateUniforms(s,e){de(s,e)}};class Ke{constructor(e,t=!0){g(this,"observer");g(this,"textures",new WeakMap);g(this,"loadStatus",new WeakMap);g(this,"elementUrls",new WeakMap);g(this,"onUpdate");this.onUpdate=e,t&&(this.observer=new IntersectionObserver(r=>{for(const i of r){const a=i.target;i.isIntersecting?this.loadTexture(a):this.disposeTexture(a)}},{rootMargin:"300px"}))}register(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return;this.elementUrls.get(e)!==t&&(this.elementUrls.set(e,t),this.observer?(this.observer.unobserve(e),this.observer.observe(e)):this.loadTexture(e))}unregister(e){e.nodeType===Node.ELEMENT_NODE&&this.observer&&this.observer.unobserve(e),this.disposeTexture(e),this.elementUrls.delete(e),this.loadStatus.delete(e)}loadTexture(e){return Be(this,null,function*(){if(this.loadStatus.get(e)||this.textures.has(e))return;const t=this.elementUrls.get(e);if(t){this.loadStatus.set(e,!0);try{let r;if(t.startsWith("data:image/svg+xml"))r=yield new Promise((a,n)=>{const o=new Image;o.onload=()=>a(o),o.onerror=n,o.src=t});else{const n=yield(yield fetch(t)).blob();r=yield createImageBitmap(n,{imageOrientation:"flipY"})}if(this.elementUrls.get(e)!==t){"close"in r&&r.close();return}const i=new v.Texture(r);r instanceof HTMLImageElement||(i.flipY=!1),i.colorSpace=v.LinearSRGBColorSpace,i.needsUpdate=!0,this.textures.set(e,i),this.onUpdate(e,i)}catch(r){console.warn("[MirageEngine] Failed to load texture:",t,r)}finally{this.elementUrls.has(e)&&this.loadStatus.set(e,!1)}}})}disposeTexture(e){const t=this.textures.get(e);t&&(t.dispose(),this.textures.delete(e),this.onUpdate(e,null)),this.loadStatus.set(e,!1)}get(e){return this.textures.get(e)}disposeAll(){this.observer&&this.observer.disconnect()}}class Je{constructor(e,t,r,i){g(this,"canvas");g(this,"scene");g(this,"camera");g(this,"renderer");g(this,"renderTargets",[]);g(this,"renderOrder",0);g(this,"qualityFactor",2);g(this,"mode","overlay");g(this,"canvasSize","viewport");g(this,"clipArea",1);g(this,"targetLayer","base");g(this,"overscan",200);g(this,"target");g(this,"mountContainer");g(this,"registry");g(this,"targetRect");g(this,"travelersByLayer",Array.from({length:L.MAX_LAYERS},()=>new Set));g(this,"textureManager");g(this,"fixedMeshes",new Set);var o,l,c,d,h;this.target=e,this.mountContainer=r,this.registry=i,this.mode=(o=t.mode)!=null?o:"overlay",this.canvasSize=(l=t.canvasSize)!=null?l:"viewport",this.clipArea=(c=t.travelerClipArea)!=null?c:1,this.targetLayer=(d=t.layer)!=null?d:"base",this.textureManager=new Ke((u,p)=>{const f=this.registry.get(u);f&&f.material instanceof v.ShaderMaterial&&z.forceUpdateUniforms(f.material,{texture:p})},this.isViewport),this.canvas=document.createElement("canvas"),this.scene=new v.Scene,this.targetRect=this.target.getBoundingClientRect();const a=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,n=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.camera=new v.OrthographicCamera(a/-2,a/2,n/2,n/-2,1,1e3),this.camera.position.z=100,this.camera.layers.set(this.getSceneLayer()),this.renderer=new v.WebGLRenderer({canvas:this.canvas,alpha:!0,antialias:!0}),v.ColorManagement.enabled=!1,this.renderer.outputColorSpace=v.LinearSRGBColorSpace,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(a,n),this.applyTextQuality((h=t.quality)!=null?h:"medium")}get isViewport(){return this.mode==="overlay"&&this.canvasSize==="viewport"}getSceneLayer(){return typeof this.targetLayer=="number"?this.targetLayer:this.targetLayer==="selected"?D.SELECTED:D.BASE}createRenderTarget(){for(let e=0;e<L.MAX_LAYERS;e++){const t=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,r=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.renderTargets.push(new v.WebGLRenderTarget(t*this.qualityFactor,r*this.qualityFactor,{minFilter:v.LinearFilter,magFilter:v.LinearFilter,format:v.RGBAFormat,stencilBuffer:!1,depthBuffer:!0}))}}applyTextQuality(e){if(typeof e=="number"){this.qualityFactor=Math.max(.1,e);return}switch(e){case"low":this.qualityFactor=1;break;case"high":this.qualityFactor=4;break;case"medium":this.qualityFactor=2;break;default:this.qualityFactor=2;break}}mount(){this.mountContainer.prepend(this.canvas),this.canvas.style.pointerEvents=this.mode==="overlay"?"none":"auto",this.updateCanvasLayout()}updateCanvasLayout(){const e=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,t=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height;this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.mode==="duplicate"?(this.canvas.style.position="",this.canvas.style.top="",this.canvas.style.left="",this.canvas.style.display="block"):(this.canvas.style.position=this.isViewport?"fixed":"absolute",this.canvas.style.top=this.isViewport?`-${this.overscan}px`:`${this.target.offsetTop}px`,this.canvas.style.left=this.isViewport?`-${this.overscan}px`:`${this.target.offsetLeft}px`,this.canvas.style.display="block")}updateUniforms(e,t){const r=this.registry.get(e);r&&(r.traverse(i=>{i.isMesh&&i.material&&z.forceUpdateUniforms(i.material,t)}),r.userData.nativeMesh&&r.userData.nativeMesh.traverse(i=>{i.isMesh&&i.material&&z.forceUpdateUniforms(i.material,t)}))}dispose(){this.renderer.dispose(),this.canvas.remove(),this.textureManager.disposeAll()}setSize(e,t){this.renderer.setSize(e,t);for(const r of this.renderTargets)r.setSize(e*this.qualityFactor,t*this.qualityFactor);this.camera.left=e/-2,this.camera.right=e/2,this.camera.top=t/2,this.camera.bottom=t/-2,this.camera.updateProjectionMatrix()}syncScene(e,t){const r=this.target.getBoundingClientRect(),i=this.isViewport?window.innerWidth+this.overscan*2:r.width,a=this.isViewport?window.innerHeight+this.overscan*2:r.height,n=this.isViewport?this.canvas.clientWidth:this.targetRect.width,o=this.isViewport?this.canvas.clientHeight:this.targetRect.height,l=Math.abs(i-n)>.1||Math.abs(a-o)>.1,c=this.mode==="overlay"&&(Math.abs(r.top-this.targetRect.top)>.1||Math.abs(r.left-this.targetRect.left)>.1);l?(this.targetRect=r,this.setSize(i,a),this.updateCanvasLayout()):c?(this.targetRect=r,this.updateCanvasLayout()):this.targetRect=r,this.renderOrder=0,this.reconcileNode(e),t.size>0&&t.forEach(d=>{const h=this.registry.get(d);if(h){this.scene.remove(h);for(const u of this.travelersByLayer)u.delete(h);this.fixedMeshes.delete(h),h.geometry.dispose(),h.userData.nativeMesh&&(this.scene.remove(h.userData.nativeMesh),Array.isArray(h.userData.nativeMesh.material)?h.userData.nativeMesh.material.forEach(u=>u.dispose()):h.userData.nativeMesh.material.dispose(),h.userData.nativeMesh.geometry.dispose()),h.traverse(u=>{u instanceof v.Mesh&&(u.geometry&&u.geometry.dispose(),u.material&&(Array.isArray(u.material)?u.material.forEach(p=>p.dispose()):u.material.dispose()))}),this.registry.remove(d),this.textureManager.unregister(d)}})}reconcileNode(e){var i;let t=this.registry.get(e.element);const r=JSON.stringify(e.shaderHooks||null);if(t&&t.userData.shaderHash!==r&&(this.scene.remove(t),t.geometry.dispose(),t.material instanceof v.Material&&t.material.dispose(),this.registry.remove(e.element),t=void 0),!t){const a=new v.PlaneGeometry(1,1),n=e.isTraveler?(i=this.renderTargets[e.captureLayer-2])==null?void 0:i.texture:this.textureManager.get(e.element),o=z.create("BOX",e.styles,"",e.rect.width,e.rect.height,this.qualityFactor,n,e.shaderHooks);t=new v.Mesh(a,o),e.type==="TEXT"&&(t.name="BG_MESH"),this.scene.add(t),this.registry.register(e.element,t),t.userData.baseMaterial=o,t.userData.domElement=e.element,t.userData.shaderHash=r}if(this.updateMeshProperties(t,e),this.updateMeshLayers(t,e),e.isTraveler)for(let a=0;a<L.MAX_LAYERS;a++)a===e.captureLayer-2?this.travelersByLayer[a].add(t):this.travelersByLayer[a].delete(t);else for(const a of this.travelersByLayer)a.delete(t);if(e.isFixed?this.fixedMeshes.add(t):this.fixedMeshes.delete(t),e.styles.imageSrc?this.textureManager.register(e.element,e.styles.imageSrc):this.textureManager.unregister(e.element),e.type==="BOX")for(const a of e.children)this.reconcileNode(a);else e.type==="TEXT"&&(this.reconcileTextChild(t,e,!1),t.userData.nativeMesh&&e.nativeStyles&&this.reconcileTextChild(t.userData.nativeMesh,e,!0))}reconcileTextChild(e,t,r){var c;const i=t.textLines||[{text:t.textContent||"",rect:t.rect}],a=r?t.nativeStyles:t.textStyles,n=JSON.stringify(a)+t.textContent+i.map(d=>d.text).join("|"),o=(c=e.userData)==null?void 0:c.textChildStyleHash;if(t.dirtyMask&ae||n!==o){e.children.filter(f=>f.name.startsWith("TEXT_CHILD")).forEach(f=>{var C;const m=f;(C=m.material.map)==null||C.dispose(),m.geometry.dispose(),e.remove(m)});const h=t.rect,u=h.x+h.width/2,p=h.y+h.height/2;i.forEach((f,m)=>{const C=z.create("TEXT",a,f.text,f.rect.width,f.rect.height,this.qualityFactor),k=new v.PlaneGeometry(1,1),O=new v.Mesh(k,C);O.name=`TEXT_CHILD_${m}`;const w=t.rect.width===0?1:f.rect.width/t.rect.width,E=t.rect.height===0?1:f.rect.height/t.rect.height;O.scale.set(w,E,1);const Y=f.rect.x+f.rect.width/2,_=f.rect.y+f.rect.height/2,V=Y-u,P=-(_-p);O.position.set(t.rect.width===0?0:V/t.rect.width,t.rect.height===0?0:P/t.rect.height,.005),e.add(O)}),e.userData.textChildStyleHash=n}e.children.forEach(d=>{if(!d.name.startsWith("TEXT_CHILD"))return;const h=d,u=t.visibility&X?D.BASE:D.HIDDEN;if(h.layers.set(u),t.visibility&j&&h.layers.enable(D.SELECTED),t.visibility&X)if(!r&&t.nativeLayer!==void 0&&t.nativeStyles!==void 0)for(let p=t.captureLayer;p<t.nativeLayer;p++)h.layers.enable(D.getCaptureLayer(p));else if(r&&t.nativeLayer!==void 0)for(let p=Math.max(t.captureLayer,t.nativeLayer);p<=L.MAX_LAYERS+1;p++)h.layers.enable(D.getCaptureLayer(p));else for(let p=t.captureLayer;p<=L.MAX_LAYERS+1;p++)h.layers.enable(D.getCaptureLayer(p))})}updateMeshProperties(e,t){var w,E,Y;const{rect:r,styles:i}=t,a=this.renderer.getPixelRatio(),n=this.renderer.domElement.width/a,o=this.renderer.domElement.height/a;e.material=e.userData.baseMaterial,e.scale.set(r.width,r.height,1),e.userData.domRect={x:r.x,y:r.y,width:r.width,height:r.height};const l=.001;this.renderOrder++;const c=this.targetRect.left+window.scrollX,d=this.targetRect.top+window.scrollY;let h,u;if(this.isViewport)h=r.x-window.innerWidth/2+r.width/2,u=-r.y+window.innerHeight/2-r.height/2;else{const _=r.x-c,V=r.y-d;h=_-n/2+r.width/2,u=-V+o/2-r.height/2}e.position.set(h,u,i.zIndex+this.renderOrder*l);const p=r.x,f=r.y;e.userData.basePosition={x:h,y:u},e.userData.originalBasePosition={x:h,y:u},e.userData.baseSize={width:r.width,height:r.height},e.userData.baseDOM={x:p,y:f},e.userData.isFixed=t.isFixed,e.userData.initialScroll={x:window.scrollX,y:window.scrollY};const m=t.element.nodeType===Node.TEXT_NODE?t.element.parentElement:t.element,C=window.getComputedStyle(m);let k=0,O=0;if(C.transform&&C.transform!=="none"){const _=new DOMMatrix(C.transform);k=_.m41,O=_.m42}if(e.userData.baseTransform={x:k,y:O},delete e.userData.originRatioX,delete e.userData.originRatioY,z.update(e.userData.baseMaterial,"BOX",i,"",r.width,r.height,this.qualityFactor,t.isTraveler?(w=this.renderTargets[t.captureLayer-2])==null?void 0:w.texture:this.textureManager.get(t.element)),t.nativeStyles&&t.nativeRect){if(!e.userData.nativeMesh){const F=z.create("BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(E=this.renderTargets[t.captureLayer-2])==null?void 0:E.texture:this.textureManager.get(t.element),t.shaderHooks),K=new v.Mesh(e.geometry,F);t.type==="TEXT"&&(K.name="BG_MESH"),this.scene.add(K),e.userData.nativeMesh=K}const _=e.userData.nativeMesh;let V,P;if(this.isViewport)V=t.nativeRect.x-window.innerWidth/2+t.nativeRect.width/2,P=-t.nativeRect.y+window.innerHeight/2-t.nativeRect.height/2;else{const F=t.nativeRect.x-c,K=t.nativeRect.y-d;V=F-n/2+t.nativeRect.width/2,P=-K+o/2-t.nativeRect.height/2}_.scale.set(t.nativeRect.width,t.nativeRect.height,1),_.position.set(V,P,t.nativeStyles.zIndex+this.renderOrder*l),z.update(_.material,"BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(Y=this.renderTargets[t.captureLayer-2])==null?void 0:Y.texture:this.textureManager.get(t.element))}else e.userData.nativeMesh&&(this.scene.remove(e.userData.nativeMesh),e.userData.nativeMesh.material instanceof v.Material&&e.userData.nativeMesh.material.dispose(),delete e.userData.nativeMesh)}updateMeshLayers(e,t){const r=t.visibility&X?D.BASE:D.HIDDEN;if(e.layers.set(r),t.visibility&j&&e.layers.enable(D.SELECTED),e.userData.nativeMesh&&t.nativeLayer!==void 0){const i=e.userData.nativeMesh;if(i.layers.set(D.HIDDEN),t.visibility&X){for(let a=t.captureLayer;a<t.nativeLayer;a++)e.layers.enable(D.getCaptureLayer(a));for(let a=Math.max(t.captureLayer,t.nativeLayer);a<=L.MAX_LAYERS+1;a++)i.layers.enable(D.getCaptureLayer(a))}}else if(t.visibility&X)for(let i=t.captureLayer;i<=L.MAX_LAYERS+1;i++)e.layers.enable(D.getCaptureLayer(i))}captureRenderTarget(e,t,r){if(e.size===0||!r)return;const i=new v.Color,a=this.renderer.getClearAlpha();this.renderer.getClearColor(i),this.renderer.setClearColor(0,0),this.renderer.setRenderTarget(r),this.renderer.clear(),this.renderer.autoClear=!1,this.renderer.setScissorTest(!0),this.camera.layers.set(t);const n=new v.Vector3,o=this.isViewport?window.innerWidth+this.overscan*2:this.targetRect.width,l=this.isViewport?window.innerHeight+this.overscan*2:this.targetRect.height,c=this.renderer.getPixelRatio();for(const d of e){n.setFromMatrixPosition(d.matrixWorld),n.project(this.camera);const h=(n.x+1)/2*o,u=(n.y+1)/2*l;let p=0,f=1;typeof this.clipArea=="number"?f=this.clipArea:this.clipArea.endsWith("%")?f=parseFloat(this.clipArea)/100:this.clipArea.endsWith("px")&&(p=parseFloat(this.clipArea));const m=d.scale.x*f+.5,C=d.scale.y*f+.5,k=h-m/2,O=u-C/2,w=(k*this.qualityFactor-p)/c,E=(O*this.qualityFactor-p)/c,Y=(m*this.qualityFactor+p*2)/c,_=(C*this.qualityFactor+p*2)/c;this.renderer.setScissor(w,E,Y,_),this.renderer.render(this.scene,this.camera)}this.renderer.setScissorTest(!1),this.renderer.autoClear=!0,this.renderer.setRenderTarget(null),this.camera.layers.set(this.getSceneLayer()),this.renderer.setClearColor(i,a)}render(){for(let e=0;e<L.MAX_LAYERS;e++){const t=e+1;this.captureRenderTarget(this.travelersByLayer[e],D.getCaptureLayer(t),this.renderTargets[e])}this.renderer.render(this.scene,this.camera)}syncMeshesByDOM(){const e=this.targetRect.left+window.scrollX,t=this.targetRect.top+window.scrollY,r=this.renderer.getPixelRatio(),i=this.renderer.domElement.width/r,a=this.renderer.domElement.height/r;this.scene.children.forEach(n=>{const o=n;if(!o.userData||!o.userData.domElement)return;const l=o.userData.domElement;let c;if(l.nodeType===Node.TEXT_NODE){const h=document.createRange();h.selectNode(l),c=h.getBoundingClientRect()}else c=l.getBoundingClientRect();const d=o.userData.domRect;if(!d||Math.abs(c.x-d.x)>.5||Math.abs(c.y-d.y)>.5||Math.abs(c.width-d.width)>.5||Math.abs(c.height-d.height)>.5){o.userData.domRect={x:c.x,y:c.y,width:c.width,height:c.height};let h,u;if(this.isViewport)h=c.x-window.innerWidth/2+c.width/2,u=-c.y+window.innerHeight/2-c.height/2;else{const p=c.x-e,f=c.y-t;h=p-i/2+c.width/2,u=-f+a/2-c.height/2}if(o.position.setX(h),o.position.setY(u),o.scale.set(c.width,c.height,1),o.material instanceof v.ShaderMaterial&&z.forceUpdateUniforms(o.material,{width:c.width,height:c.height}),o.userData.nativeMesh){const p=o.userData.nativeMesh;p.position.setX(h),p.position.setY(u),p.scale.set(c.width,c.height,1)}}})}}function Ze(s){const e=s.textContent||"",t=[];let r="",i=null,a=-1;const n=(c,d)=>{for(let h=0;h<c.length;h++){const u=c[h],p=document.createRange();p.setStart(s,d+h),p.setEnd(s,d+h+1);const f=p.getBoundingClientRect();if(f.width===0&&f.height===0){r+=u;continue}a===-1||Math.abs(f.top-a)>f.height/2?(r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),r=u,i={left:f.left,top:f.top,right:f.right,bottom:f.bottom},a=f.top):(r+=u,i&&(i.left=Math.min(i.left,f.left),i.top=Math.min(i.top,f.top),i.right=Math.max(i.right,f.right),i.bottom=Math.max(i.bottom,f.bottom)))}},o=e.match(/[^\s\-]+\-?|\-|\s+/g)||[];let l=0;for(const c of o){const d=document.createRange();d.setStart(s,l),d.setEnd(s,l+c.length);const h=d.getClientRects();if(h.length>1)n(c,l);else{const u=h.length===1?h[0]:d.getBoundingClientRect();if(u.width===0&&u.height===0){r+=c,l+=c.length;continue}a===-1||Math.abs(u.top-a)>u.height/2?(r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),r=c,i={left:u.left,top:u.top,right:u.right,bottom:u.bottom},a=u.top):(r+=c,i&&(i.left=Math.min(i.left,u.left),i.top=Math.min(i.top,u.top),i.right=Math.max(i.right,u.right),i.bottom=Math.max(i.bottom,u.bottom)))}l+=c.length}return r&&i&&t.push({text:r,rect:{left:i.left,top:i.top,width:i.right-i.left,height:i.bottom-i.top}}),t.filter(c=>c.text.trim().length>0&&c.rect.width>0&&c.rect.height>0)}function Ce(s){const e=parseFloat(s.fontSize);let t=parseFloat(s.lineHeight);isNaN(t)&&(t=e*1.2);let r=parseFloat(s.letterSpacing);return isNaN(r)&&(r=0),{font:`${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`,fontSize:s.fontSize,color:s.color,textAlign:s.textAlign||"start",textBaseline:"alphabetic",direction:s.direction||"inherit",lineHeight:t,letterSpacing:r}}function xe(s,e=$|Q|ve|ae|se,t,r=1,i=0,a=2,n,o){var Re,Le,Me,Ae,De,Ie;if(s.nodeType===Node.TEXT_NODE){const b=s;if(!b.textContent||!b.textContent.trim())return null;const M=b.textContent.replace(/\s+/g," ");if(M.length===0)return null;const B=Ze(b);if(B.length===0)return null;const W=b.parentElement,I=W?window.getComputedStyle(W):null;if(!I)return null;const G=Math.min(...B.map(A=>A.rect.left)),x=Math.min(...B.map(A=>A.rect.top)),q=Math.max(...B.map(A=>A.rect.left+A.rect.width)),J=Math.max(...B.map(A=>A.rect.top+A.rect.height));return{id:Math.random().toString(36).substring(2,9),type:"TEXT",element:b,rect:{x:G+window.scrollX,y:x+window.scrollY,width:q-G,height:J-x},styles:{backgroundColor:"transparent",backgroundImage:"",opacity:W&&W.dataset[N.KEY]===N.VALUES.HIDE?1:parseFloat(I.opacity),zIndex:(isNaN(parseInt(I.zIndex))?0:parseInt(I.zIndex))+i,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},textContent:M,textLines:B.map(A=>({text:A.text.trim(),rect:{x:A.rect.left+window.scrollX,y:A.rect.top+window.scrollY,width:A.rect.width,height:A.rect.height}})),textStyles:Ce(I),dirtyMask:e,visibility:t,isTraveler:!1,captureLayer:r,isFixed:I.position==="fixed",nativeLayer:n,nativeStyles:o?Z(Z({backgroundColor:"transparent",backgroundImage:"",opacity:W&&W.dataset[N.KEY]===N.VALUES.HIDE?1:parseFloat(I.opacity),zIndex:(isNaN(parseInt(I.zIndex))?0:parseInt(I.zIndex))+i,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},Ce(I)),o):void 0,nativeRect:o?{x:G+window.scrollX,y:x+window.scrollY,width:q-G,height:J-x}:void 0,children:[]}}if(s.nodeType!==Node.ELEMENT_NODE)return null;const l=s,c=l.dataset[R.KEY];let d=t,h=t;if(c){const b=new Set(c.split(/\s+/));for(const M of b)if(!le.includes(M))throw new Error(`[MirageEngine] Invalid filter token: '${M}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(b.has(R.VALUES.END))return null;if(b.has(R.VALUES.INCLUDE_TREE)&&b.has(R.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting filters: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(b.has(R.VALUES.INCLUDE_SELF)&&b.has(R.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting filters: 'include-self' and 'exclude-self' cannot be used together on the same element.");b.has(R.VALUES.INCLUDE_TREE)?d=d|X:b.has(R.VALUES.EXCLUDE_TREE)&&(d=d&~X),h=d,b.has(R.VALUES.INCLUDE_SELF)?h=h|X:b.has(R.VALUES.EXCLUDE_SELF)&&(h=h&~X)}const u=l.dataset[U.KEY];if(u){const b=new Set(u.split(/\s+/));for(const M of b)if(!le.includes(M))throw new Error(`[MirageEngine] Invalid select token: '${M}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(b.has(U.VALUES.END))return null;if(b.has(U.VALUES.INCLUDE_TREE)&&b.has(U.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting selects: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(b.has(U.VALUES.INCLUDE_SELF)&&b.has(U.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting selects: 'include-self' and 'exclude-self' cannot be used together on the same element.");b.has(U.VALUES.INCLUDE_TREE)?d=d|j:b.has(U.VALUES.EXCLUDE_TREE)&&(d=d&~j),h=d,b.has(U.VALUES.INCLUDE_SELF)?h=h|j:b.has(U.VALUES.EXCLUDE_SELF)&&(h=h&~j)}const p=l.dataset[L.KEY];let f=!1,m=o?Z({},o):{},C=n;if(p){let b=1;const M=p.indexOf("{"),B=p.lastIndexOf("}");let W=p;if(M!==-1&&B!==-1&&B>M){W=p.substring(0,M).trim();const x=p.substring(M,B+1);try{m=new Function("return "+x)()}catch(q){console.warn(`[MirageEngine] Failed to parse travel styles JSON: ${x}`)}}const I=W.split(/\s+/);let G=!1;if(I.includes(L.VALUES.TRAVELER)){f=!0,G=!0;const x=I.find(q=>!isNaN(parseInt(q,10)));x&&(b=parseInt(x,10))}else if(I.includes(L.VALUES.NATIVE)){f=!1;const x=I.find(q=>!isNaN(parseInt(q,10)));x&&(C=parseInt(x,10))}if(G){const x=b+1;if(x<r)throw new Error(`[MirageEngine] Traveler layer (${b}) cannot be smaller than inherited capture layer (${r-1}).`);r=Math.min(x,L.MAX_LAYERS+1)}}const k=l.dataset[me.KEY];let O;k&&(O=JSON.parse(k));const w=l.getBoundingClientRect(),E=window.getComputedStyle(l);if(w.width===0||w.height===0||E.display==="none")return null;let Y=l.getAttribute("data-mid");Y||(Y=Math.random().toString(36).substring(2,11),l.setAttribute("data-mid",Y));const _=parseInt(E.zIndex),V=(isNaN(_)?0:_)+i;let P;if(l.tagName==="IMG")P=l.src;else if(l.tagName.toLowerCase()==="svg"){const b=l.cloneNode(!0),M=m==null?void 0:m.color,B=m==null?void 0:m.fill,W=m==null?void 0:m.stroke,I=m==null?void 0:m.opacity,G=(A,ke)=>{const H=window.getComputedStyle(A),oe=ke,nt=H.fill===H.color,ot=H.stroke===H.color,ue=B||(nt?M:void 0)||H.fill;ue&&ue!=="none"&&(oe.style.fill=ue);const fe=W||(ot?M:void 0)||H.stroke;fe&&fe!=="none"&&(oe.style.stroke=fe),H.strokeWidth&&H.strokeWidth!=="0px"&&(oe.style.strokeWidth=H.strokeWidth);const Ue=M||H.color;Ue&&(oe.style.color=Ue);const ge=I||H.opacity;ge&&ge!=="1"&&(oe.style.opacity=ge);for(let ce=0;ce<A.children.length;ce++)G(A.children[ce],ke.children[ce])};G(l,b);const x=l.getBoundingClientRect(),q=window.devicePixelRatio*a;b.hasAttribute("viewBox")||b.setAttribute("viewBox",`0 0 ${x.width} ${x.height}`),b.setAttribute("width",(x.width*q).toString()),b.setAttribute("height",(x.height*q).toString());let J=new XMLSerializer().serializeToString(b);J.includes("xmlns=")||(J=J.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),P=`data:image/svg+xml;utf8,${encodeURIComponent(J)}`}else if(E.backgroundImage&&E.backgroundImage!=="none"){const b=E.backgroundImage.match(/url\(['"]?(.*?)['"]?\)/);b&&(P=b[1])}const F={backgroundColor:E.backgroundColor,backgroundImage:E.backgroundImage,opacity:l.dataset[N.KEY]===N.VALUES.HIDE?1:parseFloat(E.opacity),zIndex:V,borderRadius:E.borderRadius,borderColor:E.borderColor,borderWidth:E.borderWidth,imageSrc:P,isTraveler:f},K=F;let it,st;const Se=[];return l.tagName.toLowerCase()!=="svg"&&Array.from(l.childNodes).forEach(b=>{const M=b.nodeType===Node.TEXT_NODE?h:d,B=xe(b,e,M,r,V,a,C,b.nodeType===Node.TEXT_NODE&&Object.keys(m).length>0?m:void 0);B&&Se.push(B)}),{id:Y,type:"BOX",element:l,rect:{x:w.left+window.scrollX,y:w.top+window.scrollY,width:w.width,height:w.height},styles:K,textContent:it,textStyles:st,dirtyMask:e,visibility:h,isTraveler:f,captureLayer:r,nativeLayer:C,nativeStyles:C!==void 0?_e(Z({},F),{backgroundColor:(Re=m.backgroundColor)!=null?Re:F.backgroundColor,backgroundImage:(Le=m.backgroundImage)!=null?Le:F.backgroundImage,opacity:(Me=m.opacity)!=null?Me:F.opacity,zIndex:m.zIndex!==void 0?m.zIndex+V:F.zIndex,borderRadius:(Ae=m.borderRadius)!=null?Ae:F.borderRadius,borderColor:(De=m.borderColor)!=null?De:F.borderColor,borderWidth:(Ie=m.borderWidth)!=null?Ie:F.borderWidth,isTraveler:F.isTraveler}):void 0,nativeRect:C!==void 0?{x:m.x!==void 0?parseFloat(m.x):w.left+window.scrollX,y:m.y!==void 0?parseFloat(m.y):w.top+window.scrollY,width:m.width!==void 0?parseFloat(m.width):w.width,height:m.height!==void 0?parseFloat(m.height):w.height}:void 0,isFixed:E.position==="fixed",children:Se,shaderHooks:O}}function Qe(s,e){e.size!==0&&e.forEach((t,r)=>{var a,n,o,l;const i=s.get(r);!i||!i.userData.basePosition||(z.forceUpdateUniforms(i.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(n=t.borderRadius)!=null?n:(a=i.userData.baseStyles)==null?void 0:a.borderRadius}),i.userData.nativeMesh&&z.forceUpdateUniforms(i.userData.nativeMesh.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(l=t.borderRadius)!=null?l:(o=i.userData.baseStyles)==null?void 0:o.borderRadius}))})}class et{constructor(e,t,r,i){g(this,"target");g(this,"renderer");g(this,"registry");g(this,"isTravelEnabled",!1);g(this,"tracker");this.target=e,this.renderer=t,this.registry=r,this.tracker=new ye(e,{resizeDebounce:i.resizeDebounce}),this.tracker.onLayoutChange.add((a,n)=>{document.querySelector(`[${L.NAME}~='${L.VALUES.TRAVELER}']`)!==null&&!this.isTravelEnabled&&(this.isTravelEnabled=!0,this.renderer.createRenderTarget());const l=xe(this.target,a,X,1,0,this.renderer.qualityFactor);l&&this.renderer.syncScene(l,n)}),this.tracker.onStyleChange.add(a=>{Qe(this.registry,a)}),this.tracker.onRender.add(()=>{this.renderer.syncMeshesByDOM(),this.renderer.render()})}start(){this.tracker.start()}stop(){this.tracker.stop()}}class tt{constructor(){g(this,"store");this.store=new WeakMap}register(e,t){this.store.set(e,t)}get(e){return this.store.get(e)}has(e){return this.store.has(e)}remove(e){this.store.delete(e)}}class rt{constructor(e,t){g(this,"renderer");g(this,"syncer");g(this,"target");g(this,"registry");var i,a,n;if(this.target=e,this.registry=new tt,!document.getElementById("mirage-engine-styles")){const o=document.createElement("style");o.id="mirage-engine-styles",o.textContent=`
152
152
  [${N.NAME}="${N.VALUES.HIDE}"] {
153
153
  opacity: 0 !important;
154
154
  }
155
- `,document.head.appendChild(a)}let r;if(t.mode==="duplicate"?r=(o=(i=t.container)!=null?i:this.target.parentElement)!=null?o:void 0:r=(n=this.target.parentElement)!=null?n:void 0,!r)throw new Error("[Mirage] Cannot find a container (parent or option).");this.renderer=new Je(this.target,t,r,this.registry),this.renderer.mount(),this.syncer=new et(this.target,this.renderer,this.registry,t)}start(){this.syncer.start()}stop(){this.syncer.stop()}dispose(){this.syncer.stop(),this.renderer.dispose()}getTracker(){return this.syncer.tracker}updateUniforms(e,t){this.renderer.updateUniforms(e,t)}getCanvas(){return this.renderer.canvas}test(){const e=this.registry.get(document.querySelector("#box2"));if(!e)return;const t={ArrowRight:!1,ArrowLeft:!1,ArrowUp:!1,ArrowDown:!1};window.addEventListener("keydown",o=>{t[o.key]!==void 0&&(t[o.key]=!0)}),window.addEventListener("keyup",o=>{t[o.key]!==void 0&&(t[o.key]=!1)});const r=2,i=()=>{requestAnimationFrame(i),t.ArrowRight&&e.position.setX(e.position.x+r),t.ArrowLeft&&e.position.setX(e.position.x-r),t.ArrowUp&&e.position.setY(e.position.y+r),t.ArrowDown&&e.position.setY(e.position.y-r)};i()}}b.ALLOWED_FILTERS=le,b.ATTR_DOM=N,b.ATTR_FILTER=R,b.ATTR_SANDWICH=Fe,b.ATTR_SELECT=O,b.ATTR_SHADER=me,b.ATTR_TRAVEL=L,b.DIRTY_CONTENT=ae,b.DIRTY_NONE=ie,b.DIRTY_RECT=$,b.DIRTY_STRUCTURE=se,b.DIRTY_STYLE=Q,b.DIRTY_ZINDEX=ve,b.EXCLUDED=Xe,b.Engine=rt,b.SELECT_LAYER=j,b.THREE_LAYERS=A,b.TRAVEL_VALUES=re,b.Tracker=be,b.USER_LAYER=X,b.extractFromStyle=ye,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})});
155
+ `,document.head.appendChild(o)}let r;if(t.mode==="duplicate"?r=(a=(i=t.container)!=null?i:this.target.parentElement)!=null?a:void 0:r=(n=this.target.parentElement)!=null?n:void 0,!r)throw new Error("[Mirage] Cannot find a container (parent or option).");this.renderer=new Je(this.target,t,r,this.registry),this.renderer.mount(),this.syncer=new et(this.target,this.renderer,this.registry,t)}start(){this.syncer.start()}stop(){this.syncer.stop()}dispose(){this.syncer.stop(),this.renderer.dispose()}getTracker(){return this.syncer.tracker}updateUniforms(e,t){this.renderer.updateUniforms(e,t)}getCanvas(){return this.renderer.canvas}test(){const e=this.registry.get(document.querySelector("#box2"));if(!e)return;const t={ArrowRight:!1,ArrowLeft:!1,ArrowUp:!1,ArrowDown:!1};window.addEventListener("keydown",a=>{t[a.key]!==void 0&&(t[a.key]=!0)}),window.addEventListener("keyup",a=>{t[a.key]!==void 0&&(t[a.key]=!1)});const r=2,i=()=>{requestAnimationFrame(i),t.ArrowRight&&e.position.setX(e.position.x+r),t.ArrowLeft&&e.position.setX(e.position.x-r),t.ArrowUp&&e.position.setY(e.position.y+r),t.ArrowDown&&e.position.setY(e.position.y-r)};i()}}y.ALLOWED_FILTERS=le,y.ATTR_DOM=N,y.ATTR_FILTER=R,y.ATTR_SANDWICH=Fe,y.ATTR_SELECT=U,y.ATTR_SHADER=me,y.ATTR_TRAVEL=L,y.DIRTY_CONTENT=ae,y.DIRTY_NONE=ie,y.DIRTY_RECT=$,y.DIRTY_STRUCTURE=se,y.DIRTY_STYLE=Q,y.DIRTY_ZINDEX=ve,y.EXCLUDED=Xe,y.Engine=rt,y.SELECT_LAYER=j,y.THREE_LAYERS=D,y.TRAVEL_VALUES=re,y.Tracker=ye,y.USER_LAYER=X,y.extractFromStyle=be,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mirage-engine/core",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "main": "src/index.ts",
5
5
  "types": "src/index.ts",
6
6
  "peerDependencies": {
@@ -14,7 +14,7 @@
14
14
  "dependencies": {
15
15
  "@types/three": "^0.181.0",
16
16
  "@mirage-engine/painter": "1.0.2",
17
- "@mirage-engine/dom-tracker": "0.3.5"
17
+ "@mirage-engine/dom-tracker": "0.3.7"
18
18
  },
19
19
  "private": false,
20
20
  "publishConfig": {
@@ -17,8 +17,18 @@ export function animateMeshByData(
17
17
  backgroundColor: styleData.backgroundColor,
18
18
  backgroundImage: styleData.backgroundImage,
19
19
  opacity: styleData.opacity,
20
- borderRadius: styleData.borderRadius ?? mesh.userData.baseStyles?.borderRadius,
20
+ borderRadius:
21
+ styleData.borderRadius ?? mesh.userData.baseStyles?.borderRadius,
21
22
  // width and height are no longer updated here, they are updated in syncMeshesByDOM
22
23
  });
24
+
25
+ if (mesh.userData.nativeMesh) {
26
+ Painter.forceUpdateUniforms((mesh.userData.nativeMesh as THREE.Mesh).material as THREE.ShaderMaterial, {
27
+ backgroundColor: styleData.backgroundColor,
28
+ backgroundImage: styleData.backgroundImage,
29
+ opacity: styleData.opacity,
30
+ borderRadius: styleData.borderRadius ?? mesh.userData.baseStyles?.borderRadius,
31
+ });
32
+ }
23
33
  });
24
34
  }
@@ -74,8 +74,12 @@ export class Renderer {
74
74
  this.scene = new THREE.Scene();
75
75
 
76
76
  this.targetRect = this.target.getBoundingClientRect();
77
- const width = this.isViewport ? window.innerWidth + this.overscan * 2 : this.targetRect.width;
78
- const height = this.isViewport ? window.innerHeight + this.overscan * 2 : this.targetRect.height;
77
+ const width = this.isViewport
78
+ ? window.innerWidth + this.overscan * 2
79
+ : this.targetRect.width;
80
+ const height = this.isViewport
81
+ ? window.innerHeight + this.overscan * 2
82
+ : this.targetRect.height;
79
83
 
80
84
  // target duplicate mode
81
85
  // const width = target.parentElement!.clientWidth;
@@ -121,8 +125,12 @@ export class Renderer {
121
125
 
122
126
  public createRenderTarget() {
123
127
  for (let i = 0; i < ATTR_TRAVEL.MAX_LAYERS; i++) {
124
- const width = this.isViewport ? window.innerWidth + this.overscan * 2 : this.targetRect.width;
125
- const height = this.isViewport ? window.innerHeight + this.overscan * 2 : this.targetRect.height;
128
+ const width = this.isViewport
129
+ ? window.innerWidth + this.overscan * 2
130
+ : this.targetRect.width;
131
+ const height = this.isViewport
132
+ ? window.innerHeight + this.overscan * 2
133
+ : this.targetRect.height;
126
134
  this.renderTargets.push(
127
135
  new THREE.WebGLRenderTarget(
128
136
  width * this.qualityFactor,
@@ -154,7 +162,7 @@ export class Renderer {
154
162
  case "medium":
155
163
  // this.qualityFactor = 2;
156
164
  this.qualityFactor = 2;
157
- break;
165
+ break;
158
166
  default:
159
167
  this.qualityFactor = 2;
160
168
  break;
@@ -170,8 +178,12 @@ export class Renderer {
170
178
  }
171
179
 
172
180
  private updateCanvasLayout() {
173
- const width = this.isViewport ? window.innerWidth + this.overscan * 2 : this.targetRect.width;
174
- const height = this.isViewport ? window.innerHeight + this.overscan * 2 : this.targetRect.height;
181
+ const width = this.isViewport
182
+ ? window.innerWidth + this.overscan * 2
183
+ : this.targetRect.width;
184
+ const height = this.isViewport
185
+ ? window.innerHeight + this.overscan * 2
186
+ : this.targetRect.height;
175
187
  this.canvas.style.width = `${width}px`;
176
188
  this.canvas.style.height = `${height}px`;
177
189
 
@@ -182,8 +194,12 @@ export class Renderer {
182
194
  this.canvas.style.display = "block";
183
195
  } else {
184
196
  this.canvas.style.position = this.isViewport ? "fixed" : "absolute";
185
- this.canvas.style.top = this.isViewport ? `-${this.overscan}px` : `${this.target.offsetTop}px`;
186
- this.canvas.style.left = this.isViewport ? `-${this.overscan}px` : `${this.target.offsetLeft}px`;
197
+ this.canvas.style.top = this.isViewport
198
+ ? `-${this.overscan}px`
199
+ : `${this.target.offsetTop}px`;
200
+ this.canvas.style.left = this.isViewport
201
+ ? `-${this.overscan}px`
202
+ : `${this.target.offsetLeft}px`;
187
203
  this.canvas.style.display = "block";
188
204
  }
189
205
  }
@@ -234,10 +250,18 @@ export class Renderer {
234
250
 
235
251
  public syncScene(graphNode: SceneNode, pendingDeletions: Set<HTMLElement>) {
236
252
  const newRect = this.target.getBoundingClientRect();
237
- const newWidth = this.isViewport ? window.innerWidth + this.overscan * 2 : newRect.width;
238
- const newHeight = this.isViewport ? window.innerHeight + this.overscan * 2 : newRect.height;
239
- const oldWidth = this.isViewport ? this.canvas.clientWidth : this.targetRect.width;
240
- const oldHeight = this.isViewport ? this.canvas.clientHeight : this.targetRect.height;
253
+ const newWidth = this.isViewport
254
+ ? window.innerWidth + this.overscan * 2
255
+ : newRect.width;
256
+ const newHeight = this.isViewport
257
+ ? window.innerHeight + this.overscan * 2
258
+ : newRect.height;
259
+ const oldWidth = this.isViewport
260
+ ? this.canvas.clientWidth
261
+ : this.targetRect.width;
262
+ const oldHeight = this.isViewport
263
+ ? this.canvas.clientHeight
264
+ : this.targetRect.height;
241
265
 
242
266
  const isResized =
243
267
  Math.abs(newWidth - oldWidth) > 0.1 ||
@@ -277,7 +301,9 @@ export class Renderer {
277
301
  if (meshToDestroy.userData.nativeMesh) {
278
302
  this.scene.remove(meshToDestroy.userData.nativeMesh);
279
303
  if (Array.isArray(meshToDestroy.userData.nativeMesh.material)) {
280
- meshToDestroy.userData.nativeMesh.material.forEach((mat: THREE.Material) => mat.dispose());
304
+ meshToDestroy.userData.nativeMesh.material.forEach(
305
+ (mat: THREE.Material) => mat.dispose(),
306
+ );
281
307
  } else {
282
308
  meshToDestroy.userData.nativeMesh.material.dispose();
283
309
  }
@@ -315,7 +341,7 @@ export class Renderer {
315
341
  // private reconcileNode(node: SceneNode, activeElements: Set<HTMLElement>) {
316
342
  private reconcileNode(node: SceneNode) {
317
343
  let mesh = this.registry.get(node.element) as THREE.Mesh | undefined;
318
-
344
+
319
345
  const currentShaderHash = JSON.stringify(node.shaderHooks || null);
320
346
 
321
347
  if (mesh && mesh.userData.shaderHash !== currentShaderHash) {
@@ -342,20 +368,18 @@ export class Renderer {
342
368
  initialTexture,
343
369
  node.shaderHooks,
344
370
  );
345
-
371
+
346
372
  mesh = new THREE.Mesh(geometry, material);
347
373
 
348
374
  if (node.type === "TEXT") mesh.name = "BG_MESH";
349
375
  this.scene.add(mesh);
350
-
376
+
351
377
  this.registry.register(node.element, mesh);
352
378
  mesh.userData.baseMaterial = material;
353
379
  mesh.userData.domElement = node.element;
354
380
  mesh.userData.shaderHash = currentShaderHash;
355
381
  }
356
382
 
357
-
358
-
359
383
  // [Important] use whene mesh animating with js
360
384
 
361
385
  this.updateMeshProperties(mesh, node);
@@ -393,17 +417,27 @@ export class Renderer {
393
417
  } else if (node.type === "TEXT") {
394
418
  this.reconcileTextChild(mesh, node, false);
395
419
  if (mesh.userData.nativeMesh && node.nativeStyles) {
396
- this.reconcileTextChild(mesh.userData.nativeMesh as THREE.Mesh, node, true);
420
+ this.reconcileTextChild(
421
+ mesh.userData.nativeMesh as THREE.Mesh,
422
+ node,
423
+ true,
424
+ );
397
425
  }
398
426
  }
399
427
  }
400
428
 
401
- private reconcileTextChild(parentMesh: THREE.Mesh, node: SceneNode, isNative: boolean) {
429
+ private reconcileTextChild(
430
+ parentMesh: THREE.Mesh,
431
+ node: SceneNode,
432
+ isNative: boolean,
433
+ ) {
402
434
  const lines = node.textLines || [
403
435
  { text: node.textContent || "", rect: node.rect },
404
436
  ];
405
-
406
- const stylesToUse = (isNative ? node.nativeStyles : node.textStyles) as TextStyles;
437
+
438
+ const stylesToUse = (
439
+ isNative ? node.nativeStyles : node.textStyles
440
+ ) as TextStyles;
407
441
  const currentStyleHash =
408
442
  JSON.stringify(stylesToUse) +
409
443
  node.textContent +
@@ -474,8 +508,9 @@ export class Renderer {
474
508
  parentMesh.children.forEach((child) => {
475
509
  if (!child.name.startsWith("TEXT_CHILD")) return;
476
510
  const textMesh = child as THREE.Mesh;
477
-
478
- const layerNum = node.visibility & USER_LAYER ? THREE_LAYERS.BASE : THREE_LAYERS.HIDDEN;
511
+
512
+ const layerNum =
513
+ node.visibility & USER_LAYER ? THREE_LAYERS.BASE : THREE_LAYERS.HIDDEN;
479
514
  textMesh.layers.set(layerNum);
480
515
 
481
516
  if (node.visibility & SELECT_LAYER) {
@@ -483,16 +518,28 @@ export class Renderer {
483
518
  }
484
519
 
485
520
  if (node.visibility & USER_LAYER) {
486
- if (!isNative && node.nativeLayer !== undefined && node.nativeStyles !== undefined) {
521
+ if (
522
+ !isNative &&
523
+ node.nativeLayer !== undefined &&
524
+ node.nativeStyles !== undefined
525
+ ) {
487
526
  for (let i = node.captureLayer; i < node.nativeLayer; i++) {
488
527
  textMesh.layers.enable(THREE_LAYERS.getCaptureLayer(i));
489
528
  }
490
529
  } else if (isNative && node.nativeLayer !== undefined) {
491
- for (let i = Math.max(node.captureLayer, node.nativeLayer); i <= ATTR_TRAVEL.MAX_LAYERS + 1; i++) {
530
+ for (
531
+ let i = Math.max(node.captureLayer, node.nativeLayer);
532
+ i <= ATTR_TRAVEL.MAX_LAYERS + 1;
533
+ i++
534
+ ) {
492
535
  textMesh.layers.enable(THREE_LAYERS.getCaptureLayer(i));
493
536
  }
494
537
  } else {
495
- for (let i = node.captureLayer; i <= ATTR_TRAVEL.MAX_LAYERS + 1; i++) {
538
+ for (
539
+ let i = node.captureLayer;
540
+ i <= ATTR_TRAVEL.MAX_LAYERS + 1;
541
+ i++
542
+ ) {
496
543
  textMesh.layers.enable(THREE_LAYERS.getCaptureLayer(i));
497
544
  }
498
545
  }
@@ -506,7 +553,7 @@ export class Renderer {
506
553
  const pixelRatio = this.renderer.getPixelRatio();
507
554
  const canvasWidth = this.renderer.domElement.width / pixelRatio;
508
555
  const canvasHeight = this.renderer.domElement.height / pixelRatio;
509
-
556
+
510
557
  mesh.material = mesh.userData.baseMaterial as THREE.Material;
511
558
  mesh.scale.set(rect.width, rect.height, 1);
512
559
 
@@ -607,20 +654,27 @@ export class Renderer {
607
654
  const nativeMesh = mesh.userData.nativeMesh as THREE.Mesh;
608
655
  let nativeBaseX: number, nativeBaseY: number;
609
656
  if (this.isViewport) {
610
- nativeBaseX = node.nativeRect.x - window.innerWidth / 2 + node.nativeRect.width / 2;
611
- nativeBaseY = -node.nativeRect.y + window.innerHeight / 2 - node.nativeRect.height / 2;
657
+ nativeBaseX =
658
+ node.nativeRect.x - window.innerWidth / 2 + node.nativeRect.width / 2;
659
+ nativeBaseY =
660
+ -node.nativeRect.y +
661
+ window.innerHeight / 2 -
662
+ node.nativeRect.height / 2;
612
663
  } else {
613
664
  const nativeLocalX = node.nativeRect.x - targetPageX;
614
665
  const nativeLocalY = node.nativeRect.y - targetPageY;
615
- nativeBaseX = nativeLocalX - canvasWidth / 2 + node.nativeRect.width / 2;
616
- nativeBaseY = -nativeLocalY + canvasHeight / 2 - node.nativeRect.height / 2;
666
+ nativeBaseX =
667
+ nativeLocalX - canvasWidth / 2 + node.nativeRect.width / 2;
668
+ nativeBaseY =
669
+ -nativeLocalY + canvasHeight / 2 - node.nativeRect.height / 2;
617
670
  }
618
671
 
619
672
  nativeMesh.scale.set(node.nativeRect.width, node.nativeRect.height, 1);
620
673
  nativeMesh.position.set(
621
674
  nativeBaseX,
622
675
  nativeBaseY,
623
- (node.nativeStyles as BoxStyles).zIndex + this.renderOrder * Z_MICRO_OFFSET,
676
+ (node.nativeStyles as BoxStyles).zIndex +
677
+ this.renderOrder * Z_MICRO_OFFSET,
624
678
  );
625
679
 
626
680
  Painter.update(
@@ -663,7 +717,11 @@ export class Renderer {
663
717
  for (let i = node.captureLayer; i < node.nativeLayer; i++) {
664
718
  mesh.layers.enable(THREE_LAYERS.getCaptureLayer(i));
665
719
  }
666
- for (let i = Math.max(node.captureLayer, node.nativeLayer); i <= ATTR_TRAVEL.MAX_LAYERS + 1; i++) {
720
+ for (
721
+ let i = Math.max(node.captureLayer, node.nativeLayer);
722
+ i <= ATTR_TRAVEL.MAX_LAYERS + 1;
723
+ i++
724
+ ) {
667
725
  nativeMesh.layers.enable(THREE_LAYERS.getCaptureLayer(i));
668
726
  }
669
727
  }
@@ -701,8 +759,12 @@ export class Renderer {
701
759
  this.camera.layers.set(targetLayer);
702
760
 
703
761
  const vector = new THREE.Vector3();
704
- const canvasWidth = this.isViewport ? window.innerWidth + this.overscan * 2 : this.targetRect.width;
705
- const canvasHeight = this.isViewport ? window.innerHeight + this.overscan * 2 : this.targetRect.height;
762
+ const canvasWidth = this.isViewport
763
+ ? window.innerWidth + this.overscan * 2
764
+ : this.targetRect.width;
765
+ const canvasHeight = this.isViewport
766
+ ? window.innerHeight + this.overscan * 2
767
+ : this.targetRect.height;
706
768
 
707
769
  const pixelRatio = this.renderer.getPixelRatio();
708
770
 
@@ -791,7 +853,12 @@ export class Renderer {
791
853
  Math.abs(rect.width - cached.width) > 0.5 ||
792
854
  Math.abs(rect.height - cached.height) > 0.5
793
855
  ) {
794
- mesh.userData.domRect = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
856
+ mesh.userData.domRect = {
857
+ x: rect.x,
858
+ y: rect.y,
859
+ width: rect.width,
860
+ height: rect.height,
861
+ };
795
862
 
796
863
  let baseX: number, baseY: number;
797
864
  if (this.isViewport) {