@mirage-engine/core 0.2.2 → 0.3.1

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,11 +1,11 @@
1
- (function(v,T){typeof exports=="object"&&typeof module!="undefined"?T(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],T):(v=typeof globalThis!="undefined"?globalThis:v||self,T(v.MirageEngine={},v.THREE))})(this,function(v,T){"use strict";var Xe=Object.defineProperty;var Ye=(v,T,M)=>T in v?Xe(v,T,{enumerable:!0,configurable:!0,writable:!0,value:M}):v[T]=M;var u=(v,T,M)=>(Ye(v,typeof T!="symbol"?T+"":T,M),M);var fe=(v,T,M)=>new Promise((p,L)=>{var I=E=>{try{P(M.next(E))}catch(A){L(A)}},z=E=>{try{P(M.throw(E))}catch(A){L(A)}},P=E=>E.done?p(E.value):Promise.resolve(E.value).then(I,z);P((M=M.apply(v,T)).next())});function M(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const p=M(T),L=0,I=1,z=2,P=4,E=8,A=16,B=1,_=2,ge=0,ee=["include-tree","exclude-tree","include-self","exclude-self","end"];class te{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"),i=document.createElement("span"),r=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",i.style.margin="0",i.style.padding="0",i.style.border="none",i.style.lineHeight="normal",r.width=1,r.height=1,r.style.verticalAlign="baseline",i.appendChild(document.createTextNode("Hidden Text")),t.appendChild(i),t.appendChild(r),document.body.appendChild(t);const a=r.offsetTop-i.offsetTop;return document.body.removeChild(t),a}}u(te,"cache",new Map);class pe extends p.MeshBasicMaterial{constructor(t,i,r,a,o=2){super({transparent:!0,side:p.FrontSide,color:16777215});u(this,"canvas");u(this,"ctx");u(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=o,this.map=new p.CanvasTexture(this.canvas),this.map.colorSpace=p.LinearSRGBColorSpace,this.map.minFilter=p.LinearFilter,this.map.magFilter=p.LinearFilter,this.updateText(t,i,r,a)}wrapText(t,i){const r=t.split(`
2
- `),a=[];return r.forEach(o=>{const s=o.match(/[^\s\-]+\-?|\-|\s+/g)||[];if(s.length===0){a.push("");return}let l=s[0];for(let c=1;c<s.length;c++){const d=s[c];this.ctx.measureText(l+d).width<=i+2?l+=d:(l&&a.push(l),l=d.trimStart())}l&&a.push(l)}),a}updateText(t,i,r,a,o){o!==void 0&&(this.qualityFactor=o);const l=(window.devicePixelRatio||1)*this.qualityFactor,c=r*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=i.font,this.ctx.fillStyle=i.color,this.ctx.textBaseline="alphabetic",this.ctx.globalAlpha=1;const f=this.wrapText(t,r),h=i.lineHeight,m=te.getBaseline(i.font);f.forEach((g,C)=>{const x=C*h+m;let R=0;i.textAlign==="center"?R=r/2:i.textAlign==="right"&&(R=r),this.ctx.textAlign=i.textAlign,this.ctx.fillText(g,R,x)}),this.map&&(this.map.needsUpdate=!0)}dispose(){this.map&&this.map.dispose(),super.dispose()}}function N(n){return typeof n=="number"?n:parseFloat(n)||0}function U(n){if(!n||n==="transparent")return{color:new p.Color(16777215),alpha:0};const e=n.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);if(e){const t=parseInt(e[1],10),i=parseInt(e[2],10),r=parseInt(e[3],10),a=e[4]!==void 0?parseFloat(e[4]):1;return{color:new p.Color(`rgb(${t}, ${i}, ${r})`),alpha:a}}return{color:new p.Color(n),alpha:1}}function me(n){const e=[];let t="",i=0;for(let r=0;r<n.length;r++){const a=n[r];if(a==="(")i++;else if(a===")")i--;else if(a===","&&i===0){e.push(t.trim()),t="";continue}t+=a}return t&&e.push(t.trim()),e}function be(n){if(!n||typeof n!="string"||!n.includes("linear-gradient"))return null;const e=n.match(/linear-gradient\((.*)\)/);if(!e)return null;const t=e[1],i=me(t);let r=Math.PI,a=0;const o=i[0].trim();if(o.startsWith("to "))o==="to top"?r=0:o==="to right"?r=Math.PI/2:o==="to bottom"?r=Math.PI:o==="to left"?r=Math.PI*1.5:o==="to top right"||o==="to right top"?r=Math.PI/4:o==="to bottom right"||o==="to right bottom"?r=Math.PI*.75:o==="to bottom left"||o==="to left bottom"?r=Math.PI*1.25:(o==="to top left"||o==="to left top")&&(r=Math.PI*1.75),a=1;else if(o.endsWith("deg")||o.endsWith("rad")||o.endsWith("turn")){const l=parseFloat(o);o.endsWith("deg")?r=l*(Math.PI/180):o.endsWith("rad")?r=l:o.endsWith("turn")&&(r=l*Math.PI*2),a=1}const s=[];for(let l=a;l<i.length&&!(s.length>=8);l++){const c=i[l].trim(),d=c.lastIndexOf(" ");let f=c,h=null;if(d!==-1&&!c.endsWith(")")){const g=c.substring(d+1);(g.endsWith("%")||g.endsWith("px")||!isNaN(parseFloat(g)))&&(f=c.substring(0,d).trim(),h=g)}const m=U(f);s.push({color:m.color,alpha:m.alpha,rawStop:h,stop:0})}if(s.length>0){for(let c=0;c<s.length;c++)s[c].rawStop!==null&&(s[c].stop=parseFloat(s[c].rawStop)/100);s[0].rawStop===null&&(s[0].stop=0),s.length>1&&s[s.length-1].rawStop===null&&(s[s.length-1].stop=1);let l=0;for(let c=1;c<s.length;c++)if(s[c].rawStop!==null||c===s.length-1){const d=c-l;if(d>1){const f=s[l].stop,m=(s[c].stop-f)/d;for(let g=1;g<d;g++)s[l+g].stop=f+m*g}l=c}}return{angle:r,stops:s}}const ve=`varying vec2 vUv;
1
+ (function(y,w){typeof exports=="object"&&typeof module!="undefined"?w(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],w):(y=typeof globalThis!="undefined"?globalThis:y||self,w(y.MirageEngine={},y.THREE))})(this,function(y,w){"use strict";var ct=Object.defineProperty,lt=Object.defineProperties;var ht=Object.getOwnPropertyDescriptors;var Be=Object.getOwnPropertySymbols;var ut=Object.prototype.hasOwnProperty,dt=Object.prototype.propertyIsEnumerable;var we=(y,w,M)=>w in y?ct(y,w,{enumerable:!0,configurable:!0,writable:!0,value:M}):y[w]=M,J=(y,w)=>{for(var M in w||(w={}))ut.call(w,M)&&we(y,M,w[M]);if(Be)for(var M of Be(w))dt.call(w,M)&&we(y,M,w[M]);return y},Se=(y,w)=>lt(y,ht(w));var d=(y,w,M)=>(we(y,typeof w!="symbol"?w+"":w,M),M);var Xe=(y,w,M)=>new Promise((v,ne)=>{var V=D=>{try{A(M.next(D))}catch(F){ne(F)}},oe=D=>{try{A(M.throw(D))}catch(F){ne(F)}},A=D=>D.done?v(D.value):Promise.resolve(D.value).then(V,oe);A((M=M.apply(y,w)).next())});function M(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const v=M(w),ne={INCLUDE_TREE:"include-tree",EXCLUDE_TREE:"exclude-tree",INCLUDE_SELF:"include-self",EXCLUDE_SELF:"exclude-self",END:"end"},V={NAME:"data-mirage-dom",KEY:"mirageDom",VALUES:{HIDE:"hide"}},oe={TRAVELER:"traveler",NATIVE:"native",CAPTURE_1:"1",CAPTURE_2:"2",CAPTURE_3:"3",CAPTURE_4:"4",CAPTURE_5:"5"},A={NAME:"data-mirage-travel",KEY:"mirageTravel",VALUES:oe,MAX_LAYERS:Object.keys(oe).length-1},D={NAME:"data-mirage-filter",KEY:"mirageFilter",VALUES:ne},F={NAME:"data-mirage-select",KEY:"mirageSelect",VALUES:ne},Re={NAME:"data-mirage-shader",KEY:"mirageShader"},Ne={NAME:"data-mirage-sandwich",KEY:"mirageSandwich",VALUES:{FRONT:"front"}},ae=0,K=1,ee=2,Le=4,pe=8,me=16;function Ye(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 Me(s){const e={};if(s.opacity&&(e.opacity=parseFloat(s.opacity)),s.backgroundColor&&s.backgroundColor!=="rgba(0, 0, 0, 0)"){const t=Ye(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 De{constructor(e,t){d(this,"target");d(this,"observer");d(this,"pendingDeletions",new Set);d(this,"pendingStyles",new Map);d(this,"isDomDirty",!1);d(this,"isRunning",!1);d(this,"pendingMask",ae);d(this,"mutationTimer",null);d(this,"cssTimer",null);d(this,"resizeConfig");d(this,"resizeTimer",null);d(this,"isResizing",!1);d(this,"lastScrollX",0);d(this,"lastScrollY",0);d(this,"scrollTimer",null);d(this,"onBeforeRender",new Set);d(this,"onLayoutChange",new Set);d(this,"onStyleChange",new Set);d(this,"onScrollChange",new Set);d(this,"onRender",new Set);d(this,"onTransitionFinished",e=>{this.target.contains(e.target)&&this.mutationTimer===null&&(this.cssTimer&&clearTimeout(this.cssTimer),this.pendingStyles.size==0&&(this.pendingMask|=K|ee,this.cssTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.cssTimer=null},50)))});d(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)});d(this,"renderLoop",()=>{if(!this.isRunning)return;this.onBeforeRender.forEach(i=>i()),this.isDomDirty&&(this.isDomDirty=!1,this.onLayoutChange.forEach(i=>i(this.pendingMask,this.pendingDeletions)),this.pendingDeletions.clear(),this.pendingMask=ae);const e=window.scrollX,t=window.scrollY;(e!==this.lastScrollX||t!==this.lastScrollY)&&(this.onScrollChange.forEach(i=>i(e,t)),this.lastScrollX=e,this.lastScrollY=t,this.scrollTimer&&clearTimeout(this.scrollTimer),this.scrollTimer=window.setTimeout(()=>{this.pendingMask|=K,this.isDomDirty=!0,this.scrollTimer=null},150)),this.pendingStyles.size>0&&(this.onStyleChange.forEach(i=>i(this.pendingStyles)),this.pendingStyles.clear()),this.onRender.forEach(i=>i()),requestAnimationFrame(this.renderLoop)});var r,c;this.target=e;const i=(r=t.resizeDebounce)!=null?r:!0;i===!1?this.resizeConfig={enabled:!1,delay:0}:i===!0?this.resizeConfig={enabled:!0,delay:150}:this.resizeConfig={enabled:!0,delay:(c=i.delay)!=null?c:150,onStart:i.onStart,onEnd:i.onEnd},this.observer=new MutationObserver(n=>{let o=ae;for(const a of n)if(a.type==="childList")o|=pe,a.removedNodes.length>0&&a.removedNodes.forEach(l=>{l instanceof HTMLElement&&this.pendingDeletions.add(l)});else if(a.type==="attributes")if(a.attributeName==="style"){o|=K|ee;const l=a.target,h=Me(l.style);this.pendingStyles.set(l,h)}else(a.attributeName==="class"||a.attributeName&&a.attributeName.startsWith("data-"))&&(o|=K|ee);else a.type==="characterData"&&(o|=me|K);if(o!==ae){if(this.pendingMask|=o,o&pe){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 W=1,Z=2,ze=0,U={BASE:0,SELECTED:1,getCaptureLayer:s=>31-s,HIDDEN:31},ve=Object.values(D.VALUES);class Ae{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"),i=document.createElement("span"),r=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",i.style.margin="0",i.style.padding="0",i.style.border="none",i.style.lineHeight="normal",r.width=1,r.height=1,r.style.verticalAlign="baseline",i.appendChild(document.createTextNode("Hidden Text")),t.appendChild(i),t.appendChild(r),document.body.appendChild(t);const c=r.offsetTop-i.offsetTop;return document.body.removeChild(t),c}}d(Ae,"cache",new Map);class Pe extends v.MeshBasicMaterial{constructor(t,i,r,c,n=2){super({transparent:!0,side:v.FrontSide,color:16777215});d(this,"canvas");d(this,"ctx");d(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,i,r,c)}wrapText(t,i){const r=t.split(`
2
+ `),c=[];return r.forEach(n=>{const o=n.match(/[^\s\-]+\-?|\-|\s+/g)||[];if(o.length===0){c.push("");return}let a=o[0];for(let l=1;l<o.length;l++){const h=o[l];this.ctx.measureText(a+h).width<=i+2?a+=h:(a&&c.push(a),a=h.trimStart())}a&&c.push(a)}),c}updateText(t,i,r,c,n){n!==void 0&&(this.qualityFactor=n);const a=(window.devicePixelRatio||1)*this.qualityFactor,l=r*a,h=c*a;this.canvas.width!==l||this.canvas.height!==h?(this.canvas.width=l,this.canvas.height=h):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.setTransform(a,0,0,a,0,0),this.ctx.font=i.font,this.ctx.fillStyle=i.color,this.ctx.textBaseline="alphabetic",this.ctx.globalAlpha=1;const f=this.wrapText(t,r),b=i.lineHeight,p=Ae.getBaseline(i.font);f.forEach((u,g)=>{const S=g*b+p;let k=0;i.textAlign==="center"?k=r/2:i.textAlign==="right"&&(k=r),this.ctx.textAlign=i.textAlign,this.ctx.fillText(u,k,S)}),this.map&&(this.map.needsUpdate=!0)}dispose(){this.map&&this.map.dispose(),super.dispose()}}function te(s){return typeof s=="number"?s:parseFloat(s)||0}function ce(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),i=parseInt(e[2],10),r=parseInt(e[3],10),c=e[4]!==void 0?parseFloat(e[4]):1;return{color:new v.Color(`rgb(${t}, ${i}, ${r})`),alpha:c}}return{color:new v.Color(s),alpha:1}}function Ve(s){const e=[];let t="",i=0;for(let r=0;r<s.length;r++){const c=s[r];if(c==="(")i++;else if(c===")")i--;else if(c===","&&i===0){e.push(t.trim()),t="";continue}t+=c}return t&&e.push(t.trim()),e}function We(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],i=Ve(t);let r=Math.PI,c=0;const n=i[0].trim();if(n.startsWith("to "))n==="to top"?r=0:n==="to right"?r=Math.PI/2:n==="to bottom"?r=Math.PI:n==="to left"?r=Math.PI*1.5:n==="to top right"||n==="to right top"?r=Math.PI/4:n==="to bottom right"||n==="to right bottom"?r=Math.PI*.75:n==="to bottom left"||n==="to left bottom"?r=Math.PI*1.25:(n==="to top left"||n==="to left top")&&(r=Math.PI*1.75),c=1;else if(n.endsWith("deg")||n.endsWith("rad")||n.endsWith("turn")){const a=parseFloat(n);n.endsWith("deg")?r=a*(Math.PI/180):n.endsWith("rad")?r=a:n.endsWith("turn")&&(r=a*Math.PI*2),c=1}const o=[];for(let a=c;a<i.length&&!(o.length>=8);a++){const l=i[a].trim(),h=l.lastIndexOf(" ");let f=l,b=null;if(h!==-1&&!l.endsWith(")")){const u=l.substring(h+1);(u.endsWith("%")||u.endsWith("px")||!isNaN(parseFloat(u)))&&(f=l.substring(0,h).trim(),b=u)}const p=ce(f);o.push({color:p.color,alpha:p.alpha,rawStop:b,stop:0})}if(o.length>0){for(let l=0;l<o.length;l++)o[l].rawStop!==null&&(o[l].stop=parseFloat(o[l].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 a=0;for(let l=1;l<o.length;l++)if(o[l].rawStop!==null||l===o.length-1){const h=l-a;if(h>1){const f=o[a].stop,p=(o[l].stop-f)/h;for(let u=1;u<h;u++)o[a+u].stop=f+p*u}a=l}}return{angle:r,stops:o}}const He=`varying vec2 vUv;
3
3
  varying vec4 vScreenPos;
4
4
  void main() {
5
5
  vUv = uv;
6
6
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
7
7
  vScreenPos = gl_Position;
8
- }`,xe=`varying vec2 vUv;
8
+ }`,Ge=`varying vec2 vUv;
9
9
  uniform vec2 uSize;
10
10
  uniform vec4 uBorderRadius;
11
11
  uniform float uBorderWidth;
@@ -134,16 +134,22 @@ void main() {
134
134
 
135
135
  // #include <colorspace_fragment>
136
136
  }
137
- `,ye=`uniform sampler2D uTexture;
137
+ `,qe=`uniform sampler2D uTexture;
138
138
  varying vec4 vScreenPos;
139
139
  uniform vec2 uTextureRepeat;
140
- uniform vec2 uTextureOffset;`,Te=`vec2 screenUv = (vScreenPos.xy / vScreenPos.w) * 0.5 + 0.5;
140
+ uniform vec2 uTextureOffset;`,$e=`vec2 screenUv = (vScreenPos.xy / vScreenPos.w) * 0.5 + 0.5;
141
141
  vec2 resultUv = screenUv;
142
142
 
143
- `,Ce=`vec4 texColor = texture2D(uTexture, resultUv);
144
- baseColor = blendSrcOver(baseColor, texColor);`,re={vertexShader:ve,fragmentShader:xe},j={declChunk:ye,uvChunk:Te,baseColorChunk:Ce};function we(n,e,t,i=null,r){var x;const a=i!==null||!!n.imageSrc,o=a?j.declChunk:"",s=n.isTraveler?j.uvChunk:`vec2 resultUv = vUv * uTextureRepeat + uTextureOffset;
145
- `,l=a?s+((r==null?void 0:r.uvModifier)||""):"",c=a?j.baseColorChunk:"",d=(r==null?void 0:r.colorModifier)||"",f=re.fragmentShader.replace("#INJECT_DECLARATIONS",o).replace("#INJECT_UV_MODIFIER",l).replace("#INJECT_BASE_COLOR",c).replace("#INJECT_COLOR_MODIFIER",d),h=U(n.backgroundColor),m=U(n.borderColor),g={uSize:{value:new p.Vector2(e,t)},uBgColor:{value:new p.Vector4(h.color.r,h.color.g,h.color.b,h.alpha)},uBorderColor:{value:new p.Vector4(m.color.r,m.color.g,m.color.b,m.alpha)},uBorderRadius:{value:new p.Vector4(0,0,0,0)},uBorderWidth:{value:N(n.borderWidth)},uOpacity:{value:(x=n.opacity)!=null?x:1},uTexture:{value:null},uTextureRepeat:{value:new p.Vector2(1,1)},uTextureOffset:{value:new p.Vector2(0,0)},uGradientCount:{value:0},uGradientAngle:{value:0},uGradientColors:{value:Array.from({length:8},()=>new p.Vector4(0,0,0,0))},uGradientStops:{value:new Float32Array(8)}};ie(g.uBorderRadius.value,n.borderRadius),a&&(g.uTexture.value=i);const C=new p.ShaderMaterial({uniforms:g,vertexShader:re.vertexShader,fragmentShader:f,transparent:!0,side:p.FrontSide});return n.backgroundImage&&$(C,{backgroundImage:n.backgroundImage}),C}function Se(n,e,t,i,r){const a=N(e.borderWidth);$(n,{width:t,height:i,borderRadius:e.borderRadius,borderWidth:a,backgroundColor:e.backgroundColor,borderColor:e.borderColor,opacity:e.opacity,texture:r,backgroundImage:e.backgroundImage})}function $(n,e){var i,r,a;if(e.width!==void 0&&e.height!==void 0&&n.uniforms.uSize.value.set(e.width,e.height),e.borderRadius!==void 0&&ie(n.uniforms.uBorderRadius.value,e.borderRadius),e.borderWidth!==void 0&&(n.uniforms.uBorderWidth.value=e.borderWidth),e.backgroundColor!==void 0)if(Array.isArray(e.backgroundColor)){const o=n.uniforms.uBgColor.value.w;n.uniforms.uBgColor.value.set(e.backgroundColor[0],e.backgroundColor[1],e.backgroundColor[2],o)}else if(typeof e.backgroundColor=="string"){const o=U(e.backgroundColor);n.uniforms.uBgColor.value.set(o.color.r,o.color.g,o.color.b,o.alpha)}else{const o=n.uniforms.uBgColor.value.w;n.uniforms.uBgColor.value.set(e.backgroundColor.r,e.backgroundColor.g,e.backgroundColor.b,o)}if(e.borderColor!==void 0)if(Array.isArray(e.borderColor)){const o=n.uniforms.uBorderColor.value.w;n.uniforms.uBorderColor.value.set(e.borderColor[0],e.borderColor[1],e.borderColor[2],o)}else if(typeof e.borderColor=="string"){const o=U(e.borderColor);n.uniforms.uBorderColor.value.set(o.color.r,o.color.g,o.color.b,o.alpha)}else{const o=n.uniforms.uBorderColor.value.w;n.uniforms.uBorderColor.value.set(e.borderColor.r,e.borderColor.g,e.borderColor.b,o)}e.opacity!==void 0&&(n.uniforms.uOpacity.value=e.opacity),e.bgOpacity!==void 0&&(n.uniforms.uBgColor.value.w=e.bgOpacity),e.borderOpacity!==void 0&&(n.uniforms.uBorderColor.value.w=e.borderOpacity),n.uniforms.uTexture&&e.texture!==void 0&&(n.uniforms.uTexture.value=e.texture);const t=e.texture!==void 0?e.texture:(i=n.uniforms.uTexture)==null?void 0:i.value;if(t&&(t.image instanceof ImageBitmap||t.image instanceof HTMLImageElement||t.image instanceof HTMLCanvasElement)){const o=t.image.width,s=t.image.height,l=(r=e.width)!=null?r:n.uniforms.uSize.value.x,c=(a=e.height)!=null?a:n.uniforms.uSize.value.y;if(o&&s&&l&&c){const d=o/s,f=l/c;if(d>f){const h=f/d;n.uniforms.uTextureRepeat.value.set(h,1),n.uniforms.uTextureOffset.value.set((1-h)/2,0)}else{const h=d/f;n.uniforms.uTextureRepeat.value.set(1,h),n.uniforms.uTextureOffset.value.set(0,(1-h)/2)}}}else n.uniforms.uTextureRepeat&&(n.uniforms.uTextureRepeat.value.set(1,1),n.uniforms.uTextureOffset.value.set(0,0));if(e.backgroundImage!==void 0){const o=be(e.backgroundImage);if(o){n.uniforms.uGradientCount.value=o.stops.length,n.uniforms.uGradientAngle.value=o.angle;for(let s=0;s<8;s++)if(s<o.stops.length){const l=o.stops[s];n.uniforms.uGradientColors.value[s].set(l.color.r,l.color.g,l.color.b,l.alpha),console.log(l.color.r,l.color.g,l.color.b),n.uniforms.uGradientStops.value[s]=l.stop}else n.uniforms.uGradientColors.value[s].set(0,0,0,0),n.uniforms.uGradientStops.value[s]=1}else n.uniforms.uGradientCount.value=0}}function ie(n,e){var s,l,c,d;if(e==null){n.set(0,0,0,0);return}if(typeof e=="number"){n.set(e,e,e,e);return}if(Array.isArray(e)){n.set(e[0],e[1],e[2],e[3]);return}const t=e.split("/")[0].trim().split(/\s+/),i=N(t[0]),r=N((s=t[1])!=null?s:t[0]),a=N((l=t[2])!=null?l:t[0]),o=N((d=(c=t[3])!=null?c:t[1])!=null?d:t[0]);n.set(i,r,a,o)}const W={create(n,e,t,i,r,a=2,o=null,s){return n==="BOX"?we(e,i,r,o,s):n==="TEXT"?new pe(t||"",e,i,r,a):new p.MeshBasicMaterial({visible:!1})},update(n,e,t,i,r,a,o=2,s){e==="BOX"?Se(n,t,r,a,s):e==="TEXT"&&n.updateText(i||"",t,r,a,o)},forceUpdateUniforms(n,e){$(n,e)}};class Re{constructor(e){u(this,"observer");u(this,"textures",new WeakMap);u(this,"loadStatus",new WeakMap);u(this,"elementUrls",new WeakMap);u(this,"onUpdate");this.onUpdate=e,this.observer=new IntersectionObserver(t=>{for(const i of t){const r=i.target;i.isIntersecting?this.loadTexture(r):this.disposeTexture(r)}},{rootMargin:"300px"})}register(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return;this.elementUrls.get(e)!==t&&(this.elementUrls.set(e,t),this.observer.unobserve(e),this.observer.observe(e))}unregister(e){e.nodeType===Node.ELEMENT_NODE&&this.observer.unobserve(e),this.disposeTexture(e),this.elementUrls.delete(e),this.loadStatus.delete(e)}loadTexture(e){return fe(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{const r=yield(yield fetch(t)).blob(),a=yield createImageBitmap(r,{imageOrientation:"flipY"});if(this.elementUrls.get(e)!==t){a.close();return}const o=new p.CanvasTexture(a);o.needsUpdate=!0,this.textures.set(e,o),this.onUpdate(e,o)}catch(i){console.warn("[MirageEngine] Failed to load texture:",t,i)}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.disconnect()}}class Me{constructor(e,t,i,r){u(this,"canvas");u(this,"scene");u(this,"camera");u(this,"renderer");u(this,"renderTarget",null);u(this,"renderOrder",0);u(this,"qualityFactor",2);u(this,"mode","overlay");u(this,"clipArea",1);u(this,"target");u(this,"mountContainer");u(this,"registry");u(this,"targetRect");u(this,"travelers",new Set);u(this,"textureManager");u(this,"fixedMeshes",new Set);var s,l,c;this.target=e,this.mountContainer=i,this.registry=r,this.textureManager=new Re((d,f)=>{const h=this.registry.get(d);h&&h.material instanceof p.ShaderMaterial&&W.forceUpdateUniforms(h.material,{texture:f})}),this.mode=(s=t.mode)!=null?s:"overlay",this.clipArea=(l=t.travelerClipArea)!=null?l:1,this.canvas=document.createElement("canvas"),this.scene=new p.Scene,this.targetRect=this.target.getBoundingClientRect();const a=this.targetRect.width,o=this.targetRect.height;this.camera=new p.OrthographicCamera(a/-2,a/2,o/2,o/-2,1,1e3),this.camera.position.z=100,this.camera.layers.set(0),this.renderer=new p.WebGLRenderer({canvas:this.canvas,alpha:!0,antialias:!0}),p.ColorManagement.enabled=!1,this.renderer.outputColorSpace=p.LinearSRGBColorSpace,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(a,o),this.applyTextQuality((c=t.quality)!=null?c:"medium")}createRenderTarget(){this.renderTarget=new p.WebGLRenderTarget(this.targetRect.width*this.qualityFactor,this.targetRect.height*this.qualityFactor,{minFilter:p.LinearFilter,magFilter:p.LinearFilter,format:p.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":default:this.qualityFactor=2;break}}mount(){this.mountContainer.prepend(this.canvas),this.canvas.style.pointerEvents=this.mode==="overlay"?"none":"auto",this.updateCanvasLayout()}updateCanvasLayout(){this.canvas.style.width=`${this.targetRect.width}px`,this.canvas.style.height=`${this.targetRect.height}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="absolute",this.canvas.style.top=`${this.target.offsetTop}px`,this.canvas.style.left=`${this.target.offsetLeft}px`,this.canvas.style.display="block")}dispose(){this.renderer.dispose(),this.canvas.remove(),this.textureManager.disposeAll()}setSize(e,t){this.renderer.setSize(e,t),this.renderTarget&&this.renderTarget.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 i=this.target.getBoundingClientRect(),r=Math.abs(i.width-this.targetRect.width)>.1||Math.abs(i.height-this.targetRect.height)>.1,a=this.mode==="overlay"&&(Math.abs(i.top-this.targetRect.top)>.1||Math.abs(i.left-this.targetRect.left)>.1);r?(this.targetRect=i,this.setSize(this.targetRect.width,this.targetRect.height),this.updateCanvasLayout()):a?(this.targetRect=i,this.updateCanvasLayout()):this.targetRect=i,this.renderOrder=0,this.reconcileNode(e),t.size>0&&t.forEach(o=>{const s=this.registry.get(o);s&&(this.scene.remove(s),this.travelers.delete(s),this.fixedMeshes.delete(s),s.geometry.dispose(),s.traverse(l=>{l instanceof p.Mesh&&(l.geometry&&l.geometry.dispose(),l.material&&(Array.isArray(l.material)?l.material.forEach(c=>c.dispose()):l.material.dispose()))}),this.registry.remove(o),this.textureManager.unregister(o))})}reconcileNode(e){var i;let t=this.registry.get(e.element);if(!t){const r=new p.PlaneGeometry(1,1);let a;const o=e.isTraveler?(i=this.renderTarget)==null?void 0:i.texture:this.textureManager.get(e.element);a=W.create("BOX",e.styles,"",e.rect.width,e.rect.height,this.qualityFactor,o,e.shaderHooks),t=new p.Mesh(r,a),e.type==="TEXT"&&(t.name="BG_MESH"),this.scene.add(t),this.registry.register(e.element,t)}if(t.userData.domRect=e.rect,this.updateMeshProperties(t,e),this.updateMeshLayers(t,e),e.isTraveler?(t.layers.enable(28),this.travelers.add(t)):(t.layers.disable(28),this.travelers.delete(t)),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 r of e.children)this.reconcileNode(r);else e.type==="TEXT"&&this.reconcileTextChild(t,e)}reconcileTextChild(e,t){var s;const i=t.textLines||[{text:t.textContent||"",rect:t.rect}],r=JSON.stringify(t.textStyles)+t.textContent+i.map(l=>l.text).join("|"),a=(s=e.userData)==null?void 0:s.textChildStyleHash;if(t.dirtyMask&A||r!==a){e.children.filter(h=>h.name.startsWith("TEXT_CHILD")).forEach(h=>{var g;const m=h;(g=m.material.map)==null||g.dispose(),m.geometry.dispose(),e.remove(m)});const c=t.rect,d=c.x+c.width/2,f=c.y+c.height/2;i.forEach((h,m)=>{const g=W.create("TEXT",t.textStyles,h.text,h.rect.width,h.rect.height,this.qualityFactor),C=new p.PlaneGeometry(1,1),x=new p.Mesh(C,g);x.name=`TEXT_CHILD_${m}`,this.updateMeshLayers(x,t);const R=t.rect.width===0?1:h.rect.width/t.rect.width,D=t.rect.height===0?1:h.rect.height/t.rect.height;x.scale.set(R,D,1);const k=h.rect.x+h.rect.width/2,F=h.rect.y+h.rect.height/2,b=k-d,w=-(F-f);x.position.set(t.rect.width===0?0:b/t.rect.width,t.rect.height===0?0:w/t.rect.height,.005),e.add(x)}),e.userData.textChildStyleHash=r}}updateMeshProperties(e,t){var b;const{rect:i,styles:r}=t,a=this.renderer.getPixelRatio(),o=this.renderer.domElement.width/a,s=this.renderer.domElement.height/a;e.scale.set(i.width,i.height,1);const l=.001;this.renderOrder++;const c=this.targetRect.left+window.scrollX,d=this.targetRect.top+window.scrollY,f=i.x-c,h=i.y-d,m=f-o/2+i.width/2,g=-h+s/2-i.height/2;e.position.set(m,g,r.zIndex+this.renderOrder*l);const C=i.x,x=i.y;e.userData.basePosition={x:m,y:g},e.userData.originalBasePosition={x:m,y:g},e.userData.baseSize={width:i.width,height:i.height},e.userData.baseDOM={x:C,y:x},e.userData.isFixed=t.isFixed,e.userData.initialScroll={x:window.scrollX,y:window.scrollY};const R=t.element.nodeType===Node.TEXT_NODE?t.element.parentElement:t.element,D=window.getComputedStyle(R);let k=0,F=0;if(D.transform&&D.transform!=="none"){const w=new DOMMatrix(D.transform);k=w.m41,F=w.m42}e.userData.baseTransform={x:k,y:F},delete e.userData.originRatioX,delete e.userData.originRatioY,W.update(e.material,"BOX",t.styles,"",t.rect.width,t.rect.height,this.qualityFactor,t.isTraveler?(b=this.renderTarget)==null?void 0:b.texture:this.textureManager.get(t.element))}updateMeshLayers(e,t){const i=(1-(t.visibility&B))*30;e.layers.set(i),t.visibility===(B|_)&&e.layers.enable(29)}captureRenderTarget(){if(this.travelers.size===0)return;const e=new p.Color,t=this.renderer.getClearAlpha();this.renderer.getClearColor(e),this.renderer.setClearColor(0,0),this.renderer.setRenderTarget(this.renderTarget),this.renderer.clear(),this.renderer.autoClear=!1,this.renderer.setScissorTest(!0),this.camera.layers.set(29);const i=new p.Vector3,r=this.targetRect.width,a=this.targetRect.height,o=this.renderer.getPixelRatio();for(const s of this.travelers){i.setFromMatrixPosition(s.matrixWorld),i.project(this.camera);const l=(i.x+1)/2*r,c=(i.y+1)/2*a;let d=0,f=1;typeof this.clipArea=="number"?f=this.clipArea:this.clipArea.endsWith("%")?f=parseFloat(this.clipArea)/100:this.clipArea.endsWith("px")&&(d=parseFloat(this.clipArea));const h=s.scale.x*f+.5,m=s.scale.y*f+.5,g=l-h/2,C=c-m/2,x=(g*this.qualityFactor-d)/o,R=(C*this.qualityFactor-d)/o,D=(h*this.qualityFactor+d*2)/o,k=(m*this.qualityFactor+d*2)/o;this.renderer.setScissor(x,R,D,k),this.renderer.render(this.scene,this.camera)}this.renderer.setScissorTest(!1),this.renderer.autoClear=!0,this.renderer.setRenderTarget(null),this.camera.layers.set(0),this.renderer.setClearColor(e,t)}render(){this.renderTarget&&this.captureRenderTarget(),this.renderer.render(this.scene,this.camera)}showScissoredRenderTarget(){if(!this.renderTarget)return;const e=this.targetRect.width,t=this.targetRect.height,i=new p.PlaneGeometry(e,t),r=new p.MeshBasicMaterial({map:this.renderTarget.texture,side:p.DoubleSide,transparent:!0,opacity:.8}),a=new p.Mesh(i,r);a.position.set(0,0,90),a.layers.set(28),this.scene.add(a)}}function Ee(n){const e=n.textContent||"",t=[];let i="",r=null,a=-1;const o=(c,d)=>{for(let f=0;f<c.length;f++){const h=c[f],m=document.createRange();m.setStart(n,d+f),m.setEnd(n,d+f+1);const g=m.getBoundingClientRect();if(g.width===0&&g.height===0){i+=h;continue}a===-1||Math.abs(g.top-a)>g.height/2?(i&&r&&t.push({text:i,rect:{left:r.left,top:r.top,width:r.right-r.left,height:r.bottom-r.top}}),i=h,r={left:g.left,top:g.top,right:g.right,bottom:g.bottom},a=g.top):(i+=h,r&&(r.left=Math.min(r.left,g.left),r.top=Math.min(r.top,g.top),r.right=Math.max(r.right,g.right),r.bottom=Math.max(r.bottom,g.bottom)))}},s=e.match(/[^\s\-]+\-?|\-|\s+/g)||[];let l=0;for(const c of s){const d=document.createRange();d.setStart(n,l),d.setEnd(n,l+c.length);const f=d.getClientRects();if(f.length>1)o(c,l);else{const h=f.length===1?f[0]:d.getBoundingClientRect();if(h.width===0&&h.height===0){i+=c,l+=c.length;continue}a===-1||Math.abs(h.top-a)>h.height/2?(i&&r&&t.push({text:i,rect:{left:r.left,top:r.top,width:r.right-r.left,height:r.bottom-r.top}}),i=c,r={left:h.left,top:h.top,right:h.right,bottom:h.bottom},a=h.top):(i+=c,r&&(r.left=Math.min(r.left,h.left),r.top=Math.min(r.top,h.top),r.right=Math.max(r.right,h.right),r.bottom=Math.max(r.bottom,h.bottom)))}l+=c.length}return i&&r&&t.push({text:i,rect:{left:r.left,top:r.top,width:r.right-r.left,height:r.bottom-r.top}}),t.filter(c=>c.text.trim().length>0&&c.rect.width>0&&c.rect.height>0)}function De(n){const e=parseFloat(n.fontSize);let t=parseFloat(n.lineHeight);isNaN(t)&&(t=e*1.2);let i=parseFloat(n.letterSpacing);return isNaN(i)&&(i=0),{font:`${n.fontStyle} ${n.fontWeight} ${n.fontSize} ${n.fontFamily}`,fontSize:n.fontSize,color:n.color,textAlign:n.textAlign||"start",textBaseline:"alphabetic",direction:n.direction||"inherit",lineHeight:t,letterSpacing:i}}function ne(n,e=I|z|P|A|E,t,i){if(n.nodeType===Node.TEXT_NODE){const b=n;if(!b.textContent||!b.textContent.trim())return null;const w=b.textContent.replace(/\s+/g," ");if(w.length===0)return null;const O=Ee(b);if(O.length===0)return null;const X=b.parentElement,Y=X?window.getComputedStyle(X):null;if(!Y)return null;const G=Math.min(...O.map(y=>y.rect.left)),q=Math.min(...O.map(y=>y.rect.top)),H=Math.max(...O.map(y=>y.rect.left+y.rect.width)),V=Math.max(...O.map(y=>y.rect.top+y.rect.height));return{id:Math.random().toString(36).substring(2,9),type:"TEXT",element:b,rect:{x:G+window.scrollX,y:q+window.scrollY,width:H-G,height:V-q},styles:{backgroundColor:"transparent",backgroundImage:"",opacity:X&&X.dataset.mirageDom==="hide"?1:parseFloat(Y.opacity),zIndex:0,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},textContent:w,textLines:O.map(y=>({text:y.text.trim(),rect:{x:y.rect.left+window.scrollX,y:y.rect.top+window.scrollY,width:y.rect.width,height:y.rect.height}})),textStyles:De(Y),dirtyMask:e,visibility:t,isTraveler:!1,isFixed:Y.position==="fixed",children:[]}}if(n.nodeType!==Node.ELEMENT_NODE)return null;const r=n,a=r.dataset.mirageFilter;let o=t,s=t;if(a){const b=new Set(a.split(/\s+/));for(const w of b)if(!ee.includes(w))throw new Error(`[MirageEngine] Invalid filter token: '${w}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(b.has("end"))return null;if(b.has("include-tree")&&b.has("exclude-tree"))throw new Error("[MirageEngine] Conflicting filters: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(b.has("include-self")&&b.has("exclude-self"))throw new Error("[MirageEngine] Conflicting filters: 'include-self' and 'exclude-self' cannot be used together on the same element.");b.has("include-tree")?o=o|B:b.has("exclude-tree")&&(o=o&~B),s=o,b.has("include-self")?s=s|B:b.has("exclude-self")&&(s=s&~B)}s=s|t&_;const l=r.dataset.mirageTravel;let c=!1;l&&new Set(l.split(/\s+/)).has("traveler")&&(s=s&~_,o=o&~_,c=!0);const d=r.dataset.mirageShader;let f;d&&(f=JSON.parse(d));const h=r.getBoundingClientRect(),m=window.getComputedStyle(r);if(h.width===0||h.height===0||m.display==="none")return null;let g=r.getAttribute("data-mid");g||(g=Math.random().toString(36).substring(2,11),r.setAttribute("data-mid",g));const C=parseInt(m.zIndex);let x;if(r.tagName==="IMG")x=r.src;else if(m.backgroundImage&&m.backgroundImage!=="none"){const b=m.backgroundImage.match(/url\(['"]?(.*?)['"]?\)/);b&&(x=b[1])}const R={backgroundColor:m.backgroundColor,backgroundImage:m.backgroundImage,opacity:r.dataset.mirageDom==="hide"?1:parseFloat(m.opacity),zIndex:isNaN(C)?0:C,borderRadius:m.borderRadius,borderColor:m.borderColor,borderWidth:m.borderWidth,imageSrc:x,isTraveler:c};let D,k;const F=[];return Array.from(r.childNodes).forEach(b=>{const w=b.nodeType===Node.TEXT_NODE?s:o,O=ne(b,e,w);O&&F.push(O)}),{id:g,type:"BOX",element:r,rect:{x:h.left+window.scrollX,y:h.top+window.scrollY,width:h.width,height:h.height},styles:R,textContent:D,textStyles:k,dirtyMask:e,visibility:s,isTraveler:c,isFixed:m.position==="fixed",children:F,shaderHooks:f}}function Oe(n,e){e.size!==0&&e.forEach((t,i)=>{var b,w,O,X,Y,G,q,H,V,y,oe,se,ae,ce,le,he,de,ue;const r=n.get(i);if(!r||!r.userData.basePosition)return;let{x:a,y:o}=r.userData.basePosition;const{width:s,height:l}=r.userData.baseSize,c=(b=t.width)!=null?b:s,d=(w=t.height)!=null?w:l,f=c-s,h=d-l;if(t.width!==void 0&&r.userData.originRatioX===void 0&&Math.abs(f)>.1){const J=i.getBoundingClientRect(),Z=(O=t.x)!=null?O:0,Q=(Y=(X=r.userData.baseTransform)==null?void 0:X.x)!=null?Y:0,K=r.userData.isFixed?0:window.scrollX;let S=-(J.left+K-Z+Q-r.userData.baseDOM.x)/f;Math.abs(S)<.05?S=0:Math.abs(S-1)<.05?S=1:Math.abs(S-.5)<.05&&(S=.5),r.userData.originRatioX=S}if(t.height!==void 0&&r.userData.originRatioY===void 0&&Math.abs(h)>.1){const J=i.getBoundingClientRect(),Z=(G=t.y)!=null?G:0,Q=(H=(q=r.userData.baseTransform)==null?void 0:q.y)!=null?H:0,K=r.userData.isFixed?0:window.scrollY;let S=-(J.top+K-Z+Q-r.userData.baseDOM.y)/h;Math.abs(S)<.05?S=0:Math.abs(S-1)<.05?S=1:Math.abs(S-.5)<.05&&(S=.5),r.userData.originRatioY=S}const m=(V=r.userData.originRatioX)!=null?V:.5,g=(y=r.userData.originRatioY)!=null?y:.5,C=f*(.5-m),x=h*(.5-g),R=(se=(oe=r.userData.baseTransform)==null?void 0:oe.x)!=null?se:0,D=(ce=(ae=r.userData.baseTransform)==null?void 0:ae.y)!=null?ce:0,k=((le=t.x)!=null?le:R)-R,F=((he=t.y)!=null?he:D)-D;r.position.setX(a+C+k),r.position.setY(o-(x+F)),r.scale.set(c,d,1),W.forceUpdateUniforms(r.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(ue=t.borderRadius)!=null?ue:(de=r.userData.baseStyles)==null?void 0:de.borderRadius,width:c,height:d})})}function ke(n,e,t){n.forEach(i=>{if(i.userData.isFixed&&i.userData.initialScroll&&i.userData.originalBasePosition){const r=e-i.userData.initialScroll.x,a=t-i.userData.initialScroll.y;i.userData.basePosition.x=i.userData.originalBasePosition.x+r,i.userData.basePosition.y=i.userData.originalBasePosition.y-a,i.position.x=i.userData.basePosition.x,i.position.y=i.userData.basePosition.y}})}function Ie(n){const e={};if(n.opacity&&(e.opacity=parseFloat(n.opacity)),n.backgroundColor&&n.backgroundColor!=="rgba(0, 0, 0, 0)"){const t=U(n.backgroundColor);e.backgroundColor=[t.color.r,t.color.g,t.color.b]}if(n.backgroundImage?e.backgroundImage=n.backgroundImage:n.background&&(e.backgroundImage=n.background),n.borderRadius&&(e.borderRadius=parseFloat(n.borderRadius)),n.width&&(e.width=parseFloat(n.width)),n.height&&(e.height=parseFloat(n.height)),n.transform&&n.transform!=="none"){const t=new DOMMatrix(n.transform);e.x=t.m41,e.y=t.m42,e.z=t.m43}return e}class Be{constructor(e,t,i,r){u(this,"target");u(this,"renderer");u(this,"registry");u(this,"filter");u(this,"observer");u(this,"pendingDeletions",new Set);u(this,"pendingStyles",new Map);u(this,"isDomDirty",!1);u(this,"isRunning",!1);u(this,"isTravelEnabled",!1);u(this,"pendingMask",L);u(this,"mutationTimer",null);u(this,"cssTimer",null);u(this,"resizeConfig");u(this,"resizeTimer",null);u(this,"isResizing",!1);u(this,"lastScrollX",0);u(this,"lastScrollY",0);u(this,"scrollTimer",null);u(this,"onTransitionFinished",e=>{this.target.contains(e.target)&&this.mutationTimer===null&&(this.cssTimer&&clearTimeout(this.cssTimer),this.pendingStyles.size==0&&(this.pendingMask|=I|z,this.cssTimer=window.setTimeout(()=>{this.isDomDirty=!0,this.cssTimer=null},50)))});u(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)});u(this,"renderLoop",()=>{if(!this.isRunning)return;this.isDomDirty&&this.forceUpdateScene();const e=window.scrollX,t=window.scrollY;(e!==this.lastScrollX||t!==this.lastScrollY)&&(ke(this.renderer.fixedMeshes,e,t),this.lastScrollX=e,this.lastScrollY=t,this.scrollTimer&&clearTimeout(this.scrollTimer),this.scrollTimer=window.setTimeout(()=>{this.pendingMask|=I,this.isDomDirty=!0,this.scrollTimer=null},150)),this.pendingStyles.size>0&&(Oe(this.registry,this.pendingStyles),this.pendingStyles.clear()),this.renderer.render(),requestAnimationFrame(this.renderLoop)});var o,s;this.target=e,this.renderer=t,this.registry=i,this.filter=r.filter;const a=(o=r.resizeDebounce)!=null?o:!0;a===!1?this.resizeConfig={enabled:!1,delay:0}:a===!0?this.resizeConfig={enabled:!0,delay:150}:this.resizeConfig={enabled:!0,delay:(s=a.delay)!=null?s:150,onStart:a.onStart,onEnd:a.onEnd},this.observer=new MutationObserver(l=>{let c=L;for(const d of l)if(d.type==="childList")c|=E,d.removedNodes.length>0&&d.removedNodes.forEach(f=>{f instanceof HTMLElement&&this.pendingDeletions.add(f)});else if(d.type==="attributes")if(d.attributeName==="style"){c|=I|z;const f=d.target,h=Ie(f.style);this.pendingStyles.set(f,h)}else d.attributeName==="class"&&(c|=I|z);else d.type==="characterData"&&(c|=A|I);if(c!==L){if(this.pendingMask|=c,c&E){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.forceUpdateScene(),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)}forceUpdateScene(){this.isDomDirty=!1,this.lastScrollX=window.scrollX,this.lastScrollY=window.scrollY;const e=document.querySelector("[data-mirage-travel='traveler']")!==null;e&&!this.isTravelEnabled&&(this.isTravelEnabled=!0,this.renderer.createRenderTarget());const t=ne(this.target,this.pendingMask,e?B|_:B,this.filter);t&&(this.renderer.syncScene(t,this.pendingDeletions),this.pendingDeletions.clear()),this.pendingMask=L}}class Fe{constructor(){u(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 Le{constructor(e,t){u(this,"renderer");u(this,"syncer");u(this,"target");u(this,"registry");var r,a,o;if(this.target=e,this.registry=new Fe,!document.getElementById("mirage-engine-styles")){const s=document.createElement("style");s.id="mirage-engine-styles",s.textContent=`
146
- [data-mirage-dom="hide"] {
143
+ `,je=`vec4 texColor = texture2D(uTexture, resultUv);
144
+ baseColor = blendSrcOver(baseColor, texColor);`,Ie={vertexShader:He,fragmentShader:Ge},ye={declChunk:qe,uvChunk:$e,baseColorChunk:je};function Ke(s,e,t,i=null,r){var I;const c=i!==null||!!s.imageSrc;let n="";const o={};if(r!=null&&r.uniforms)for(const[C,T]of Object.entries(r.uniforms))typeof T=="number"?(n+=`uniform float ${C};
145
+ `,o[C]={value:T}):Array.isArray(T)?T.length===2?(n+=`uniform vec2 ${C};
146
+ `,o[C]={value:new v.Vector2(...T)}):T.length===3?(n+=`uniform vec3 ${C};
147
+ `,o[C]={value:new v.Vector3(...T)}):T.length===4&&(n+=`uniform vec4 ${C};
148
+ `,o[C]={value:new v.Vector4(...T)}):(n+=`uniform float ${C};
149
+ `,o[C]={value:T});const a=(c?ye.declChunk:"")+`
150
+ `+n,l=s.isTraveler?ye.uvChunk:`vec2 resultUv = vUv * uTextureRepeat + uTextureOffset;
151
+ `,h=c?l+((r==null?void 0:r.uvModifier)||""):"",f=c?ye.baseColorChunk:"",b=(r==null?void 0:r.colorModifier)||"",p=Ie.fragmentShader.replace("#INJECT_DECLARATIONS",a).replace("#INJECT_UV_MODIFIER",h).replace("#INJECT_BASE_COLOR",f).replace("#INJECT_COLOR_MODIFIER",b),u=ce(s.backgroundColor),g=ce(s.borderColor),S={uSize:{value:new v.Vector2(e,t)},uBgColor:{value:new v.Vector4(u.color.r,u.color.g,u.color.b,u.alpha)},uBorderColor:{value:new v.Vector4(g.color.r,g.color.g,g.color.b,g.alpha)},uBorderRadius:{value:new v.Vector4(0,0,0,0)},uBorderWidth:{value:te(s.borderWidth)},uOpacity:{value:(I=s.opacity)!=null?I: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)}};ke(S.uBorderRadius.value,s.borderRadius),c&&(S.uTexture.value=i);const k=new v.ShaderMaterial({uniforms:J(J({},S),o),vertexShader:Ie.vertexShader,fragmentShader:p,transparent:!0,side:v.FrontSide});return s.backgroundImage&&Ee(k,{backgroundImage:s.backgroundImage}),k}function Je(s,e,t,i,r){const c=te(e.borderWidth);Ee(s,{width:t,height:i,borderRadius:e.borderRadius,borderWidth:c,backgroundColor:e.backgroundColor,borderColor:e.borderColor,opacity:e.opacity,texture:r,backgroundImage:e.backgroundImage})}function Ee(s,e){var i,r,c;if(e.width!==void 0&&e.height!==void 0&&s.uniforms.uSize.value.set(e.width,e.height),e.borderRadius!==void 0&&ke(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=ce(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=ce(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:(i=s.uniforms.uTexture)==null?void 0:i.value;if(t&&(t.image instanceof ImageBitmap||t.image instanceof HTMLImageElement||t.image instanceof HTMLCanvasElement)){const n=t.image.width,o=t.image.height,a=(r=e.width)!=null?r:s.uniforms.uSize.value.x,l=(c=e.height)!=null?c:s.uniforms.uSize.value.y;if(n&&o&&a&&l){const h=n/o,f=a/l;if(h>f){const b=f/h;s.uniforms.uTextureRepeat.value.set(b,1),s.uniforms.uTextureOffset.value.set((1-b)/2,0)}else{const b=h/f;s.uniforms.uTextureRepeat.value.set(1,b),s.uniforms.uTextureOffset.value.set(0,(1-b)/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=We(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 a=n.stops[o];s.uniforms.uGradientColors.value[o].set(a.color.r,a.color.g,a.color.b,a.alpha),s.uniforms.uGradientStops.value[o]=a.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 ke(s,e){var o,a,l,h;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+/),i=te(t[0]),r=te((o=t[1])!=null?o:t[0]),c=te((a=t[2])!=null?a:t[0]),n=te((h=(l=t[3])!=null?l:t[1])!=null?h:t[0]);s.set(i,r,c,n)}const q={create(s,e,t,i,r,c=2,n=null,o){return s==="BOX"?Ke(e,i,r,n,o):s==="TEXT"?new Pe(t||"",e,i,r,c):new v.MeshBasicMaterial({visible:!1})},update(s,e,t,i,r,c,n=2,o){e==="BOX"?Je(s,t,r,c,o):e==="TEXT"&&s.updateText(i||"",t,r,c,n)},forceUpdateUniforms(s,e){Ee(s,e)}};class Ze{constructor(e){d(this,"observer");d(this,"textures",new WeakMap);d(this,"loadStatus",new WeakMap);d(this,"elementUrls",new WeakMap);d(this,"onUpdate");this.onUpdate=e,this.observer=new IntersectionObserver(t=>{for(const i of t){const r=i.target;i.isIntersecting?this.loadTexture(r):this.disposeTexture(r)}},{rootMargin:"300px"})}register(e,t){if(e.nodeType!==Node.ELEMENT_NODE)return;this.elementUrls.get(e)!==t&&(this.elementUrls.set(e,t),this.observer.unobserve(e),this.observer.observe(e))}unregister(e){e.nodeType===Node.ELEMENT_NODE&&this.observer.unobserve(e),this.disposeTexture(e),this.elementUrls.delete(e),this.loadStatus.delete(e)}loadTexture(e){return Xe(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 i;if(t.startsWith("data:image/svg+xml"))i=yield new Promise((c,n)=>{const o=new Image;o.onload=()=>c(o),o.onerror=n,o.src=t});else{const n=yield(yield fetch(t)).blob();i=yield createImageBitmap(n,{imageOrientation:"flipY"})}if(this.elementUrls.get(e)!==t){"close"in i&&i.close();return}const r=new v.Texture(i);i instanceof HTMLImageElement||(r.flipY=!1),r.colorSpace=v.LinearSRGBColorSpace,r.needsUpdate=!0,this.textures.set(e,r),this.onUpdate(e,r)}catch(i){console.warn("[MirageEngine] Failed to load texture:",t,i)}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.disconnect()}}class Qe{constructor(e,t,i,r){d(this,"canvas");d(this,"scene");d(this,"camera");d(this,"renderer");d(this,"renderTargets",[]);d(this,"renderOrder",0);d(this,"qualityFactor",2);d(this,"mode","overlay");d(this,"clipArea",1);d(this,"targetLayer","base");d(this,"target");d(this,"mountContainer");d(this,"registry");d(this,"targetRect");d(this,"travelersByLayer",Array.from({length:A.MAX_LAYERS},()=>new Set));d(this,"textureManager");d(this,"fixedMeshes",new Set);var o,a,l,h;this.target=e,this.mountContainer=i,this.registry=r,this.textureManager=new Ze((f,b)=>{const p=this.registry.get(f);p&&p.material instanceof v.ShaderMaterial&&q.forceUpdateUniforms(p.material,{texture:b})}),this.mode=(o=t.mode)!=null?o:"overlay",this.clipArea=(a=t.travelerClipArea)!=null?a:1,this.targetLayer=(l=t.layer)!=null?l:"base",this.canvas=document.createElement("canvas"),this.scene=new v.Scene,this.targetRect=this.target.getBoundingClientRect();const c=this.targetRect.width,n=this.targetRect.height;this.camera=new v.OrthographicCamera(c/-2,c/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(c,n),this.applyTextQuality((h=t.quality)!=null?h:"medium")}getSceneLayer(){return typeof this.targetLayer=="number"?this.targetLayer:this.targetLayer==="selected"?U.SELECTED:U.BASE}createRenderTarget(){for(let e=0;e<A.MAX_LAYERS;e++)this.renderTargets.push(new v.WebGLRenderTarget(this.targetRect.width*this.qualityFactor,this.targetRect.height*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(){this.canvas.style.width=`${this.targetRect.width}px`,this.canvas.style.height=`${this.targetRect.height}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="absolute",this.canvas.style.top=`${this.target.offsetTop}px`,this.canvas.style.left=`${this.target.offsetLeft}px`,this.canvas.style.display="block")}updateUniforms(e,t){const i=this.registry.get(e);i&&(i.traverse(r=>{r.isMesh&&r.material&&q.forceUpdateUniforms(r.material,t)}),i.userData.nativeMesh&&i.userData.nativeMesh.traverse(r=>{r.isMesh&&r.material&&q.forceUpdateUniforms(r.material,t)}))}dispose(){this.renderer.dispose(),this.canvas.remove(),this.textureManager.disposeAll()}setSize(e,t){this.renderer.setSize(e,t);for(const i of this.renderTargets)i.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 i=this.target.getBoundingClientRect(),r=Math.abs(i.width-this.targetRect.width)>.1||Math.abs(i.height-this.targetRect.height)>.1,c=this.mode==="overlay"&&(Math.abs(i.top-this.targetRect.top)>.1||Math.abs(i.left-this.targetRect.left)>.1);r?(this.targetRect=i,this.setSize(this.targetRect.width,this.targetRect.height),this.updateCanvasLayout()):c?(this.targetRect=i,this.updateCanvasLayout()):this.targetRect=i,this.renderOrder=0,this.reconcileNode(e),t.size>0&&t.forEach(n=>{const o=this.registry.get(n);if(o){this.scene.remove(o);for(const a of this.travelersByLayer)a.delete(o);this.fixedMeshes.delete(o),o.geometry.dispose(),o.userData.nativeMesh&&(this.scene.remove(o.userData.nativeMesh),Array.isArray(o.userData.nativeMesh.material)?o.userData.nativeMesh.material.forEach(a=>a.dispose()):o.userData.nativeMesh.material.dispose(),o.userData.nativeMesh.geometry.dispose()),o.traverse(a=>{a instanceof v.Mesh&&(a.geometry&&a.geometry.dispose(),a.material&&(Array.isArray(a.material)?a.material.forEach(l=>l.dispose()):a.material.dispose()))}),this.registry.remove(n),this.textureManager.unregister(n)}})}reconcileNode(e){var i;let t=this.registry.get(e.element);if(!t){const r=new v.PlaneGeometry(1,1),c=e.isTraveler?(i=this.renderTargets[e.captureLayer-2])==null?void 0:i.texture:this.textureManager.get(e.element),n=q.create("BOX",e.styles,"",e.rect.width,e.rect.height,this.qualityFactor,c,e.shaderHooks);t=new v.Mesh(r,n),e.type==="TEXT"&&(t.name="BG_MESH"),this.scene.add(t),this.registry.register(e.element,t),t.userData.baseMaterial=n}if(this.updateMeshProperties(t,e),this.updateMeshLayers(t,e),e.isTraveler)for(let r=0;r<A.MAX_LAYERS;r++)r===e.captureLayer-2?this.travelersByLayer[r].add(t):this.travelersByLayer[r].delete(t);else for(const r of this.travelersByLayer)r.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 r of e.children)this.reconcileNode(r);else e.type==="TEXT"&&(this.reconcileTextChild(t,e,!1),t.userData.nativeMesh&&e.nativeStyles&&this.reconcileTextChild(t.userData.nativeMesh,e,!0))}reconcileTextChild(e,t,i){var l;const r=t.textLines||[{text:t.textContent||"",rect:t.rect}],c=i?t.nativeStyles:t.textStyles,n=JSON.stringify(c)+t.textContent+r.map(h=>h.text).join("|"),o=(l=e.userData)==null?void 0:l.textChildStyleHash;if(t.dirtyMask&me||n!==o){e.children.filter(u=>u.name.startsWith("TEXT_CHILD")).forEach(u=>{var S;const g=u;(S=g.material.map)==null||S.dispose(),g.geometry.dispose(),e.remove(g)});const f=t.rect,b=f.x+f.width/2,p=f.y+f.height/2;r.forEach((u,g)=>{const S=q.create("TEXT",c,u.text,u.rect.width,u.rect.height,this.qualityFactor),k=new v.PlaneGeometry(1,1),I=new v.Mesh(k,S);I.name=`TEXT_CHILD_${g}`;const C=t.rect.width===0?1:u.rect.width/t.rect.width,T=t.rect.height===0?1:u.rect.height/t.rect.height;I.scale.set(C,T,1);const N=u.rect.x+u.rect.width/2,z=u.rect.y+u.rect.height/2,H=N-b,_=-(z-p);I.position.set(t.rect.width===0?0:H/t.rect.width,t.rect.height===0?0:_/t.rect.height,.005),e.add(I)}),e.userData.textChildStyleHash=n}e.children.forEach(h=>{if(!h.name.startsWith("TEXT_CHILD"))return;const f=h,b=t.visibility&W?U.BASE:U.HIDDEN;if(f.layers.set(b),t.visibility&Z&&f.layers.enable(U.SELECTED),t.visibility&W)if(!i&&t.nativeLayer!==void 0&&t.nativeStyles!==void 0)for(let p=t.captureLayer;p<t.nativeLayer;p++)f.layers.enable(U.getCaptureLayer(p));else if(i&&t.nativeLayer!==void 0)for(let p=Math.max(t.captureLayer,t.nativeLayer);p<=A.MAX_LAYERS+1;p++)f.layers.enable(U.getCaptureLayer(p));else for(let p=t.captureLayer;p<=A.MAX_LAYERS+1;p++)f.layers.enable(U.getCaptureLayer(p))})}updateMeshProperties(e,t){var N,z,H;const{rect:i,styles:r}=t,c=this.renderer.getPixelRatio(),n=this.renderer.domElement.width/c,o=this.renderer.domElement.height/c;e.material=e.userData.baseMaterial,e.scale.set(i.width,i.height,1),e.userData.domRect=Se(J({},i),{width:i.width,height:i.height});const a=.001;this.renderOrder++;const l=this.targetRect.left+window.scrollX,h=this.targetRect.top+window.scrollY,f=i.x-l,b=i.y-h,p=f-n/2+i.width/2,u=-b+o/2-i.height/2;e.position.set(p,u,r.zIndex+this.renderOrder*a);const g=i.x,S=i.y;e.userData.basePosition={x:p,y:u},e.userData.originalBasePosition={x:p,y:u},e.userData.baseSize={width:i.width,height:i.height},e.userData.baseDOM={x:g,y:S},e.userData.isFixed=t.isFixed,e.userData.initialScroll={x:window.scrollX,y:window.scrollY};const k=t.element.nodeType===Node.TEXT_NODE?t.element.parentElement:t.element,I=window.getComputedStyle(k);let C=0,T=0;if(I.transform&&I.transform!=="none"){const _=new DOMMatrix(I.transform);C=_.m41,T=_.m42}if(e.userData.baseTransform={x:C,y:T},delete e.userData.originRatioX,delete e.userData.originRatioY,q.update(e.userData.baseMaterial,"BOX",r,"",i.width,i.height,this.qualityFactor,t.isTraveler?(N=this.renderTargets[t.captureLayer-2])==null?void 0:N.texture:this.textureManager.get(t.element)),t.nativeStyles&&t.nativeRect){if(!e.userData.nativeMesh){const Q=q.create("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),t.shaderHooks),$=new v.Mesh(e.geometry,Q);t.type==="TEXT"&&($.name="BG_MESH"),this.scene.add($),e.userData.nativeMesh=$}const _=e.userData.nativeMesh,B=t.nativeRect.x-l,re=t.nativeRect.y-h,ie=B-n/2+t.nativeRect.width/2,se=-re+o/2-t.nativeRect.height/2;_.scale.set(t.nativeRect.width,t.nativeRect.height,1),_.position.set(ie,se,t.nativeStyles.zIndex+this.renderOrder*a),q.update(_.material,"BOX",t.nativeStyles,"",t.nativeRect.width,t.nativeRect.height,this.qualityFactor,t.isTraveler?(H=this.renderTargets[t.captureLayer-2])==null?void 0:H.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 i=t.visibility&W?U.BASE:U.HIDDEN;if(e.layers.set(i),t.visibility&Z&&e.layers.enable(U.SELECTED),e.userData.nativeMesh&&t.nativeLayer!==void 0){const r=e.userData.nativeMesh;if(r.layers.set(U.HIDDEN),t.visibility&W){for(let c=t.captureLayer;c<t.nativeLayer;c++)e.layers.enable(U.getCaptureLayer(c));for(let c=Math.max(t.captureLayer,t.nativeLayer);c<=A.MAX_LAYERS+1;c++)r.layers.enable(U.getCaptureLayer(c))}}else if(t.visibility&W)for(let r=t.captureLayer;r<=A.MAX_LAYERS+1;r++)e.layers.enable(U.getCaptureLayer(r))}captureRenderTarget(e,t,i){if(e.size===0||!i)return;const r=new v.Color,c=this.renderer.getClearAlpha();this.renderer.getClearColor(r),this.renderer.setClearColor(0,0),this.renderer.setRenderTarget(i),this.renderer.clear(),this.renderer.autoClear=!1,this.renderer.setScissorTest(!0),this.camera.layers.set(t);const n=new v.Vector3,o=this.targetRect.width,a=this.targetRect.height,l=this.renderer.getPixelRatio();for(const h of e){n.setFromMatrixPosition(h.matrixWorld),n.project(this.camera);const f=(n.x+1)/2*o,b=(n.y+1)/2*a;let p=0,u=1;typeof this.clipArea=="number"?u=this.clipArea:this.clipArea.endsWith("%")?u=parseFloat(this.clipArea)/100:this.clipArea.endsWith("px")&&(p=parseFloat(this.clipArea));const g=h.scale.x*u+.5,S=h.scale.y*u+.5,k=f-g/2,I=b-S/2,C=(k*this.qualityFactor-p)/l,T=(I*this.qualityFactor-p)/l,N=(g*this.qualityFactor+p*2)/l,z=(S*this.qualityFactor+p*2)/l;this.renderer.setScissor(C,T,N,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(r,c)}render(){for(let e=0;e<A.MAX_LAYERS;e++){const t=e+1;this.captureRenderTarget(this.travelersByLayer[e],U.getCaptureLayer(t),this.renderTargets[e])}this.renderer.render(this.scene,this.camera)}}function et(s){const e=s.textContent||"",t=[];let i="",r=null,c=-1;const n=(l,h)=>{for(let f=0;f<l.length;f++){const b=l[f],p=document.createRange();p.setStart(s,h+f),p.setEnd(s,h+f+1);const u=p.getBoundingClientRect();if(u.width===0&&u.height===0){i+=b;continue}c===-1||Math.abs(u.top-c)>u.height/2?(i&&r&&t.push({text:i,rect:{left:r.left,top:r.top,width:r.right-r.left,height:r.bottom-r.top}}),i=b,r={left:u.left,top:u.top,right:u.right,bottom:u.bottom},c=u.top):(i+=b,r&&(r.left=Math.min(r.left,u.left),r.top=Math.min(r.top,u.top),r.right=Math.max(r.right,u.right),r.bottom=Math.max(r.bottom,u.bottom)))}},o=e.match(/[^\s\-]+\-?|\-|\s+/g)||[];let a=0;for(const l of o){const h=document.createRange();h.setStart(s,a),h.setEnd(s,a+l.length);const f=h.getClientRects();if(f.length>1)n(l,a);else{const b=f.length===1?f[0]:h.getBoundingClientRect();if(b.width===0&&b.height===0){i+=l,a+=l.length;continue}c===-1||Math.abs(b.top-c)>b.height/2?(i&&r&&t.push({text:i,rect:{left:r.left,top:r.top,width:r.right-r.left,height:r.bottom-r.top}}),i=l,r={left:b.left,top:b.top,right:b.right,bottom:b.bottom},c=b.top):(i+=l,r&&(r.left=Math.min(r.left,b.left),r.top=Math.min(r.top,b.top),r.right=Math.max(r.right,b.right),r.bottom=Math.max(r.bottom,b.bottom)))}a+=l.length}return i&&r&&t.push({text:i,rect:{left:r.left,top:r.top,width:r.right-r.left,height:r.bottom-r.top}}),t.filter(l=>l.text.trim().length>0&&l.rect.width>0&&l.rect.height>0)}function Oe(s){const e=parseFloat(s.fontSize);let t=parseFloat(s.lineHeight);isNaN(t)&&(t=e*1.2);let i=parseFloat(s.letterSpacing);return isNaN(i)&&(i=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:i}}function Ue(s,e=K|ee|Le|me|pe,t,i=1,r=0,c=2,n,o){var $,le,he,ue,de,fe;if(s.nodeType===Node.TEXT_NODE){const m=s;if(!m.textContent||!m.textContent.trim())return null;const R=m.textContent.replace(/\s+/g," ");if(R.length===0)return null;const O=et(m);if(O.length===0)return null;const X=m.parentElement,L=X?window.getComputedStyle(X):null;if(!L)return null;const Y=Math.min(...O.map(E=>E.rect.left)),x=Math.min(...O.map(E=>E.rect.top)),P=Math.max(...O.map(E=>E.rect.left+E.rect.width)),j=Math.max(...O.map(E=>E.rect.top+E.rect.height));return{id:Math.random().toString(36).substring(2,9),type:"TEXT",element:m,rect:{x:Y+window.scrollX,y:x+window.scrollY,width:P-Y,height:j-x},styles:{backgroundColor:"transparent",backgroundImage:"",opacity:X&&X.dataset[V.KEY]===V.VALUES.HIDE?1:parseFloat(L.opacity),zIndex:(isNaN(parseInt(L.zIndex))?0:parseInt(L.zIndex))+r,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},textContent:R,textLines:O.map(E=>({text:E.text.trim(),rect:{x:E.rect.left+window.scrollX,y:E.rect.top+window.scrollY,width:E.rect.width,height:E.rect.height}})),textStyles:Oe(L),dirtyMask:e,visibility:t,isTraveler:!1,captureLayer:i,isFixed:L.position==="fixed",nativeLayer:n,nativeStyles:o?J(J({backgroundColor:"transparent",backgroundImage:"",opacity:X&&X.dataset[V.KEY]===V.VALUES.HIDE?1:parseFloat(L.opacity),zIndex:(isNaN(parseInt(L.zIndex))?0:parseInt(L.zIndex))+r,borderRadius:"0px",borderColor:"transparent",borderWidth:"0px",isTraveler:!1},Oe(L)),o):void 0,nativeRect:o?{x:Y+window.scrollX,y:x+window.scrollY,width:P-Y,height:j-x}:void 0,children:[]}}if(s.nodeType!==Node.ELEMENT_NODE)return null;const a=s,l=a.dataset[D.KEY];let h=t,f=t;if(l){const m=new Set(l.split(/\s+/));for(const R of m)if(!ve.includes(R))throw new Error(`[MirageEngine] Invalid filter token: '${R}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(m.has(D.VALUES.END))return null;if(m.has(D.VALUES.INCLUDE_TREE)&&m.has(D.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting filters: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(m.has(D.VALUES.INCLUDE_SELF)&&m.has(D.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting filters: 'include-self' and 'exclude-self' cannot be used together on the same element.");m.has(D.VALUES.INCLUDE_TREE)?h=h|W:m.has(D.VALUES.EXCLUDE_TREE)&&(h=h&~W),f=h,m.has(D.VALUES.INCLUDE_SELF)?f=f|W:m.has(D.VALUES.EXCLUDE_SELF)&&(f=f&~W)}const b=a.dataset[F.KEY];if(b){const m=new Set(b.split(/\s+/));for(const R of m)if(!ve.includes(R))throw new Error(`[MirageEngine] Invalid select token: '${R}'. Expected one of: 'include-tree', 'exclude-tree', 'include-self', 'exclude-self', 'end'.`);if(m.has(F.VALUES.END))return null;if(m.has(F.VALUES.INCLUDE_TREE)&&m.has(F.VALUES.EXCLUDE_TREE))throw new Error("[MirageEngine] Conflicting selects: 'include-tree' and 'exclude-tree' cannot be used together on the same element.");if(m.has(F.VALUES.INCLUDE_SELF)&&m.has(F.VALUES.EXCLUDE_SELF))throw new Error("[MirageEngine] Conflicting selects: 'include-self' and 'exclude-self' cannot be used together on the same element.");m.has(F.VALUES.INCLUDE_TREE)?h=h|Z:m.has(F.VALUES.EXCLUDE_TREE)&&(h=h&~Z),f=h,m.has(F.VALUES.INCLUDE_SELF)?f=f|Z:m.has(F.VALUES.EXCLUDE_SELF)&&(f=f&~Z)}const p=a.dataset[A.KEY];let u=!1,g=o?J({},o):{},S=n;if(p){let m=1;const R=p.indexOf("{"),O=p.lastIndexOf("}");let X=p;if(R!==-1&&O!==-1&&O>R){X=p.substring(0,R).trim();const x=p.substring(R,O+1);try{g=new Function("return "+x)()}catch(P){console.warn(`[MirageEngine] Failed to parse travel styles JSON: ${x}`)}}const L=X.split(/\s+/);let Y=!1;if(L.includes(A.VALUES.TRAVELER)){u=!0,Y=!0;const x=L.find(P=>!isNaN(parseInt(P,10)));x&&(m=parseInt(x,10))}else if(L.includes(A.VALUES.NATIVE)){u=!1;const x=L.find(P=>!isNaN(parseInt(P,10)));x&&(S=parseInt(x,10))}if(Y){const x=m+1;if(x<i)throw new Error(`[MirageEngine] Traveler layer (${m}) cannot be smaller than inherited capture layer (${i-1}).`);i=Math.min(x,A.MAX_LAYERS+1)}}const k=a.dataset[Re.KEY];let I;k&&(I=JSON.parse(k));const C=a.getBoundingClientRect(),T=window.getComputedStyle(a);if(C.width===0||C.height===0||T.display==="none")return null;let N=a.getAttribute("data-mid");N||(N=Math.random().toString(36).substring(2,11),a.setAttribute("data-mid",N));const z=parseInt(T.zIndex),H=(isNaN(z)?0:z)+r;let _;if(a.tagName==="IMG")_=a.src;else if(a.tagName.toLowerCase()==="svg"){const m=a.cloneNode(!0),R=g==null?void 0:g.color,O=g==null?void 0:g.fill,X=g==null?void 0:g.stroke,L=g==null?void 0:g.opacity,Y=(E,_e)=>{const G=window.getComputedStyle(E),ge=_e,ot=G.fill===G.color,at=G.stroke===G.color,Te=O||(ot?R:void 0)||G.fill;Te&&Te!=="none"&&(ge.style.fill=Te);const Ce=X||(at?R:void 0)||G.stroke;Ce&&Ce!=="none"&&(ge.style.stroke=Ce),G.strokeWidth&&G.strokeWidth!=="0px"&&(ge.style.strokeWidth=G.strokeWidth);const Fe=R||G.color;Fe&&(ge.style.color=Fe);const xe=L||G.opacity;xe&&xe!=="1"&&(ge.style.opacity=xe);for(let be=0;be<E.children.length;be++)Y(E.children[be],_e.children[be])};Y(a,m);const x=a.getBoundingClientRect(),P=window.devicePixelRatio*c;m.hasAttribute("viewBox")||m.setAttribute("viewBox",`0 0 ${x.width} ${x.height}`),m.setAttribute("width",(x.width*P).toString()),m.setAttribute("height",(x.height*P).toString());let j=new XMLSerializer().serializeToString(m);j.includes("xmlns=")||(j=j.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),_=`data:image/svg+xml;utf8,${encodeURIComponent(j)}`}else if(T.backgroundImage&&T.backgroundImage!=="none"){const m=T.backgroundImage.match(/url\(['"]?(.*?)['"]?\)/);m&&(_=m[1])}const B={backgroundColor:T.backgroundColor,backgroundImage:T.backgroundImage,opacity:a.dataset[V.KEY]===V.VALUES.HIDE?1:parseFloat(T.opacity),zIndex:H,borderRadius:T.borderRadius,borderColor:T.borderColor,borderWidth:T.borderWidth,imageSrc:_,isTraveler:u},re=B;let ie,se;const Q=[];return a.tagName.toLowerCase()!=="svg"&&Array.from(a.childNodes).forEach(m=>{const R=m.nodeType===Node.TEXT_NODE?f:h,O=Ue(m,e,R,i,H,c,S,m.nodeType===Node.TEXT_NODE&&Object.keys(g).length>0?g:void 0);O&&Q.push(O)}),{id:N,type:"BOX",element:a,rect:{x:C.left+window.scrollX,y:C.top+window.scrollY,width:C.width,height:C.height},styles:re,textContent:ie,textStyles:se,dirtyMask:e,visibility:f,isTraveler:u,captureLayer:i,nativeLayer:S,nativeStyles:S!==void 0?Se(J({},B),{backgroundColor:($=g.backgroundColor)!=null?$:B.backgroundColor,backgroundImage:(le=g.backgroundImage)!=null?le:B.backgroundImage,opacity:(he=g.opacity)!=null?he:B.opacity,zIndex:g.zIndex!==void 0?g.zIndex+H:B.zIndex,borderRadius:(ue=g.borderRadius)!=null?ue:B.borderRadius,borderColor:(de=g.borderColor)!=null?de:B.borderColor,borderWidth:(fe=g.borderWidth)!=null?fe:B.borderWidth,isTraveler:B.isTraveler}):void 0,nativeRect:S!==void 0?{x:g.x!==void 0?parseFloat(g.x):C.left+window.scrollX,y:g.y!==void 0?parseFloat(g.y):C.top+window.scrollY,width:g.width!==void 0?parseFloat(g.width):C.width,height:g.height!==void 0?parseFloat(g.height):C.height}:void 0,isFixed:T.position==="fixed",children:Q,shaderHooks:I}}function tt(s,e){e.size!==0&&e.forEach((t,i)=>{var N,z,H,_,B,re,ie,se,Q,$,le,he,ue,de,fe,m,R,O;const r=s.get(i);if(!r||!r.userData.basePosition)return;let{x:c,y:n}=r.userData.basePosition;const{width:o,height:a}=r.userData.baseSize,l=(N=t.width)!=null?N:o,h=(z=t.height)!=null?z:a,f=l-o,b=h-a;if(t.width!==void 0&&r.userData.originRatioX===void 0&&Math.abs(f)>.1){const X=i.getBoundingClientRect(),L=(H=t.x)!=null?H:0,Y=(B=(_=r.userData.baseTransform)==null?void 0:_.x)!=null?B:0,x=r.userData.isFixed?0:window.scrollX;let E=-(X.left+x-L+Y-r.userData.baseDOM.x)/f;Math.abs(E)<.05?E=0:Math.abs(E-1)<.05?E=1:Math.abs(E-.5)<.05&&(E=.5),r.userData.originRatioX=E}if(t.height!==void 0&&r.userData.originRatioY===void 0&&Math.abs(b)>.1){const X=i.getBoundingClientRect(),L=(re=t.y)!=null?re:0,Y=(se=(ie=r.userData.baseTransform)==null?void 0:ie.y)!=null?se:0,x=r.userData.isFixed?0:window.scrollY;let E=-(X.top+x-L+Y-r.userData.baseDOM.y)/b;Math.abs(E)<.05?E=0:Math.abs(E-1)<.05?E=1:Math.abs(E-.5)<.05&&(E=.5),r.userData.originRatioY=E}const p=(Q=r.userData.originRatioX)!=null?Q:.5,u=($=r.userData.originRatioY)!=null?$:.5,g=f*(.5-p),S=b*(.5-u),k=(he=(le=r.userData.baseTransform)==null?void 0:le.x)!=null?he:0,I=(de=(ue=r.userData.baseTransform)==null?void 0:ue.y)!=null?de:0,C=((fe=t.x)!=null?fe:k)-k,T=((m=t.y)!=null?m:I)-I;r.position.setX(c+g+C),r.position.setY(n-(S+T)),r.scale.set(l,h,1),q.forceUpdateUniforms(r.material,{backgroundColor:t.backgroundColor,backgroundImage:t.backgroundImage,opacity:t.opacity,borderRadius:(O=t.borderRadius)!=null?O:(R=r.userData.baseStyles)==null?void 0:R.borderRadius,width:l,height:h})})}function rt(s,e,t){s.forEach(i=>{if(i.userData.isFixed&&i.userData.initialScroll&&i.userData.originalBasePosition){const r=e-i.userData.initialScroll.x,c=t-i.userData.initialScroll.y;i.userData.basePosition.x=i.userData.originalBasePosition.x+r,i.userData.basePosition.y=i.userData.originalBasePosition.y-c,i.position.x=i.userData.basePosition.x,i.position.y=i.userData.basePosition.y}})}class it{constructor(e,t,i,r){d(this,"target");d(this,"renderer");d(this,"registry");d(this,"isTravelEnabled",!1);d(this,"tracker");this.target=e,this.renderer=t,this.registry=i,this.tracker=new De(e,{resizeDebounce:r.resizeDebounce}),this.tracker.onLayoutChange.add((c,n)=>{document.querySelector(`[${A.NAME}~='${A.VALUES.TRAVELER}']`)!==null&&!this.isTravelEnabled&&(this.isTravelEnabled=!0,this.renderer.createRenderTarget());const a=Ue(this.target,c,W,1,0,this.renderer.qualityFactor);a&&this.renderer.syncScene(a,n)}),this.tracker.onScrollChange.add((c,n)=>{rt(this.renderer.fixedMeshes,c,n)}),this.tracker.onStyleChange.add(c=>{tt(this.registry,c)}),this.tracker.onRender.add(()=>{this.renderer.render()})}start(){this.tracker.start()}stop(){this.tracker.stop()}}class st{constructor(){d(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 nt{constructor(e,t){d(this,"renderer");d(this,"syncer");d(this,"target");d(this,"registry");var r,c,n;if(this.target=e,this.registry=new st,!document.getElementById("mirage-engine-styles")){const o=document.createElement("style");o.id="mirage-engine-styles",o.textContent=`
152
+ [${V.NAME}="${V.VALUES.HIDE}"] {
147
153
  opacity: 0 !important;
148
154
  }
149
- `,document.head.appendChild(s)}let i;if(t.mode==="duplicate"?i=(a=(r=t.container)!=null?r:this.target.parentElement)!=null?a:void 0:i=(o=this.target.parentElement)!=null?o:void 0,!i)throw new Error("[Mirage] Cannot find a container (parent or option).");this.renderer=new Me(this.target,t,i,this.registry),this.renderer.mount(),this.syncer=new Be(this.target,this.renderer,this.registry,t)}start(){this.syncer.start()}stop(){this.syncer.stop()}dispose(){this.syncer.stop(),this.renderer.dispose()}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 i=2,r=()=>{requestAnimationFrame(r),t.ArrowRight&&e.position.setX(e.position.x+i),t.ArrowLeft&&e.position.setX(e.position.x-i),t.ArrowUp&&e.position.setY(e.position.y+i),t.ArrowDown&&e.position.setY(e.position.y-i)};r()}}v.ALLOWED_FILTERS=ee,v.DIRTY_CONTENT=A,v.DIRTY_NONE=L,v.DIRTY_RECT=I,v.DIRTY_STRUCTURE=E,v.DIRTY_STYLE=z,v.DIRTY_ZINDEX=P,v.EXCLUDED=ge,v.Engine=Le,v.SYSTEM_LAYER=_,v.USER_LAYER=B,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})});
155
+ `,document.head.appendChild(o)}let i;if(t.mode==="duplicate"?i=(c=(r=t.container)!=null?r:this.target.parentElement)!=null?c:void 0:i=(n=this.target.parentElement)!=null?n:void 0,!i)throw new Error("[Mirage] Cannot find a container (parent or option).");this.renderer=new Qe(this.target,t,i,this.registry),this.renderer.mount(),this.syncer=new it(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",c=>{t[c.key]!==void 0&&(t[c.key]=!0)}),window.addEventListener("keyup",c=>{t[c.key]!==void 0&&(t[c.key]=!1)});const i=2,r=()=>{requestAnimationFrame(r),t.ArrowRight&&e.position.setX(e.position.x+i),t.ArrowLeft&&e.position.setX(e.position.x-i),t.ArrowUp&&e.position.setY(e.position.y+i),t.ArrowDown&&e.position.setY(e.position.y-i)};r()}}y.ALLOWED_FILTERS=ve,y.ATTR_DOM=V,y.ATTR_FILTER=D,y.ATTR_SANDWICH=Ne,y.ATTR_SELECT=F,y.ATTR_SHADER=Re,y.ATTR_TRAVEL=A,y.DIRTY_CONTENT=me,y.DIRTY_NONE=ae,y.DIRTY_RECT=K,y.DIRTY_STRUCTURE=pe,y.DIRTY_STYLE=ee,y.DIRTY_ZINDEX=Le,y.EXCLUDED=ze,y.Engine=nt,y.SELECT_LAYER=Z,y.THREE_LAYERS=U,y.TRAVEL_VALUES=oe,y.Tracker=De,y.USER_LAYER=W,y.extractFromStyle=Me,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
@@ -1,11 +1,6 @@
1
- import { StyleData } from '../types';
1
+ import { StyleData } from '@mirage-engine/dom-tracker';
2
2
  import { MeshRegistry } from '../store/MeshRegistry';
3
3
 
4
4
  import * as THREE from "three";
5
5
  export declare function animateMeshByData(registry: MeshRegistry, data: Map<HTMLElement, StyleData>): void;
6
- export declare function animateMeshByAttribute(_target: HTMLElement, _options: {
7
- duration: number;
8
- easing?: string;
9
- }): void;
10
6
  export declare function updateFixedMeshesScroll(fixedMeshes: Set<THREE.Mesh>, currentScrollX: number, currentScrollY: number): void;
11
- export declare function extractFromStyle(style: CSSStyleDeclaration): StyleData;
@@ -9,5 +9,8 @@ export declare class Engine {
9
9
  start(): void;
10
10
  stop(): void;
11
11
  dispose(): void;
12
+ getTracker(): import('@mirage-engine/dom-tracker').Tracker;
13
+ updateUniforms(element: HTMLElement, uniforms: Record<string, any>): void;
14
+ getCanvas(): HTMLCanvasElement;
12
15
  test(): void;
13
16
  }
@@ -1,33 +1,15 @@
1
1
  import { CoreConfig } from '../types/config';
2
2
  import { Renderer } from '../renderer/Renderer';
3
3
  import { MeshRegistry } from '../store/MeshRegistry';
4
+ import { Tracker } from '@mirage-engine/dom-tracker';
4
5
 
5
6
  export declare class Syncer {
6
7
  private target;
7
8
  private renderer;
8
9
  private registry;
9
- private filter;
10
- private observer;
11
- private pendingDeletions;
12
- private pendingStyles;
13
- private isDomDirty;
14
- private isRunning;
15
10
  private isTravelEnabled;
16
- private pendingMask;
17
- private mutationTimer;
18
- private cssTimer;
19
- private resizeConfig;
20
- private resizeTimer;
21
- private isResizing;
22
- private lastScrollX;
23
- private lastScrollY;
24
- private scrollTimer;
11
+ tracker: Tracker;
25
12
  constructor(target: HTMLElement, renderer: Renderer, registry: MeshRegistry, config: CoreConfig);
26
13
  start(): void;
27
14
  stop(): void;
28
- private clearTimers;
29
- private onTransitionFinished;
30
- private onWindowResize;
31
- private forceUpdateScene;
32
- private renderLoop;
33
15
  }
@@ -1,4 +1,3 @@
1
1
  import { SceneNode, Visibility } from '../types';
2
- import { FilterConfig } from '../types/config';
3
2
 
4
- export declare function extractSceneGraph(sourceNode: HTMLElement | Node, initialMask: number | undefined, inheritedFlow: Visibility, filterConfig?: FilterConfig): SceneNode | null;
3
+ export declare function extractSceneGraph(sourceNode: HTMLElement | Node, initialMask: number | undefined, inheritedFlow: Visibility, captureLayer?: number, inheritedZIndex?: number, qualityFactor?: number, inheritedNativeLayer?: number, inheritedNativeStyles?: any): SceneNode | null;
@@ -1,4 +1,4 @@
1
- import { SceneNode, CoreConfig } from '../types';
1
+ import { SceneNode, CoreConfig, LayerTarget } from '../types';
2
2
  import { MeshRegistry } from '../store/MeshRegistry';
3
3
  import * as THREE from "three";
4
4
  export declare class Renderer {
@@ -6,23 +6,26 @@ export declare class Renderer {
6
6
  private readonly scene;
7
7
  private readonly camera;
8
8
  private readonly renderer;
9
- private renderTarget;
9
+ private renderTargets;
10
10
  private renderOrder;
11
- private qualityFactor;
11
+ qualityFactor: number;
12
12
  private mode;
13
13
  private clipArea;
14
+ targetLayer: number | LayerTarget;
14
15
  private target;
15
16
  private mountContainer;
16
17
  private registry;
17
18
  private targetRect;
18
- private travelers;
19
+ private travelersByLayer;
19
20
  private textureManager;
20
21
  readonly fixedMeshes: Set<THREE.Mesh>;
21
22
  constructor(target: HTMLElement, config: CoreConfig, mountContainer: HTMLElement, registry: MeshRegistry);
23
+ private getSceneLayer;
22
24
  createRenderTarget(): void;
23
25
  private applyTextQuality;
24
26
  mount(): void;
25
27
  private updateCanvasLayout;
28
+ updateUniforms(element: HTMLElement, uniforms: Record<string, any>): void;
26
29
  dispose(): void;
27
30
  setSize(width: number, height: number): void;
28
31
  syncScene(graphNode: SceneNode, pendingDeletions: Set<HTMLElement>): void;
@@ -32,5 +35,4 @@ export declare class Renderer {
32
35
  private updateMeshLayers;
33
36
  private captureRenderTarget;
34
37
  render(): void;
35
- showScissoredRenderTarget(): void;
36
38
  }
@@ -0,0 +1,63 @@
1
+ export declare const ATTR_DOM: {
2
+ readonly NAME: "data-mirage-dom";
3
+ readonly KEY: "mirageDom";
4
+ readonly VALUES: {
5
+ readonly HIDE: "hide";
6
+ };
7
+ };
8
+ export declare const TRAVEL_VALUES: {
9
+ readonly TRAVELER: "traveler";
10
+ readonly NATIVE: "native";
11
+ readonly CAPTURE_1: "1";
12
+ readonly CAPTURE_2: "2";
13
+ readonly CAPTURE_3: "3";
14
+ readonly CAPTURE_4: "4";
15
+ readonly CAPTURE_5: "5";
16
+ };
17
+ export declare const ATTR_TRAVEL: {
18
+ readonly NAME: "data-mirage-travel";
19
+ readonly KEY: "mirageTravel";
20
+ readonly VALUES: {
21
+ readonly TRAVELER: "traveler";
22
+ readonly NATIVE: "native";
23
+ readonly CAPTURE_1: "1";
24
+ readonly CAPTURE_2: "2";
25
+ readonly CAPTURE_3: "3";
26
+ readonly CAPTURE_4: "4";
27
+ readonly CAPTURE_5: "5";
28
+ };
29
+ readonly MAX_LAYERS: number;
30
+ };
31
+ export declare const ATTR_FILTER: {
32
+ readonly NAME: "data-mirage-filter";
33
+ readonly KEY: "mirageFilter";
34
+ readonly VALUES: {
35
+ INCLUDE_TREE: string;
36
+ EXCLUDE_TREE: string;
37
+ INCLUDE_SELF: string;
38
+ EXCLUDE_SELF: string;
39
+ END: string;
40
+ };
41
+ };
42
+ export declare const ATTR_SELECT: {
43
+ readonly NAME: "data-mirage-select";
44
+ readonly KEY: "mirageSelect";
45
+ readonly VALUES: {
46
+ INCLUDE_TREE: string;
47
+ EXCLUDE_TREE: string;
48
+ INCLUDE_SELF: string;
49
+ EXCLUDE_SELF: string;
50
+ END: string;
51
+ };
52
+ };
53
+ export declare const ATTR_SHADER: {
54
+ readonly NAME: "data-mirage-shader";
55
+ readonly KEY: "mirageShader";
56
+ };
57
+ export declare const ATTR_SANDWICH: {
58
+ readonly NAME: "data-mirage-sandwich";
59
+ readonly KEY: "mirageSandwich";
60
+ readonly VALUES: {
61
+ readonly FRONT: "front";
62
+ };
63
+ };
@@ -23,6 +23,10 @@ export interface SceneNode {
23
23
  dirtyMask: number;
24
24
  visibility: Visibility;
25
25
  isTraveler: boolean;
26
+ captureLayer: number;
27
+ nativeLayer?: number;
28
+ nativeStyles?: BoxStyles | TextStyles;
29
+ nativeRect?: NodeRect;
26
30
  isFixed: boolean;
27
31
  shaderHooks?: ShaderHooks;
28
32
  children: SceneNode[];
@@ -1,15 +1,9 @@
1
1
  export type Quality = "low" | "medium" | "high" | number;
2
+ export type LayerTarget = "base" | "selected";
2
3
  export type MirageMode = "overlay" | "duplicate";
3
4
  export type PxUnit = `${number}px`;
4
5
  export type PercentUnit = `${number}%`;
5
6
  export type travelerClipArea = PxUnit | PercentUnit | number;
6
- export interface FilterConfig {
7
- includeTree?: string[];
8
- excludeTree?: string[];
9
- includeSelf?: string[];
10
- excludeSelf?: string[];
11
- end?: string[];
12
- }
13
7
  export interface ResizeConfig {
14
8
  delay?: number;
15
9
  onStart?: () => void;
@@ -17,11 +11,11 @@ export interface ResizeConfig {
17
11
  }
18
12
  interface BaseConfig {
19
13
  debug?: boolean;
14
+ layer?: number | LayerTarget;
20
15
  quality?: Quality;
21
16
  style?: {
22
17
  zIndex?: string;
23
18
  };
24
- filter?: FilterConfig;
25
19
  resizeDebounce?: boolean | ResizeConfig;
26
20
  travelerClipArea?: travelerClipArea;
27
21
  }
@@ -1,11 +1,12 @@
1
- export declare const DIRTY_NONE = 0;
2
- export declare const DIRTY_RECT: number;
3
- export declare const DIRTY_STYLE: number;
4
- export declare const DIRTY_ZINDEX: number;
5
- export declare const DIRTY_STRUCTURE: number;
6
- export declare const DIRTY_CONTENT: number;
1
+ export { DIRTY_NONE, DIRTY_RECT, DIRTY_STYLE, DIRTY_ZINDEX, DIRTY_STRUCTURE, DIRTY_CONTENT, } from '@mirage-engine/dom-tracker';
7
2
  export declare const USER_LAYER: number;
8
- export declare const SYSTEM_LAYER: number;
3
+ export declare const SELECT_LAYER: number;
9
4
  export declare const EXCLUDED = 0;
5
+ export declare const THREE_LAYERS: {
6
+ readonly BASE: 0;
7
+ readonly SELECTED: 1;
8
+ readonly getCaptureLayer: (layerNum: number) => number;
9
+ readonly HIDDEN: 31;
10
+ };
10
11
  export type Visibility = 0 | 1 | 2 | 3;
11
12
  export declare const ALLOWED_FILTERS: string[];
@@ -1,4 +1,5 @@
1
1
  export * from './config';
2
2
  export * from './common';
3
+ export * from './attributes';
3
4
  export * from './flags';
4
- export * from './animate';
5
+ export * from '@mirage-engine/dom-tracker';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mirage-engine/core",
3
- "version": "0.2.2",
3
+ "version": "0.3.1",
4
4
  "main": "src/index.ts",
5
5
  "types": "src/index.ts",
6
6
  "peerDependencies": {
@@ -13,7 +13,8 @@
13
13
  },
14
14
  "dependencies": {
15
15
  "@types/three": "^0.181.0",
16
- "@mirage-engine/painter": "1.0.0"
16
+ "@mirage-engine/painter": "1.0.2",
17
+ "@mirage-engine/dom-tracker": "0.3.4"
17
18
  },
18
19
  "private": false,
19
20
  "publishConfig": {
@@ -1,6 +1,6 @@
1
- import { StyleData } from "../types";
1
+ import { StyleData } from "@mirage-engine/dom-tracker";
2
2
  import { MeshRegistry } from "../store/MeshRegistry";
3
- import { Painter, parseColor } from "@mirage-engine/painter";
3
+ import { Painter } from "@mirage-engine/painter";
4
4
  import * as THREE from "three";
5
5
 
6
6
  export function animateMeshByData(
@@ -21,9 +21,6 @@ export function animateMeshByData(
21
21
  const widthDiff = currentW - baseW;
22
22
  const heightDiff = currentH - baseH;
23
23
 
24
- // --- Capture and Lock Transform Origin (Performance & Accuracy) ---
25
- // We capture the origin on the very first frame of change (> 0.1px)
26
- // to ensure perfect sync from the start of the first animation.
27
24
  if (
28
25
  styleData.width !== undefined &&
29
26
  mesh.userData.originRatioX === undefined &&
@@ -33,8 +30,6 @@ export function animateMeshByData(
33
30
  const tx = styleData.x ?? 0;
34
31
  const baseTx = mesh.userData.baseTransform?.x ?? 0;
35
32
  const scrollOffsetX = mesh.userData.isFixed ? 0 : window.scrollX;
36
- // rect.left already includes GSAP transform (tx).
37
- // We subtract tx to strip the animation, then add baseTx to match baseDOM's initial state.
38
33
  const currentPageX = rect.left + scrollOffsetX - tx + baseTx;
39
34
  const deltaX = currentPageX - mesh.userData.baseDOM.x;
40
35
 
@@ -66,20 +61,15 @@ export function animateMeshByData(
66
61
  mesh.userData.originRatioY = ratioY;
67
62
  }
68
63
 
69
- // --- Calculate Mesh Position using Measured Origin ---
70
64
  const ratioX = mesh.userData.originRatioX ?? 0.5;
71
65
  const ratioY = mesh.userData.originRatioY ?? 0.5;
72
66
 
73
- // Since Three.js meshes expand from center, we offset the center based on the locked origin ratio
74
67
  const moveX = widthDiff * (0.5 - ratioX);
75
68
  const moveY = heightDiff * (0.5 - ratioY);
76
69
 
77
- // --- Calculate Delta Movement ---
78
- // Extract baseTransform stored during syncScene
79
70
  const baseTx = mesh.userData.baseTransform?.x ?? 0;
80
71
  const baseTy = mesh.userData.baseTransform?.y ?? 0;
81
72
 
82
- // We only want to apply the DIFFERENCE in transform since the base extraction.
83
73
  const deltaTx = (styleData.x ?? baseTx) - baseTx;
84
74
  const deltaTy = (styleData.y ?? baseTy) - baseTy;
85
75
 
@@ -97,10 +87,6 @@ export function animateMeshByData(
97
87
  });
98
88
  });
99
89
  }
100
- export function animateMeshByAttribute(
101
- _target: HTMLElement,
102
- _options: { duration: number; easing?: string },
103
- ) {}
104
90
 
105
91
  export function updateFixedMeshesScroll(
106
92
  fixedMeshes: Set<THREE.Mesh>,
@@ -120,44 +106,3 @@ export function updateFixedMeshesScroll(
120
106
  }
121
107
  });
122
108
  }
123
-
124
- export function extractFromStyle(style: CSSStyleDeclaration): StyleData {
125
- const styleObject: StyleData = {};
126
-
127
- if (style.opacity) {
128
- styleObject.opacity = parseFloat(style.opacity);
129
- }
130
-
131
- if (style.backgroundColor && style.backgroundColor !== "rgba(0, 0, 0, 0)") {
132
- const parsed = parseColor(style.backgroundColor);
133
- styleObject.backgroundColor = [parsed.color.r, parsed.color.g, parsed.color.b];
134
- }
135
-
136
- if (style.backgroundImage) {
137
- styleObject.backgroundImage = style.backgroundImage;
138
- } else if (style.background) {
139
- styleObject.backgroundImage = style.background;
140
- }
141
-
142
- if (style.borderRadius) {
143
- styleObject.borderRadius = parseFloat(style.borderRadius);
144
- }
145
- if (style.width) {
146
- styleObject.width = parseFloat(style.width);
147
- }
148
- if (style.height) {
149
- styleObject.height = parseFloat(style.height);
150
- }
151
- if (style.transform && style.transform !== "none") {
152
- const matrix = new DOMMatrix(style.transform);
153
-
154
- styleObject.x = matrix.m41;
155
- styleObject.y = matrix.m42;
156
- styleObject.z = matrix.m43;
157
-
158
- // [TODO] direct matrix data pipeline to webGL
159
- // styleObject.matrix = matrix.toFloat32Array();
160
- }
161
-
162
- return styleObject;
163
- }