narraleaf-react 0.42.3 → 0.42.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js
CHANGED
|
@@ -4,20 +4,20 @@ var pe={action:"displayable:action",applyTransform:"displayable:applyTransform",
|
|
|
4
4
|
A returnable jump suspends the scene it leaves rather than unloading it, so a scene cannot be called from itself or from anything it has called.`,this);if(e.isSceneSuspended(this.callee))throw this._callerAlreadyParkedError(n);let r=e.getSuspendedScenes().length,s=e.game.config.maxSceneCallDepth;if(r>=s)throw new J(`Scene call depth limit reached (${s}).
|
|
5
5
|
Each returnable jump keeps the scene it left mounted, so a chain of them holds every scene in the chain on the stage at once. Raise maxSceneCallDepth if the story really needs to go this deep.`,this);let a=this.callee.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{a&&e.audioManager.isManaged(a)&&e.audioManager.resume(a,0)},[]),a&&e.audioManager.isManaged(a)&&e.audioManager.pause(a,this.callee.config.backgroundMusicFade),super.executeAction(e,t)}else if(this.type===z.callTo){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));let r=this.contentNode.getChild();if(!r?.action)throw new Ae("A scene call has no return address. `scene:callTo` is only ever built with a `scene:resume` chained behind it (see Scene._callScene).");let s=this.callee;if(e.isSceneSuspended(s))throw this._callerAlreadyParkedError(n);let a=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{e.setSceneSuspended(s,!1);let[u]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(l,u)},[a]),e.setSceneSuspended(s,!0);let c=i.getSceneRoot().contentNode;return[{type:this.type,node:r},{type:this.type,node:c}]}else if(this.type===z.resume){let n=this.contentNode.getContent()[0],i=this.callee,r=i.state.backgroundMusic,s=ye.createSceneSnapshot(n,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let c=new S(l=>l);e.timelines.attachTimeline(c),ye.handleSceneInit(n,{type:this.type,node:this.contentNode.getChild()},e,c),ye.restoreSceneSnapshot(a,e),e.setSceneSuspended(i,!0),r&&e.audioManager.isManaged(r)&&e.audioManager.pause(r,0)},[s]),n.events.emit("event:scene.preUnmount"),ye.unloadScene(n,e),e.setSceneSuspended(i,!1),r&&e.audioManager.isManaged(r)&&e.audioManager.resume(r,i.config.backgroundMusicFade),super.executeAction(e,t)}else if(this.type===z.setBackgroundMusic){let[n,i]=this.contentNode.getContent(),r=this.callee,s=e.getExposedStateForce(r),a=r.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.setBackgroundMusic(c,0)},[a]),s.setBackgroundMusic(n,i||0),super.executeAction(e,t)}else{if(this.type===z.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===z.transitionToScene){let[n,i]=this.contentNode.getContent();return this.applyStageTransition(e,n,i,t)}else if(this.type===z.nvlBlock){let[n,i]=this.contentNode.getContent(),r=e.createNvlSnapshot();return e.enterNvlMode(i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{e.restoreNvlSnapshot(s)},[r]),n.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]}else if(this.type===z.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=S.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===z.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=S.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===z.nvlEnd){let[n]=this.contentNode.getContent(),i=e.createNvlSnapshot();return e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{e.restoreNvlSnapshot(r)},[i]),e.exitNvlMode(n||null),{type:this.type,node:null}}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===z.callTo&&t.allowFutureScene!==!1){let i=this.contentNode.getContent()[0],r=e.getScene(i,!0);r.isSceneRootConstructed()||r.constructSceneRoot(e);let s=r.getSceneRoot()?.contentNode,a=this.contentNode.getChild()?.action;return[...s?.action?[s.action]:[],...a?[a]:[]]}if(this.type===z.jumpTo&&t.allowFutureScene!==!1){let i=this.contentNode.getContent()[0],r=e.getScene(i,!0);r.isSceneRootConstructed()||r.constructSceneRoot(e);let s=e.getScene(i,!0).getSceneRoot()?.contentNode;return s?.action?[s.action]:[]}if(this.type===z.nvlBlock){let[i]=this.contentNode.getContent(),r=super.getFutureActions(e,t);return[...i??[],...r]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new J(`Scene with name ${e} not found
|
|
6
6
|
Make sure you have registered the scene using story.register`,this)}_callerAlreadyParkedError(e){let t=this.getSceneName(this.callee);return new J(`Cannot call scene ${this.getSceneName(e)} from ${t}: ${t} is already parked behind another call.
|
|
7
|
-
A returnable jump suspends the scene it is taken from, and a scene has one place on the stage, so two calls cannot be open from the same scene at the same time. Take the calls one after the other in a single branch rather than one per branch of a concurrent group.`,this)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===z.callTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`callTo {${i.stringify(e,t,n)}}`)}if(this.type===z.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${i.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};ye.ActionTypes=z;var ee=ye;var cr=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},C=class o extends cr{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var qi={center:"center",left:"left",right:"right"};import{animate as ca}from"motion/react";var In=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(In||{}),aa={left:"33.33%",center:"50%",right:"66.66%"},gt=class gt{static isUnknown(e){return e===gt.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},c=t?{right:s}:{left:s};return this.wrap({...a,...c})}static calc(e,t,n){if(e==null||e===""||gt.isUnknown(e))return"auto";let i=!(t===void 0||gt.isUnknown(t));if(typeof n=="number"&&n>0){let s=gt.toPercent(e,n);if(s!==null){let a=i?t/n*100:0;return`${Math.round((s+a)*1e6)/1e6}%`}}let r=typeof e=="number"?`${e}px`:e;return i?`calc(${r} + ${t}px)`:`calc(${r} + 0px)`}static toPercent(e,t){if(typeof e=="number")return t>0?e/t*100:null;let n=/^(-?\d+(?:\.\d+)?)%$/.exec(e.trim());return n?parseFloat(n[1]):null}static toCoord2D(e){if(lt.isCommonPositionType(e))return yt.fromCommonPosition(e);if(yt.isCoord2DPosition(e))return e;if(Sn.isAlignPosition(e))return yt.fromAlignPosition(e);if(typeof e=="object"&&e!==null&&["x","y","xalign","yalign","xoffset","yoffset"].some(t=>t in e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static orUnknown(e){return gt.isUnknown(e)||e===void 0?gt.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return yt.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:gt.isUnknown(t.x)?0:t.x,y:gt.isUnknown(t.y)?0:t.y,xoffset:gt.isUnknown(t.xoffset)?0:t.xoffset,yoffset:gt.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(In).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&e!==null&&("xalign"in e||"yalign"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof lt||e instanceof yt||e instanceof Sn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return yt.fromCommonPosition(new lt(e));if(this.isRawAlignPosition(e))return yt.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new yt(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};gt.Unknown=Symbol("Unknown");var O=gt,Yi=class Yi{static isCommonPositionType(e){return e instanceof Yi}constructor(e){this.position=e}toCSS(){return{x:aa[this.position],y:"50%",xoffset:0,yoffset:0}}};Yi.Positions=In;var lt=Yi,yt=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:aa[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>typeof n!="number"||!Number.isFinite(n)?O.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:O.isUnknown(t.x)?e.x:t.x,y:O.isUnknown(t.y)?e.y:t.y,xoffset:O.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:O.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=O.orUnknown(e.x),this.y=O.orUnknown(e.y),this.xoffset=O.orUnknown(e.xoffset),this.yoffset=O.orUnknown(e.yoffset)):(this.x=O.orUnknown(e),this.y=O.orUnknown(t),this.xoffset=O.Unknown,this.yoffset=O.Unknown),this.check()}check(){let e=t=>/^-?\d+(\.\d+)?%$/.test(t);if(typeof this.x=="string"&&!e(this.x))throw new Error(`Invalid x position: ${this.x}`);if(typeof this.y=="string"&&!e(this.y))throw new Error(`Invalid y position: ${this.y}`)}toCSS(){return{x:this.x,y:this.y,xoffset:this.xoffset,yoffset:this.yoffset}}},Sn=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=O.orUnknown(e.xalign),this.yalign=O.orUnknown(e.yalign),this.xoffset=O.orUnknown(e.xoffset),this.yoffset=O.orUnknown(e.yoffset)):(this.xalign=O.orUnknown(e),this.yalign=O.orUnknown(t),this.xoffset=O.Unknown,this.yoffset=O.Unknown),this.check()}check(){if(typeof this.xalign=="number"&&isNaN(this.xalign))throw new Error("Invalid xalign position: "+this.xalign);if(typeof this.yalign=="number"&&isNaN(this.yalign))throw new Error("Invalid yalign position: "+this.yalign)}toCSS(){return{x:O.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:O.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var j=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new lr(this.mergeWithDefaultConfig(e))}copy(){return new o(Y({},this.defaultConfig),this.handlers)}keys(){return Object.keys(this.defaultConfig)}getDefaultConfig(){return this.defaultConfig}mergeWithDefaultConfig(e){return Object.fromEntries(Object.entries(this.defaultConfig).map(([t,n])=>[t,this.mergeValue(t,n,e[t])]))}mergeValue(e,t,n){return this.isPlainObject(n)?Y({},n):Array.isArray(t)?Array.isArray(n)&&n.length>0?[...n]:[...t]:n!==void 0?this.applyHandler(e,n):t}isPlainObject(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}applyHandler(e,t){return typeof this.handlers[e]=="function"?this.handlers[e](t):t}},lr=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(Y({},this.config))}join(e){let t=ta(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var Gl={[qi.left]:"25.33%",[qi.center]:"50%",[qi.right]:"75.66%"},Et=class Et{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new Et(Et.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?O.toCoord2D(O.tryParsePosition(e||t)):O.mergePosition(O.tryParsePosition(e),O.tryParsePosition(t))}static mergeState(e,t){if("position"in e&&"position"in t){let n=this.mergePosition(e.position,t.position);return{...Object.assign({},e,t),position:n}}return{...Object.assign({},e,t)}}get(){return this.state}freeze(){return this.frozen=!0,this}assign(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Et.mergeState(this.state,t),this}lock(){if(this.locked)throw new Error("Transform state is already locked.");return this.locked=Symbol(),this.locked}isLocked(){return!!this.locked}canWrite(e){return this.locked===null||this.locked===e}unlock(e){return this.locked===e&&(this.locked=null),this}toFramesDefinition(e,t){return Qn(Z.constructStyle(e,this.state,t))}toStyle(e,t){return Qn(Z.constructStyle(e,this.state,t))}serialize(){return Et.TransformStateSerializer.serialize(this.state)}clone(){return new Et(Et.mergeState({},this.state))}overwrite(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Et.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}resetTo(e){return this.state=e,this.locked=null,this.frozen=!1,this}};Et.DefaultTransformState=new j({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new lt("center"),opacity:0,alt:"",maskImage:void 0,maskSize:void 0,maskPosition:void 0,maskRepeat:void 0,maskMode:void 0,clipPath:void 0,filter:void 0,backdropFilter:void 0,mixBlendMode:void 0}),Et.TransformStateSerializer=new qe({position:e=>O.serializePosition(O.tryParsePosition(e))},{position:e=>O.toCoord2D(e)});var ne=Et,Le=class Le{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},Le.defaultConfig,t||{});else{let[n,i]=[e,t||Le.defaultOptions];this.sequences.push({props:n,options:i||Le.defaultOptions}),this.config=Object.assign({},Le.defaultConfig)}}static isPosition(e){return lt.isCommonPositionType(e)||yt.isCoord2DPosition(e)||Sn.isAlignPosition(e)}static immediate(e){return new Le(e,{duration:0,ease:"linear"})}static left(e,t){return new Le({position:lt.Positions.Left},{duration:e,ease:t})}static right(e,t){return new Le({position:lt.Positions.Right},{duration:e,ease:t})}static center(e,t){return new Le({position:lt.Positions.Center},{duration:e,ease:t})}static create(e){return new Le([],e)}static positionToCSS(e,t,n,i){return e?O.isRawPosition(e)?O.D2PositionToCSS(O.rawPositionToCoord2D(e),n,t,i):O.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?O.toCoord2D(O.tryParsePosition(e||t)):O.mergePosition(O.tryParsePosition(e),O.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...Y(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,c=function(p,h,g){return typeof p>"u"?typeof g<"u"?h(g):"":h(p)},l=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${u})`,c(t.rotation,p=>`rotate(${p}deg)`,0),c(t.scaleX,p=>`scaleX(${p*a})`,1),c(t.scaleY,p=>`scaleY(${p*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{},a=e.game?.config,c=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...Le.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?Rn(t.fontColor):void 0,transform:Le.propToCSSTransform(e,t),...Le.constructVisualEffectStyle(t),...s?s(t):{}}}static constructVisualEffectStyle(e){let t=e;return{maskImage:t.maskImage,WebkitMaskImage:t.maskImage,maskSize:t.maskSize,WebkitMaskSize:t.maskSize,maskPosition:t.maskPosition,WebkitMaskPosition:t.maskPosition,maskRepeat:t.maskRepeat,WebkitMaskRepeat:t.maskRepeat,maskMode:t.maskMode,WebkitMaskMode:t.maskMode,clipPath:t.clipPath,filter:t.filter,backdropFilter:t.backdropFilter,WebkitBackdropFilter:t.backdropFilter,mixBlendMode:t.mixBlendMode}}animate(e,{gameState:t,ref:n,overwrites:i,companionRefs:r}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:s,sequences:a,options:c}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(m=>!!m.ref.current).map(({ref:m,project:y})=>({el:m.current,project:y}))});if(a.length||t.logger.warn("Transform","No sequences to animate."),c.repeat!==void 0&&!Number.isFinite(c.repeat))throw new J("A transform applied with `transform()` (or `show`, `hide`, `pos`, ...) has to end, but this one repeats forever.\nUse `element.loop(transform)` for a motion that runs until it is stopped - the line does not wait for it, and `element.stopLoop()` ends it.");let l=!1,u=e.lock(),d=ca(a,c),p=()=>{e.overwrite(u,s.get()).unlock(u),d.complete(),l=!0},h=new S().registerSkipController(new U(p)),g=()=>{l||e.overwrite(u,s.get()).unlock(u),l=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),h.resolve()};return d.then(g,(m=>{t.logger.error("Failed to animate transform. "+(m?.toString?.()||""));try{g()}catch{h.resolve()}})),d.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:s,sequences:a,options:c},this),h}startLoop(e,{gameState:t,ref:n,overwrites:i,companionRefs:r},s){if(!n.current)throw new Error("No ref found when looping.");this.commit();let{sequences:a,options:c}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(d=>!!d.ref.current).map(({ref:d,project:p})=>({el:d.current,project:p}))});a.length||t.logger.warn("Transform","No sequences to loop.");let l=[n.current,Qn(e.toFramesDefinition(t,i)),{duration:0}],u=ca([l,...a],{...c,repeat:1/0,repeatType:s?.repeatType??c.repeatType??"loop",repeatDelay:s?.repeatDelay!==void 0?this.toSeconds(s.repeatDelay,void 0):c.repeatDelay});return u.play(),t.logger.debug("Transform","Loop started.",{sequences:a,options:c},this),{stop:()=>{u.stop()}}}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...Le.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i,companions:r}){let s=t.clone(),a=s.lock(),c=this.sequences.flatMap(({props:l,options:u})=>{let d=s.assign(a,l),p=d.toFramesDefinition(e,n),h=this.getOptions(u),g=[i,p,h];if(!r||!r.length)return[g];let m=d.get();return[g,...r.map(({el:y,project:T})=>[y,Qn(T(m)),{...h,at:"<"}])]});return{finalState:s.unlock(a).freeze(),sequences:c,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t,repeatType:n}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0),repeatType:n}}copy(){return new Le(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}effect(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}lens(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}maskImage(e){return this.pushChange({key:"maskImage",props:e})}clipPath(e){return this.pushChange({key:"clipPath",props:e})}filter(e){return this.pushChange({key:"filter",props:e})}backdropFilter(e){return this.pushChange({key:"backdropFilter",props:e})}mixBlendMode(e){return this.pushChange({key:"mixBlendMode",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new J("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new J("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};Le.defaultConfig={sync:!0},Le.defaultOptions={duration:0,ease:"linear"},Le.CommonImagePositionMap=Gl;var Z=Le;var Xi=class{constructor(){this.id="";this._staticId=null;this._dirty=!1}setId(e){this.id=e}getId(){return this.id}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}markDirty(){return this._dirty=!0,this}isDirty(){return this._dirty}reset(){this._dirty=!1}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var la=Symbol("_Chained"),ua;ua=la;var ur=class ur{constructor(e){this[ua]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[la]}static toActions(e){return e.flat(2).map(t=>ur.isChained(t)?t.fromChained(t):t).flat(3)}push(...e){this.__actions.push(...e)}getActions(){return this.__actions}getSelf(){return this.__self}newChain(){return this.getSelf().chain()}},Be=ur,Mn=class extends Xi{chain(e){let t=Be.isChained(this)?this:this.proxy(this,new Be(this));if(!e)return t;let n=Array.isArray(e)?e:[e];return t.push(...n),t}proxy(e,t){let n=new Proxy(e,{get:function(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=e.do([n]).getActions()[0];return this.chain(i)}};var le=class extends Mn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Ot=class extends X{executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",c=s.action?s.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};Ot.ActionTypes=qs;var Jn=64;function da(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function pr(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function Qi(o,e=0,t=new Set){if(e>Jn)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>Qi(n,e+1,t)):da(o)?Object.values(o).every(n=>Qi(n,e+1,t)):!1}finally{t.delete(o)}}function ma(o,e){let t=[],n=[];return{data:dr(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function dr(o,e,t,n,i,r,s){if(t>Jn)throw new E(`A stored value nests deeper than ${Jn} levels and cannot be saved
|
|
7
|
+
A returnable jump suspends the scene it is taken from, and a scene has one place on the stage, so two calls cannot be open from the same scene at the same time. Take the calls one after the other in a single branch rather than one per branch of a concurrent group.`,this)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===z.callTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`callTo {${i.stringify(e,t,n)}}`)}if(this.type===z.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${i.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};ye.ActionTypes=z;var ee=ye;var cr=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},C=class o extends cr{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var qi={center:"center",left:"left",right:"right"};import{animate as ca}from"motion/react";var In=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(In||{}),aa={left:"33.33%",center:"50%",right:"66.66%"},gt=class gt{static isUnknown(e){return e===gt.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},c=t?{right:s}:{left:s};return this.wrap({...a,...c})}static calc(e,t,n){if(e==null||e===""||gt.isUnknown(e))return"auto";let i=!(t===void 0||gt.isUnknown(t));if(typeof n=="number"&&n>0){let s=gt.toPercent(e,n);if(s!==null){let a=i?t/n*100:0;return`${Math.round((s+a)*1e6)/1e6}%`}}let r=typeof e=="number"?`${e}px`:e;return i?`calc(${r} + ${t}px)`:`calc(${r} + 0px)`}static toPercent(e,t){if(typeof e=="number")return t>0?e/t*100:null;let n=/^(-?\d+(?:\.\d+)?)%$/.exec(e.trim());return n?parseFloat(n[1]):null}static toCoord2D(e){if(lt.isCommonPositionType(e))return yt.fromCommonPosition(e);if(yt.isCoord2DPosition(e))return e;if(Sn.isAlignPosition(e))return yt.fromAlignPosition(e);if(typeof e=="object"&&e!==null&&["x","y","xalign","yalign","xoffset","yoffset"].some(t=>t in e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static orUnknown(e){return gt.isUnknown(e)||e===void 0?gt.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return yt.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:gt.isUnknown(t.x)?0:t.x,y:gt.isUnknown(t.y)?0:t.y,xoffset:gt.isUnknown(t.xoffset)?0:t.xoffset,yoffset:gt.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(In).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&e!==null&&("xalign"in e||"yalign"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof lt||e instanceof yt||e instanceof Sn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return yt.fromCommonPosition(new lt(e));if(this.isRawAlignPosition(e))return yt.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new yt(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};gt.Unknown=Symbol("Unknown");var O=gt,Yi=class Yi{static isCommonPositionType(e){return e instanceof Yi}constructor(e){this.position=e}toCSS(){return{x:aa[this.position],y:"50%",xoffset:0,yoffset:0}}};Yi.Positions=In;var lt=Yi,yt=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:aa[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>typeof n!="number"||!Number.isFinite(n)?O.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:O.isUnknown(t.x)?e.x:t.x,y:O.isUnknown(t.y)?e.y:t.y,xoffset:O.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:O.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=O.orUnknown(e.x),this.y=O.orUnknown(e.y),this.xoffset=O.orUnknown(e.xoffset),this.yoffset=O.orUnknown(e.yoffset)):(this.x=O.orUnknown(e),this.y=O.orUnknown(t),this.xoffset=O.Unknown,this.yoffset=O.Unknown),this.check()}check(){let e=t=>/^-?\d+(\.\d+)?%$/.test(t);if(typeof this.x=="string"&&!e(this.x))throw new Error(`Invalid x position: ${this.x}`);if(typeof this.y=="string"&&!e(this.y))throw new Error(`Invalid y position: ${this.y}`)}toCSS(){return{x:this.x,y:this.y,xoffset:this.xoffset,yoffset:this.yoffset}}},Sn=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=O.orUnknown(e.xalign),this.yalign=O.orUnknown(e.yalign),this.xoffset=O.orUnknown(e.xoffset),this.yoffset=O.orUnknown(e.yoffset)):(this.xalign=O.orUnknown(e),this.yalign=O.orUnknown(t),this.xoffset=O.Unknown,this.yoffset=O.Unknown),this.check()}check(){if(typeof this.xalign=="number"&&isNaN(this.xalign))throw new Error("Invalid xalign position: "+this.xalign);if(typeof this.yalign=="number"&&isNaN(this.yalign))throw new Error("Invalid yalign position: "+this.yalign)}toCSS(){return{x:O.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:O.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var j=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new lr(this.mergeWithDefaultConfig(e))}copy(){return new o(Y({},this.defaultConfig),this.handlers)}keys(){return Object.keys(this.defaultConfig)}getDefaultConfig(){return this.defaultConfig}mergeWithDefaultConfig(e){return Object.fromEntries(Object.entries(this.defaultConfig).map(([t,n])=>[t,this.mergeValue(t,n,e[t])]))}mergeValue(e,t,n){return this.isPlainObject(n)?Y({},n):Array.isArray(t)?Array.isArray(n)&&n.length>0?[...n]:[...t]:n!==void 0?this.applyHandler(e,n):t}isPlainObject(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}applyHandler(e,t){return typeof this.handlers[e]=="function"?this.handlers[e](t):t}},lr=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(Y({},this.config))}join(e){let t=ta(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var Fl={[qi.left]:"25.33%",[qi.center]:"50%",[qi.right]:"75.66%"},Et=class Et{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new Et(Et.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?O.toCoord2D(O.tryParsePosition(e||t)):O.mergePosition(O.tryParsePosition(e),O.tryParsePosition(t))}static mergeState(e,t){if("position"in e&&"position"in t){let n=this.mergePosition(e.position,t.position);return{...Object.assign({},e,t),position:n}}return{...Object.assign({},e,t)}}get(){return this.state}freeze(){return this.frozen=!0,this}assign(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Et.mergeState(this.state,t),this}lock(){if(this.locked)throw new Error("Transform state is already locked.");return this.locked=Symbol(),this.locked}isLocked(){return!!this.locked}canWrite(e){return this.locked===null||this.locked===e}unlock(e){return this.locked===e&&(this.locked=null),this}toFramesDefinition(e,t){return Qn(Z.constructStyle(e,this.state,t))}toStyle(e,t){return Qn(Z.constructStyle(e,this.state,t))}serialize(){return Et.TransformStateSerializer.serialize(this.state)}clone(){return new Et(Et.mergeState({},this.state))}overwrite(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=Et.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}resetTo(e){return this.state=e,this.locked=null,this.frozen=!1,this}};Et.DefaultTransformState=new j({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new lt("center"),opacity:0,alt:"",maskImage:void 0,maskSize:void 0,maskPosition:void 0,maskRepeat:void 0,maskMode:void 0,clipPath:void 0,filter:void 0,backdropFilter:void 0,mixBlendMode:void 0}),Et.TransformStateSerializer=new qe({position:e=>O.serializePosition(O.tryParsePosition(e))},{position:e=>O.toCoord2D(e)});var ne=Et,Le=class Le{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},Le.defaultConfig,t||{});else{let[n,i]=[e,t||Le.defaultOptions];this.sequences.push({props:n,options:i||Le.defaultOptions}),this.config=Object.assign({},Le.defaultConfig)}}static isPosition(e){return lt.isCommonPositionType(e)||yt.isCoord2DPosition(e)||Sn.isAlignPosition(e)}static immediate(e){return new Le(e,{duration:0,ease:"linear"})}static left(e,t){return new Le({position:lt.Positions.Left},{duration:e,ease:t})}static right(e,t){return new Le({position:lt.Positions.Right},{duration:e,ease:t})}static center(e,t){return new Le({position:lt.Positions.Center},{duration:e,ease:t})}static create(e){return new Le([],e)}static positionToCSS(e,t,n,i){return e?O.isRawPosition(e)?O.D2PositionToCSS(O.rawPositionToCoord2D(e),n,t,i):O.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?O.toCoord2D(O.tryParsePosition(e||t)):O.mergePosition(O.tryParsePosition(e),O.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...Y(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,c=function(p,h,g){return typeof p>"u"?typeof g<"u"?h(g):"":h(p)},l=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${u})`,c(t.rotation,p=>`rotate(${p}deg)`,0),c(t.scaleX,p=>`scaleX(${p*a})`,1),c(t.scaleY,p=>`scaleY(${p*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{},a=e.game?.config,c=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...Le.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?Rn(t.fontColor):void 0,transform:Le.propToCSSTransform(e,t),...Le.constructVisualEffectStyle(t),...s?s(t):{}}}static constructVisualEffectStyle(e){let t=e;return{maskImage:t.maskImage,WebkitMaskImage:t.maskImage,maskSize:t.maskSize,WebkitMaskSize:t.maskSize,maskPosition:t.maskPosition,WebkitMaskPosition:t.maskPosition,maskRepeat:t.maskRepeat,WebkitMaskRepeat:t.maskRepeat,maskMode:t.maskMode,WebkitMaskMode:t.maskMode,clipPath:t.clipPath,filter:t.filter,backdropFilter:t.backdropFilter,WebkitBackdropFilter:t.backdropFilter,mixBlendMode:t.mixBlendMode}}animate(e,{gameState:t,ref:n,overwrites:i,companionRefs:r}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:s,sequences:a,options:c}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(m=>!!m.ref.current).map(({ref:m,project:y})=>({el:m.current,project:y}))});if(a.length||t.logger.warn("Transform","No sequences to animate."),c.repeat!==void 0&&!Number.isFinite(c.repeat))throw new J("A transform applied with `transform()` (or `show`, `hide`, `pos`, ...) has to end, but this one repeats forever.\nUse `element.loop(transform)` for a motion that runs until it is stopped - the line does not wait for it, and `element.stopLoop()` ends it.");let l=!1,u=e.lock(),d=ca(a,c),p=()=>{e.overwrite(u,s.get()).unlock(u),d.complete(),l=!0},h=new S().registerSkipController(new U(p)),g=()=>{l||e.overwrite(u,s.get()).unlock(u),l=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),h.resolve()};return d.then(g,(m=>{t.logger.error("Failed to animate transform. "+(m?.toString?.()||""));try{g()}catch{h.resolve()}})),d.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:s,sequences:a,options:c},this),h}startLoop(e,{gameState:t,ref:n,overwrites:i,companionRefs:r},s){if(!n.current)throw new Error("No ref found when looping.");this.commit();let{sequences:a,options:c}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(d=>!!d.ref.current).map(({ref:d,project:p})=>({el:d.current,project:p}))});a.length||t.logger.warn("Transform","No sequences to loop.");let l=[n.current,Qn(e.toFramesDefinition(t,i)),{duration:0}],u=ca([l,...a],{...c,repeat:1/0,repeatType:s?.repeatType??c.repeatType??"loop",repeatDelay:s?.repeatDelay!==void 0?this.toSeconds(s.repeatDelay,void 0):c.repeatDelay});return u.play(),t.logger.debug("Transform","Loop started.",{sequences:a,options:c},this),{stop:()=>{u.stop()}}}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...Le.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i,companions:r}){let s=t.clone(),a=s.lock(),c=this.sequences.flatMap(({props:l,options:u})=>{let d=s.assign(a,l),p=d.toFramesDefinition(e,n),h=this.getOptions(u),g=[i,p,h];if(!r||!r.length)return[g];let m=d.get();return[g,...r.map(({el:y,project:T})=>[y,Qn(T(m)),{...h,at:"<"}])]});return{finalState:s.unlock(a).freeze(),sequences:c,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t,repeatType:n}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0),repeatType:n}}copy(){return new Le(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}effect(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}lens(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}maskImage(e){return this.pushChange({key:"maskImage",props:e})}clipPath(e){return this.pushChange({key:"clipPath",props:e})}filter(e){return this.pushChange({key:"filter",props:e})}backdropFilter(e){return this.pushChange({key:"backdropFilter",props:e})}mixBlendMode(e){return this.pushChange({key:"mixBlendMode",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new J("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new J("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};Le.defaultConfig={sync:!0},Le.defaultOptions={duration:0,ease:"linear"},Le.CommonImagePositionMap=Fl;var Z=Le;var Xi=class{constructor(){this.id="";this._staticId=null;this._dirty=!1}setId(e){this.id=e}getId(){return this.id}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}markDirty(){return this._dirty=!0,this}isDirty(){return this._dirty}reset(){this._dirty=!1}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var la=Symbol("_Chained"),ua;ua=la;var ur=class ur{constructor(e){this[ua]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[la]}static toActions(e){return e.flat(2).map(t=>ur.isChained(t)?t.fromChained(t):t).flat(3)}push(...e){this.__actions.push(...e)}getActions(){return this.__actions}getSelf(){return this.__self}newChain(){return this.getSelf().chain()}},Be=ur,Mn=class extends Xi{chain(e){let t=Be.isChained(this)?this:this.proxy(this,new Be(this));if(!e)return t;let n=Array.isArray(e)?e:[e];return t.push(...n),t}proxy(e,t){let n=new Proxy(e,{get:function(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=e.do([n]).getActions()[0];return this.chain(i)}};var le=class extends Mn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Ot=class extends X{executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",c=s.action?s.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};Ot.ActionTypes=qs;var Jn=64;function da(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function pr(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function Qi(o,e=0,t=new Set){if(e>Jn)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>Qi(n,e+1,t)):da(o)?Object.values(o).every(n=>Qi(n,e+1,t)):!1}finally{t.delete(o)}}function ma(o,e){let t=[],n=[];return{data:dr(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function dr(o,e,t,n,i,r,s){if(t>Jn)throw new E(`A stored value nests deeper than ${Jn} levels and cannot be saved
|
|
8
8
|
at ${s}, ${pr(e)}
|
|
9
9
|
A saved game this deep is almost always a data-structure bug. Flatten the value,
|
|
10
10
|
or keep the deep part outside the store and save an id for it.`);if(o===void 0)return r.push([...e]),null;if(o===null)return null;if(o instanceof Date)return i.push([...e]),o.toISOString();if(typeof o=="number"||typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="object"){if(n.has(o))throw new E(`A stored value refers back to itself and cannot be saved
|
|
11
11
|
at ${s}, ${pr(e)}
|
|
12
12
|
A saved game is a tree. Cutting the back-edge would save a different object graph
|
|
13
13
|
than the one you built, so this is refused rather than guessed at \u2014 break the
|
|
14
|
-
reference, or store an id in place of the object.`);if(Array.isArray(o)||da(o)){n.add(o);try{if(Array.isArray(o))return o.map((c,l)=>dr(c,[...e,l],t+1,n,i,r,s));let a={};return Object.entries(o).forEach(([c,l])=>{a[c]=dr(l,[...e,c],t+1,n,i,r,s)}),a}finally{n.delete(o)}}}return console.warn(`Value of type "${
|
|
15
|
-
at ${s}, ${pr(e)}`),null}function
|
|
14
|
+
reference, or store an id in place of the object.`);if(Array.isArray(o)||da(o)){n.add(o);try{if(Array.isArray(o))return o.map((c,l)=>dr(c,[...e,l],t+1,n,i,r,s));let a={};return Object.entries(o).forEach(([c,l])=>{a[c]=dr(l,[...e,c],t+1,n,i,r,s)}),a}finally{n.delete(o)}}}return console.warn(`Value of type "${Ol(o)}" cannot be saved and was stored as null
|
|
15
|
+
at ${s}, ${pr(e)}`),null}function Ol(o){return typeof o!="object"||o===null?typeof o:o.constructor?.name??"object"}function fa(o,e,t){let n=pa(o,e,mr);return n=pa(n,t,()=>{}),n}function pa(o,e,t){if(!Array.isArray(e)||!e.length)return o;let n=o;for(let i of e){if(!Array.isArray(i))continue;if(!i.length){n=t(n);continue}let r=n;for(let a=0;a<i.length-1&&r!==null&&typeof r=="object";a++)r=r[i[a]];if(r===null||typeof r!="object")continue;let s=i[i.length-1];r[s]=t(r[s])}return n}function mr(o){return o instanceof Date?o:typeof o=="string"||typeof o=="number"?new Date(o):new Date(NaN)}function ha(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function fr(o,e,t=0){if(Object.is(o,e))return!0;if(t>Jn)return!1;if(o instanceof Date||e instanceof Date)return o instanceof Date&&e instanceof Date&&o.getTime()===e.getTime();if(Array.isArray(o)||Array.isArray(e))return Array.isArray(o)&&Array.isArray(e)&&o.length===e.length&&o.every((n,i)=>fr(n,e[i],t+1));if(ha(o)&&ha(e)){let n=Object.keys(o);return n.length===Object.keys(e).length&&n.every(i=>Object.prototype.hasOwnProperty.call(e,i)&&fr(o[i],e[i],t+1))}return!1}var Ht=class o{constructor(e,t,n){this.owner=null;this.name=e,this.key=n||e,this.content=Y({},t),this.defaultContent=t}static isSerializable(e){return Qi(e)}set(e,t){let n=this.content[e];return o.isSerializable(t)?(this.content[e]=t,this.reportChange(e,n,t),this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
|
|
16
16
|
at namespace "${this.name}"`),this.content[e]=t,this.reportChange(e,n,t),this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}has(e){return this.content[e]!==void 0}keys(){return Object.keys(this.content)}values(){return Object.values(this.content)}entries(){return Object.entries(this.content)}reset(){let e=this.content;return this.content=Y({},this.defaultContent),new Set([...Object.keys(e),...Object.keys(this.content)]).forEach(n=>{this.reportChange(n,e[n],this.content[n])}),this}getContent(){return this.content}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content={},this.deserialize(e)}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n,t)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)}),this.owner?.reportRestore(this.key)}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e,t){let n=`namespace "${this.name}"`+(t===void 0?"":`, key "${t}"`),i={any:s=>{let a=ma(s,n),c={type:"any",data:a.data};return a.dates.length&&(c.dates=a.dates),a.undefineds.length&&(c.undefineds=a.undefineds),c},date:s=>({type:"date",data:s.toISOString()})},r=this.toTypeName(e);return i[r](e)}unwrap(e){let n={any:i=>fa(i.data,i.dates,i.undefineds),date:i=>mr(i.data)}[e?.type];return n?n(e):(console.warn(`Unknown stored value type "${e?.type}", reading it as-is
|
|
17
17
|
at namespace "${this.name}"`),e?.data)}attach(e){return this.owner=e,this}detach(e){return this.owner===e&&(this.owner=null),this}reportChange(e,t,n){!this.owner||fr(t,n)||this.owner.reportChange({namespace:this.key,key:String(e),previous:t,next:n})}},rn=class rn{constructor(){this.events=new _;this.namespaces={};this.restoreBatch=null;this.events.setMaxListeners(64)}static createNamespace(e,t,n){return new Ht(e,t,n)}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,e.attach(this),this}getNamespace(e){if(!this.namespaces[e])throw new E(`Namespace ${e} is not initialized, did you forget to register it?
|
|
18
|
-
Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]?.detach(this),this.namespaces[e]=t,t.attach(this),this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return this.namespaces[e]?.detach(this),delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}onChange(e,t,n){let i=typeof e=="string"?e:null,r=typeof t=="string"?t:null,s=typeof e=="function"?e:typeof t=="function"?t:n;if(!s)throw new E("No listener provided when subscribing to storable changes");return this.events.on(rn.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(rn.EventTypes["event:storable.restore"],e)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}let t=this.restoreBatch=new Set;try{Object.entries(e).forEach(([n,i])=>{this.namespaces[n]||this.addNamespace(new Ht(n,{})),this.namespaces[n].deserialize(i)})}finally{this.restoreBatch=null}this.events.emit(rn.EventTypes["event:storable.restore"],{namespaces:Array.from(t)})}clear(){return this.values().forEach(e=>e.detach(this)),this.namespaces={},this}reportChange(e){this.events.emit(rn.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(rn.EventTypes["event:storable.restore"],{namespaces:[e]})}};rn.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var Zn=rn;var xf={};var Nn=class extends Mn{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let c=a.getFutureActions(e,i).filter(l=>!r.has(l));s.push(...c)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var tt=class extends X{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Ft.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=S.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[s]),a}else if(this.type===Ft.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.seek){let[i]=this.contentNode.getContent(),r=e.audioManager.getPosition(this.callee),s=S.forward(e.audioManager.seek(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{e.audioManager.seek(this.callee,a)},[r]),s}else if(this.type===Ft.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};tt.ActionTypes=Ft;var nt={bgm:"bgm",sound:"sound",voice:"voice"},_i=8,sn=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function Gn(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var ti=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=c=>{t.set(c.id,{id:c.id,parentId:c.parentId??null,volume:Gn(c.volume)})};Object.values(nt).forEach(c=>n({id:c}));let i=new Set;e.forEach(c=>{let l=c?.id;if(typeof l!="string"||l.trim().length===0)throw new sn(`Audio bus id must be a non-empty string, got ${JSON.stringify(l)}.`);if(i.has(l))throw new sn(`Audio bus "${l}" is declared more than once.`);i.add(l),n(c)}),o.assertResolvable(t);let r=[],s=new Map,a=c=>{let l=s.get(c);if(l)return l;let u=t.get(c),d=u.parentId===null?null:a(u.parentId),p={id:u.id,parentId:u.parentId,volume:u.volume,depth:d?d.depth+1:1};return s.set(c,p),r.push(p),p};return t.forEach(c=>a(c.id)),new o(r,s)}static isSeeded(e){return Object.values(nt).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new sn(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new sn(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>_i)throw new sn(`Audio bus "${t.id}" nests deeper than ${_i}: ${n.join(" -> ")}.`);r=s}})}getNodes(){return this.nodes}get(e){return this.index.get(e)??null}has(e){return this.index.has(e)}isUnder(e,t){let n=this.index.get(e),i=0;for(;n&&i<=_i;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},hr=ti.resolve();function Ol(o){hr=o}function gr(){return hr}function Ji(o,e){let t=hr;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var ga={[nt.bgm]:"bgmVolume",[nt.sound]:"soundVolume",[nt.voice]:"voiceVolume"};function ya(o){let e={};return Object.entries(ga).forEach(([t,n])=>{e[t]={get:()=>Gn(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var ei=class ei{constructor(e,t={}){this.declarations=e;this.events=new _;this.overrides=new Map;this.aliasTokens=[];this.tree=null;this.events.setMaxListeners(64),this.aliases=t,Object.entries(t).forEach(([n,i])=>{this.aliasTokens.push(i.subscribe(r=>{this.announce(n,Gn(r))}))})}dispose(){this.aliasTokens.forEach(e=>e.cancel()),this.aliasTokens.length=0}announce(e,t){let n=t;try{n=this.getEffectiveVolume(e)}catch{}this.events.emit(ei.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=ti.resolve(this.declarations()??[]),Ol(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=Gn(t),i=this.aliases[e];return i?(i.set(n),this):(this.overrides.set(e,n),this.announce(e,n),this)}setVolumes(e){return Object.entries(e).forEach(([t,n])=>this.setVolume(t,n)),this}getVolume(e){let t=this.aliases[e];return t?Gn(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return Gn(this.getDeclaredVolume(e)*this.getVolume(e))}list(){return this.getTree().getNodes().map(e=>({id:e.id,parentId:e.parentId,volume:this.getVolume(e.id),declaredVolume:e.volume,effectiveVolume:this.getEffectiveVolume(e.id)}))}getVolumes(){let e={};return this.list().forEach(t=>{e[t.id]=t.volume}),e}onVolumeChange(e){return this.events.on(ei.EventTypes["event:audioBus.volumeChange"],e)}};ei.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var ni=ei;var va=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(va||{}),Ce=class Ce extends le{static toSound(e){return e==null?null:typeof e=="string"?new Ce({src:e}):e}static isSound(e){return e instanceof Ce}static voice(e){let t=typeof e=="string"?{src:e}:e;return new Ce({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new Ce({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new Ce({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=Ce.DefaultUserConfig.create(t),[i]=n.extract(Ce.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e,t){return gr().isUnder(this.config.type,nt.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(tt.ActionTypes.play,[{end:this.state.volume,duration:e||0,waitForEnd:t?.waitForEnd===!0}])}stop(e){return this.pushAction(tt.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(tt.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(tt.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(tt.ActionTypes.setRate,[e])}pause(e){return this.pushAction(tt.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(tt.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(tt.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state:Ce.StateSerializer.serialize(this.state)}}fromData(e){return this.state=Ce.StateSerializer.deserialize(e.state),this}copy(){return new Ce(this.userConfig.get())}reset(){return super.reset(),this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return Ce.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new tt(this.chain(),e,new C().setContent(t)))}};Ce.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",Ce.DefaultUserConfig=new j({src:Ce.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Ce.DefaultConfig=new j({src:Ce.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Ce.DefaultState=new j({volume:1,rate:1,paused:!1,muted:!1}),Ce.StateSerializer=new qe;var fe=Ce;var Tn=class Tn{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===Tn.SrcTypes.image?t.add(s):r===Tn.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof F?F.getSrcURL(e):e.type==="image"?F.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(ee,z.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(P.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof ve){let n=t;if(t.is(ve,ht.setSrc)){let i=t.contentNode.getContent()[0];if(P.isImageSrc(i))return{type:"image",src:P.srcToURL(i),activeType:"scene"}}else{if(t.type===ht.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===ht.setAppearance){let i=t.contentNode.getContent()[0];if(F.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(F.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:F.getSrcFromTags(i,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof fe){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof F||P.isStaticImageData(e)){if(e instanceof F){if(!P.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(F.getSrcURL(e)))return this}else if(this.isSrcRegistered(P.srcToURL(e.src)))return this;this.src.push({type:"image",src:P.isStaticImageData(e)?P.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof fe?t:new fe({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof fe?e.getSrc():e;return this.src.some(n=>n.type===Tn.SrcTypes.audio?t===n.src.getSrc():n.type===Tn.SrcTypes.image?t===F.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};Tn.SrcTypes={image:"image",video:"video",audio:"audio"};var Re=Tn;import*as Na from"howler";var ze=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var ut=class o{static isTextEvent(e){return e instanceof o}static expression(e,t,n={}){return new o({expression:{image:e,appearance:t},sound:n.sound})}static sound(e){return new o({sound:e})}constructor(e){this.config=e}};function Sa(o,e){let{render:t,data:n,...i}=e,r=Y(o,i);return"render"in e?r.render=e.render:"render"in o&&(r.render=o.render),"data"in e?r.data=e.data:"data"in o&&(r.data=o.data),r}var Se=class Se{static isWord(e){return e instanceof Se}static color(e,t){return Se.isWord(e)?e.copy().assign({color:t}):new Se(e,{color:t})}static bold(e){return Se.isWord(e)?e.copy().assign({bold:!0}):new Se(e,{bold:!0})}static italic(e){return Se.isWord(e)?e.copy().assign({italic:!0}):new Se(e,{italic:!0})}static emphasis(e,t={}){return Se.isWord(e)?e.copy().assign({emphasis:t}):new Se(e,{emphasis:t})}static custom(e,t,n={}){let i={...n,render:t};return Se.isWord(e)?e.copy().assign(i):new Se(e,i)}static getText(e){return e.filter(t=>!t.isPause()&&!t.isTextEvent()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=Sa(Se.defaultConfig,t)}evaluate(e){if(ze.isPause(this.text))return[this];if(ut.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>Se.isWord(n)?n.inherit(this.config).evaluate(e):new Se(n,this.config)).flat():Se.isWord(t)?t.inherit(this.config).evaluate(e):[new Se(t,this.config)]}return[this]}inherit(e){return this.config.color=this.config.color||e.color,this.config.italic=this.config.italic??e.italic,this.config.bold=this.config.bold??e.bold,this.config.cps=this.config.cps??e.cps,this.config.emphasis=this.config.emphasis??e.emphasis,this.config.fontScale=this.config.fontScale??e.fontScale,this}assign(e){return this.config=Sa(this.config,e),this}copy(){return new Se(this.text,this.config)}isPause(){return ze.isPause(this.text)}isTextEvent(){return ut.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Se.defaultConfig={},Se.defaultColor="#000";var ie=Se;var pt=class pt{static isSentence(e){return e instanceof pt}static toSentence(e){return pt.isSentence(e)?e:new pt(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return ie.isWord(e)?e:new ie(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[ie.isWord(e)?e:new ie(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(pt.isSingleWord):pt.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||ie.isWord(e)||ze.isPause(e)||ut.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=pt.format(e),this.config=Y(pt.defaultConfig,{...t,voice:typeof t.voice=="string"?fe.voice(t.voice):fe.toSound(t.voice)}),this.state=_s(pt.defaultState)}toData(){return null}fromData(e){return this.state=Y(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...pt.formatStaticWord(i))}return t}copy(){return new pt([...this.text],this.config)}};pt.defaultConfig={voice:null,character:null,voiceId:null},pt.defaultState={};var me=pt;var Zi=class{constructor(e,t){this.game=e,this.prefix=t}log(e,...t){this.isEnabled("log")&&console.log(...this.colorLog("gray",e,...t))}info(e,...t){this.isEnabled("info")&&console.info(...this._log(e,...t))}warn(e,...t){this.isEnabled("warn")&&console.warn(...this._log(e,...t))}error(e,...t){this.isEnabled("error")&&console.error(...this._log(e,...t))}debug(e,...t){this.isEnabled("debug")&&console.debug(...this.colorLog("gray",e,...t))}trace(e,...t){this.isEnabled("trace")&&console.trace(this._log(e,...t))}weakWarn(e,...t){this.isEnabled("warn")&&console.log(...this.colorLog("yellow",e,...t))}weakError(e,...t){this.isEnabled("error")&&console.log(...this.colorLog("red",e,...t))}verbose(e,...t){this.isEnabled("verbose")&&console.log(...this.colorLog("gray",e,...t))}group(e,t=!1){let n=this._log(e).join(" ");return this.isEnabled("info")&&(t?console.groupCollapsed(n):console.group(n)),{end:()=>{this.isEnabled("info")&&console.groupEnd()}}}isEnabled(e){return typeof this.game.config.app.logger=="boolean"?this.game.config.app.logger:this.game.config.app.logger[e]}_log(e,...t){return t.length===0?[this.prefix||"",e]:[`${this.prefix||""} [${e}]`,...t]}colorLog(e,t,...n){if(n.length===0)return[`%c${this.prefix||""} ${t}`,`color: ${e}`];let i=[],r=[],s=[];return this.prefix?(i.push(`%c${this.prefix} [${t}]`),r.push(`color: ${e}`)):(i.push(`%c[${t}]`),r.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(i.push(`%c${a}`),r.push(`color: ${e}`)):(i.push("%O"),s.push(a),r.push(""))}),[i.join(" ")].concat(r,s)}};var an=class extends X{executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};an.ActionTypes=Ys;var xe=class o extends le{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new an(t,an.ActionTypes.action,new C().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new an(this.chain(),an.ActionTypes.action,new C().setContent(e))]}};var Hl={volume:1,limit:1/0},Vl=class ba{constructor(e,t,n,i){this.subChannels=new Map,this.tokens=new Set,this.tokenQueue=[],this.muted=!1,this.removed=!1,this.name=e,this.audioProvider=t,this.parentChannel=i??null,this.options={...Hl,...n},this.volume=this.options.volume;let r=this.audioProvider.getAudioContext();this.gainNode=r.createGain(),this.gainNode.gain.value=this.muted?0:this.volume,this.connectToParent()}connectToParent(){this.parentChannel?this.gainNode.connect(this.parentChannel.getGainNode()):this.gainNode.connect(this.audioProvider.getAudioContext().destination)}getGainNode(){return this.gainNode}ensureNotRemoved(){if(this.removed)throw new Error(`Channel "${this.name}" has been removed and cannot be used.`)}getName(){return this.name}async play(e,t){if(this.ensureNotRemoved(),this.tokens.size>=this.options.limit){let r=this.tokenQueue.shift();r&&r.stop()}let n=await this.audioProvider.createToken(e,t,this.gainNode);this.tokens.add(n),this.tokenQueue.push(n);let i=()=>{this.tokens.delete(n);let r=this.tokenQueue.indexOf(n);r!==-1&&this.tokenQueue.splice(r,1)};return n.once("ended",i),n.once("stop",i),n}createChannel(e,t){if(this.ensureNotRemoved(),this.subChannels.has(e))throw new Error(`Channel "${e}" already exists under "${this.name}".`);this.audioProvider.checkChannelLimit();let n=new ba(e,this.audioProvider,t,this);return this.subChannels.set(e,n),this.audioProvider.registerChannel(n),n}getChannel(e){return this.ensureNotRemoved(),this.subChannels.get(e)??null}getChannels(){return this.ensureNotRemoved(),Array.from(this.subChannels.values())}setVolume(e){return this.ensureNotRemoved(),this.volume=Math.max(0,Math.min(1,e)),this.muted||(this.gainNode.gain.value=this.volume),this}getVolume(){return this.volume}mute(e){return this.ensureNotRemoved(),this.muted=e!==void 0?e:!0,this.gainNode.gain.value=this.muted?0:this.volume,this}unmute(){return this.mute(!1)}isMuted(){return this.muted}remove(){if(this.removed)return this;this.removed=!0;for(let t of this.tokens)t.stop();this.tokens.clear();let e=Array.from(this.subChannels.values());this.subChannels.clear();for(let t of e)t.remove();try{this.gainNode.disconnect()}catch(t){console.warn("Failed to disconnect Channel gain node during remove().",t)}return this.audioProvider.unregisterChannel(this),this.parentChannel&&this.parentChannel.removeSubChannel(this.name),this}removeSubChannel(e){this.subChannels.delete(e)}getTokens(){this.ensureNotRemoved();let e=[...this.tokenQueue];for(let t of this.subChannels.values())e.push(...t.getTokens());return e}isRemoved(){return this.removed}getParent(){return this.parentChannel}getOptions(){return{...this.options}}},Aa=!1;function Ul(o){Aa=o}function cn(o,e){Aa||(e!==void 0?console.warn(o,e):console.warn(o))}var Wl=class{constructor(o,e){this.currentSource=null,this.mediaElementSource=null,this.endedHandler=null,this.eventListeners=new Map,this.audioContext=o,this.gainNode=e}setSource(o){this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.setupEventListeners()}getSource(){return this.currentSource}refreshSource(o){let e=new Map(this.eventListeners);this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.eventListeners=e,this.setupEventListeners()}disconnectSource(){if(this.currentSource){if(this.removeAllEventListeners(),this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.disconnect()}catch(o){cn("Failed to disconnect AudioBufferSourceNode in disconnectSource().",o)}else this.currentSource instanceof HTMLAudioElement&&(this.currentSource.pause(),this.currentSource.src="",this.currentSource.load());if(this.mediaElementSource){try{this.mediaElementSource.disconnect()}catch(o){cn("Failed to disconnect MediaElementAudioSourceNode in disconnectSource().",o)}this.mediaElementSource=null}this.currentSource=null}}setupEventListeners(){this.currentSource&&(this.endedHandler=o=>{this.emit("ended")},this.currentSource instanceof HTMLAudioElement?this.currentSource.addEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.addEventListener("ended",this.endedHandler))}removeAllEventListeners(){!this.currentSource||!this.endedHandler||(this.currentSource instanceof HTMLAudioElement?this.currentSource.removeEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.removeEventListener("ended",this.endedHandler),this.endedHandler=null)}emit(o){let e=this.eventListeners.get(o);e&&[...e].forEach((t,n)=>{try{t.callback()}catch(i){console.error(`Error in event listener for '${o}':`,i)}t.once&&e.splice(e.indexOf(t),1)})}on(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!1})}off(o,e){let t=this.eventListeners.get(o);if(!t)return;let n=t.findIndex(i=>i.callback===e);n!==-1&&t.splice(n,1)}once(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!0})}stop(){if(this.currentSource){if(this.currentSource instanceof HTMLAudioElement)this.currentSource.pause(),this.currentSource.currentTime=0;else if(this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.stop()}catch(o){cn("Failed to stop AudioBufferSourceNode in stop().",o)}}}destroy(){this.disconnectSource(),this.eventListeners.clear()}start(o=0,e=0){this.currentSource instanceof AudioBufferSourceNode?this.currentSource.start(o,e):this.currentSource instanceof HTMLAudioElement&&this.currentSource.play()}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},Ta=class{constructor(o,e){this.token=o,this.endVolume=e,this.cancelled=!1,this.finishedInternal=!1,this._finished=new Promise(t=>{this.resolveFinished=t})}get finished(){return this._finished}cancel(){this.cancelled||this.finishedInternal||(this.cancelled=!0,this.resolveFinished())}finish(){this.finishedInternal||(this.finishedInternal=!0,this.token.setVolume(this.endVolume),this.resolveFinished())}isCancelled(){return this.cancelled}isFinished(){return this.finishedInternal}getTargetVolume(){return this.endVolume}},Bl=class{constructor(o,e,t={},n){this._isPlaying=!1,this._isPaused=!1,this._isMuted=!1,this.volume=1,this.rate=1,this.contextStartTime=0,this.startOffset=0,this.pauseOffset=0,this.duration=0,this.currentFade=null,this.audioContext=o,this.volume=t.volume??1,this.rate=t.rate??1,this.startOffset=t.startOffset??0,this.duration=t.duration??0,this.outputNode=n??o.destination,this.gainNode=o.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.outputNode),this.sourceController=new Wl(o,this.gainNode),this.sourceController.setSource(e);let i=this.startOffset;this.sourceController.start(0,i),this.contextStartTime=this.audioContext.currentTime,this._isPlaying=!0,this.duration>0&&setTimeout(()=>{this._isPlaying&&this.stop()},this.duration*1e3)}emit(o){if(this.sourceController.emit(o),o==="ended"){this._isPlaying=!1;try{this.gainNode.disconnect()}catch(e){cn("Failed to disconnect gain node on natural end.",e)}}}setVolume(o){return this.currentFade&&(this.currentFade.cancel(),this.currentFade=null),o=Math.max(0,Math.min(1,o)),this.volume=o,this._isMuted||(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=o),this}getVolume(){return this.volume}mute(o){let e=o!==void 0?o:!0;if(this._isMuted=e,this.currentFade&&!this.currentFade.isFinished()&&!this.currentFade.isCancelled()){let t=this.currentFade.getTargetVolume();this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.volume=t,this.gainNode.gain.value=e?0:t,this.currentFade.finish(),this.currentFade=null}else this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=e?0:this.volume;return this}unmute(){return this.mute(!1)}isMuted(){return this._isMuted}pause(){if(!this._isPlaying||this._isPaused)return this;let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?(o.pause(),this.pauseOffset=o.currentTime):o instanceof AudioBufferSourceNode&&(this.pauseOffset=this.getCurrentTime(),this.sourceController.stop()),this._isPlaying=!1,this._isPaused=!0,this.emit("pause"),this}resume(){if(!this._isPaused)return this;let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement){let e=o.play();e&&typeof e.catch=="function"&&e.catch(()=>{this._isPlaying=!1,this._isPaused=!0})}else if(o instanceof AudioBufferSourceNode){let e=this.audioContext.createBufferSource();e.buffer=o.buffer,e.playbackRate.value=this.rate,e.loop=o.loop,e.loopStart=o.loopStart,e.loopEnd=o.loopEnd,this.sourceController.refreshSource(e),this.startOffset=this.pauseOffset,this.contextStartTime=this.audioContext.currentTime,this.sourceController.start(0,this.pauseOffset)}return this._isPlaying=!0,this._isPaused=!1,this.emit("resume"),this}isPlaying(){return this._isPlaying}isPaused(){return this._isPaused}stop(o={}){let{fadeDuration:e=0}=o;return e>0?this.fade(this.getVolume(),0,e).finished.then(()=>{this.doStop()}):this.doStop(),this}doStop(){this.sourceController.stop(),this._isPlaying=!1,this._isPaused=!1,this.emit("stop"),this.sourceController.destroy();try{this.gainNode.disconnect()}catch(o){cn("Failed to disconnect gain node on stop().",o)}}setRate(o){o=Math.max(.001,o),this.rate=o;let e=this.sourceController.getSource();return e instanceof HTMLAudioElement?e.playbackRate=o:e instanceof AudioBufferSourceNode&&(e.playbackRate.value=o),this}getRate(){return this.rate}seek(o){o=Math.max(0,o);let e=this.sourceController.getSource();if(e instanceof HTMLAudioElement)e.currentTime=o,this.emit("seek");else if(e instanceof AudioBufferSourceNode){let t=this.getCurrentTime();if(Math.abs(o-t)>.01){if(this._isPlaying){this.sourceController.stop();let n=this.audioContext.createBufferSource();n.buffer=e.buffer,n.playbackRate.value=this.rate,n.loop=e.loop,n.loopStart=e.loopStart,n.loopEnd=e.loopEnd,this.sourceController.refreshSource(n),this.startOffset=this.audioContext.currentTime-o,this.sourceController.start(0,o)}else this._isPaused&&(this.pauseOffset=o);this.emit("seek")}}return this}getCurrentTime(){let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement)return o.currentTime;if(o instanceof AudioBufferSourceNode){if(this._isPaused)return this.pauseOffset;if(this._isPlaying)return(this.audioContext.currentTime-this.contextStartTime)*this.rate+this.startOffset}return 0}getDuration(){let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?o.duration||0:o instanceof AudioBufferSourceNode&&o.buffer?o.buffer.duration:this.duration}fade(o,e,t){if(this.currentFade&&this.currentFade.cancel(),o=Math.max(0,Math.min(1,o)),e=Math.max(0,Math.min(1,e)),t=Math.max(0,t),t===0){this.setVolume(e);let r=new Ta(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new Ta(this,e);this.currentFade=n;let i=this.audioContext.currentTime;return this.gainNode.gain.setValueAtTime(o,i),this.gainNode.gain.linearRampToValueAtTime(e,i+t/1e3),setTimeout(()=>{!n.isCancelled()&&!n.isFinished()&&(this.volume=e,n.finish(),this.currentFade=null)},t),n}on(o,e){return this.sourceController.on(o,e),this}off(o,e){return this.sourceController.off(o,e),this}once(o,e){return this.sourceController.once(o,e),this}},zl=class{constructor(o){this.alive=!0,this.refCount=0,this.audioBuffer=o}addRef(){this.refCount++}releaseRef(){this.refCount>0&&this.refCount--}getRefCount(){return this.refCount}async unload(){this.refCount>0||(this.alive=!1)}async forceUnload(){this.alive=!1,this.refCount=0}isAlive(){return this.alive}raw(){if(!this.alive)throw new Error("CachedAudio has been unloaded.");return this.audioBuffer}},Kl=10*1024*1024,$l=class{constructor(o){this.cache=new Map,this.loadingPromises=new Map,this.audioContext=o}async load(o){let e=this.cache.get(o);if(e&&e.isAlive())return e;let t=this.loadingPromises.get(o);if(t)return t;let n=this.doLoad(o);this.loadingPromises.set(o,n);try{let i=await n;return this.cache.set(o,i),i}finally{this.loadingPromises.delete(o)}}async doLoad(o){let e=await(await fetch(o)).arrayBuffer(),t=await this.audioContext.decodeAudioData(e);return new zl(t)}clear(){for(let o of this.cache.values())o.forceUnload();this.cache.clear(),this.loadingPromises.clear()}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size}}},jl={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},Ca=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...jl,...o},Ul(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new $l(this.audioContext),this.masterChannel=new Vl("__master__",this,{volume:this.options.volume},null),this.initialize()}async onceReady(){return this.readyPromise?(await this.readyPromise,this):this}initialize(){this.isReady||(this.readyPromise=this.waitForUnlock())}waitForUnlock(){return typeof document>"u"?(this.isReady=!0,Promise.resolve()):this.audioContext.state==="running"?(this.isReady=!0,Promise.resolve()):new Promise(o=>{let e=()=>{if(this.destroyed){this.clearUnlockHandler(),o();return}this.audioContext.resume().then(()=>{this.audioContext.state==="running"&&(this.clearUnlockHandler(),this.isReady=!0,o())}).catch(t=>{cn("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:c=!1}=e??{},l,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")l=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),l=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),l=p}let d=new Bl(this.audioContext,l,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(l instanceof AudioBufferSourceNode?(l.loop=c,c&&s!==void 0&&(l.loopStart=r,l.loopEnd=s)):l instanceof HTMLAudioElement&&(l.loop=c),u){let p=!1,h=()=>{p||(p=!0,u.releaseRef?.())};d.once("ended",h),d.once("stop",h)}return d}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<Kl?"full":"stream"}catch(t){return cn("Failed to resolve load mode via HEAD request, falling back to 'stream'.",t),"stream"}}createStreamSource(o){let e=new Audio(o);return e.crossOrigin="anonymous",e}checkChannelLimit(){if(this.registeredChannels.size+1>=this.options.maxChannels)throw new Error(`Maximum number of channels (${this.options.maxChannels}) reached.`)}registerChannel(o){this.registeredChannels.add(o)}unregisterChannel(o){this.registeredChannels.delete(o)}setVolume(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.setVolume(o),this}getVolume(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getVolume()}mute(o){return this.ensureNotDestroyed(),this.ensureReady(),o===void 0?this.masterChannel.mute():this.masterChannel.mute(o),this}unmute(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.unmute(),this}isMuted(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.isMuted()}createChannel(o,e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.createChannel(o,e)}getChannel(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannel(o)}getChannels(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannels()}async load(o){return this.ensureNotDestroyed(),this.ensureReady(),this.audioCache.load(o)}async play(o,e){this.ensureNotDestroyed(),this.ensureReady();let t=this.masterChannel.getTokens();for(let n of t)try{n.stop()}catch{}return this.masterChannel.play(o,e)}getTokens(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getTokens()}destroy(){this.destroyed||(this.destroyed=!0,this.clearUnlockHandler(),this.audioCache.clear(),this.masterChannel.remove(),this.registeredChannels.clear(),this.audioContext.close().catch(o=>{cn("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var de=class de{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new Ca({maxChannels:de.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=de.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,de.BusRampTimeConstant),r.setValueAtTime(s,a+de.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${nt.sound}" instead.`)),this.channels.get(nt.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=de.defaultFade(e)){let n=new S;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=de.clipRegionOf(e),a=await i.play(r,{volume:0,...de.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,s);let c=e.state.muted??!1;a.mute(c),e.state.muted=c,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,!e.config.loop&&t.waitForEnd!==!1&&await new Promise(l=>{a.once("ended",()=>l())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t=de.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new E(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=await n.play(i,{volume:0,...de.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(s,r);let a=e.state.muted??!1;return s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:i,originalVolume:t.end}),t.duration>0?s.fade(0,t.end,t.duration):s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,s}catch(n){throw this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,n),n}}stop(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return this.arm(e,i),t===0?(i.token.stop(),this.state.delete(e),n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.token.stop(),this.state.delete(e),n.resolve()}),n}setVolume(e,t,n=0){let i=new S;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new S;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}arm(e,t){let n=(t.transport??0)+1;return t.transport=n,()=>this.state.get(e)===t&&t.transport===n}pause(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);e.markDirty();let r=this.arm(e,i);return t===0?(i.pausePosition=i.token.getCurrentTime(),i.token.pause(),e.state.paused=!0,n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{if(!r()){n.resolve();return}i.pausePosition=i.token.getCurrentTime(),i.token.pause(),i.token.setVolume(i.originalVolume),e.state.paused=!0,n.resolve()}),n}resume(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);e.markDirty();let r=this.arm(e,i);return t===0?(i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,n.resolve()):(i.token.setVolume(0),i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,i.token.fade(0,i.originalVolume,t).finished.then(()=>{if(!r()){n.resolve();return}e.state.paused=!1,n.resolve()})),n}seek(e,t){if(!this.state.has(e))return S.resolve(void 0);let n=this.state.get(e),i=de.clampToRegion(t,de.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),S.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,c=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=c<i?c:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,S.resolve(void 0)):S.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime(),...e.state.paused?{paused:!0}:{}}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...de.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(de.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let c=e.state.muted??!1;a.mute(c),e.state.muted=c;let l=t.paused??e.state.paused??!1;e.state.paused=l,l?a.pause():t.isPlaying||a.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}preload(e){return this.ready.then(()=>this.sound.load(e.config.src)).then(()=>{}).catch(t=>{this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${e.config.src}")`,t)})}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),this.isReady&&this.busTree&&this.busTree.getNodes().forEach(e=>{this.applyBusVolume(this.channels.get(e.id),this.mixer.getEffectiveVolume(e.id),!1)})}setBusVolume(e,t){this.mixer.setVolume(e,t)}getBusVolume(e){return this.mixer.getVolume(e)}getBuses(){return this.mixer.list()}setGroupVolume(e,t){this.setBusVolume(e,t)}getGroupVolume(e){return this.getBusVolume(e)}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}destroy(){this.reset(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};de.MaxChannels=1024,de.BusRampTimeConstant=.02,de.BusRampSettle=de.BusRampTimeConstant*5;var eo=de;var to=class{constructor(e){this.config=e;this.watching=null;this.warnings=[]}observe(e){return this.watching=e,this}warn(e,t){return this.warnings.push([e,t]),this.watching?.logger.warn(t),t}getWarnings(){return[...this.warnings]}};import*as Jl from"html-to-image";var we=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),ct(()=>{this.preventAttach()})}static proxy(e){let t=new S,n=new S,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new E("Cannot create an 'any' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new E("Cannot create an 'all' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let c=e[a];i.attachChild(c),c.then(l=>{r[a]=l,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new S,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?ct(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new U(()=>(i&&i.abort(),t))),i=e(t),i?ct(()=>s()):ct(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}isFailed(){return this._status==="failed"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onFailed(e){this._onFailed.push(e)}onSettled(e){this.isSettled()?ct(e):(this.onResolved(e),this.onCancelled(e),this.onFailed(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new E(`Attaching to this timeline violates the timeline's state.
|
|
18
|
+
Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]?.detach(this),this.namespaces[e]=t,t.attach(this),this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return this.namespaces[e]?.detach(this),delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}onChange(e,t,n){let i=typeof e=="string"?e:null,r=typeof t=="string"?t:null,s=typeof e=="function"?e:typeof t=="function"?t:n;if(!s)throw new E("No listener provided when subscribing to storable changes");return this.events.on(rn.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(rn.EventTypes["event:storable.restore"],e)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}let t=this.restoreBatch=new Set;try{Object.entries(e).forEach(([n,i])=>{this.namespaces[n]||this.addNamespace(new Ht(n,{})),this.namespaces[n].deserialize(i)})}finally{this.restoreBatch=null}this.events.emit(rn.EventTypes["event:storable.restore"],{namespaces:Array.from(t)})}clear(){return this.values().forEach(e=>e.detach(this)),this.namespaces={},this}reportChange(e){this.events.emit(rn.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(rn.EventTypes["event:storable.restore"],{namespaces:[e]})}};rn.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var Zn=rn;var wf={};var Nn=class extends Mn{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let c=a.getFutureActions(e,i).filter(l=>!r.has(l));s.push(...c)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var tt=class extends X{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Ft.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=S.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[s]),a}else if(this.type===Ft.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Ft.seek){let[i]=this.contentNode.getContent(),r=e.audioManager.getPosition(this.callee),s=S.forward(e.audioManager.seek(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{e.audioManager.seek(this.callee,a)},[r]),s}else if(this.type===Ft.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};tt.ActionTypes=Ft;var nt={bgm:"bgm",sound:"sound",voice:"voice"},_i=8,sn=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function Gn(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var ti=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=c=>{t.set(c.id,{id:c.id,parentId:c.parentId??null,volume:Gn(c.volume)})};Object.values(nt).forEach(c=>n({id:c}));let i=new Set;e.forEach(c=>{let l=c?.id;if(typeof l!="string"||l.trim().length===0)throw new sn(`Audio bus id must be a non-empty string, got ${JSON.stringify(l)}.`);if(i.has(l))throw new sn(`Audio bus "${l}" is declared more than once.`);i.add(l),n(c)}),o.assertResolvable(t);let r=[],s=new Map,a=c=>{let l=s.get(c);if(l)return l;let u=t.get(c),d=u.parentId===null?null:a(u.parentId),p={id:u.id,parentId:u.parentId,volume:u.volume,depth:d?d.depth+1:1};return s.set(c,p),r.push(p),p};return t.forEach(c=>a(c.id)),new o(r,s)}static isSeeded(e){return Object.values(nt).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new sn(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new sn(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>_i)throw new sn(`Audio bus "${t.id}" nests deeper than ${_i}: ${n.join(" -> ")}.`);r=s}})}getNodes(){return this.nodes}get(e){return this.index.get(e)??null}has(e){return this.index.has(e)}isUnder(e,t){let n=this.index.get(e),i=0;for(;n&&i<=_i;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},hr=ti.resolve();function Hl(o){hr=o}function gr(){return hr}function Ji(o,e){let t=hr;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var ga={[nt.bgm]:"bgmVolume",[nt.sound]:"soundVolume",[nt.voice]:"voiceVolume"};function ya(o){let e={};return Object.entries(ga).forEach(([t,n])=>{e[t]={get:()=>Gn(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var ei=class ei{constructor(e,t={}){this.declarations=e;this.events=new _;this.overrides=new Map;this.aliasTokens=[];this.tree=null;this.events.setMaxListeners(64),this.aliases=t,Object.entries(t).forEach(([n,i])=>{this.aliasTokens.push(i.subscribe(r=>{this.announce(n,Gn(r))}))})}dispose(){this.aliasTokens.forEach(e=>e.cancel()),this.aliasTokens.length=0}announce(e,t){let n=t;try{n=this.getEffectiveVolume(e)}catch{}this.events.emit(ei.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=ti.resolve(this.declarations()??[]),Hl(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=Gn(t),i=this.aliases[e];return i?(i.set(n),this):(this.overrides.set(e,n),this.announce(e,n),this)}setVolumes(e){return Object.entries(e).forEach(([t,n])=>this.setVolume(t,n)),this}getVolume(e){let t=this.aliases[e];return t?Gn(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return Gn(this.getDeclaredVolume(e)*this.getVolume(e))}list(){return this.getTree().getNodes().map(e=>({id:e.id,parentId:e.parentId,volume:this.getVolume(e.id),declaredVolume:e.volume,effectiveVolume:this.getEffectiveVolume(e.id)}))}getVolumes(){let e={};return this.list().forEach(t=>{e[t.id]=t.volume}),e}onVolumeChange(e){return this.events.on(ei.EventTypes["event:audioBus.volumeChange"],e)}};ei.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var ni=ei;var va=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(va||{}),Ce=class Ce extends le{static toSound(e){return e==null?null:typeof e=="string"?new Ce({src:e}):e}static isSound(e){return e instanceof Ce}static voice(e){let t=typeof e=="string"?{src:e}:e;return new Ce({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new Ce({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new Ce({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=Ce.DefaultUserConfig.create(t),[i]=n.extract(Ce.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e,t){return gr().isUnder(this.config.type,nt.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(tt.ActionTypes.play,[{end:this.state.volume,duration:e||0,waitForEnd:t?.waitForEnd===!0}])}stop(e){return this.pushAction(tt.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(tt.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(tt.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(tt.ActionTypes.setRate,[e])}pause(e){return this.pushAction(tt.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(tt.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(tt.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state:Ce.StateSerializer.serialize(this.state)}}fromData(e){return this.state=Ce.StateSerializer.deserialize(e.state),this}copy(){return new Ce(this.userConfig.get())}reset(){return super.reset(),this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return Ce.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new tt(this.chain(),e,new C().setContent(t)))}};Ce.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",Ce.DefaultUserConfig=new j({src:Ce.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Ce.DefaultConfig=new j({src:Ce.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Ce.DefaultState=new j({volume:1,rate:1,paused:!1,muted:!1}),Ce.StateSerializer=new qe;var fe=Ce;var Tn=class Tn{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===Tn.SrcTypes.image?t.add(s):r===Tn.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof F?F.getSrcURL(e):e.type==="image"?F.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(ee,z.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(P.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof ve){let n=t;if(t.is(ve,ht.setSrc)){let i=t.contentNode.getContent()[0];if(P.isImageSrc(i))return{type:"image",src:P.srcToURL(i),activeType:"scene"}}else{if(t.type===ht.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===ht.setAppearance){let i=t.contentNode.getContent()[0];if(F.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(F.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:F.getSrcFromTags(i,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof fe){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof F||P.isStaticImageData(e)){if(e instanceof F){if(!P.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(F.getSrcURL(e)))return this}else if(this.isSrcRegistered(P.srcToURL(e.src)))return this;this.src.push({type:"image",src:P.isStaticImageData(e)?P.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof fe?t:new fe({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof fe?e.getSrc():e;return this.src.some(n=>n.type===Tn.SrcTypes.audio?t===n.src.getSrc():n.type===Tn.SrcTypes.image?t===F.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};Tn.SrcTypes={image:"image",video:"video",audio:"audio"};var Re=Tn;import*as Na from"howler";var ze=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var ut=class o{static isTextEvent(e){return e instanceof o}static expression(e,t,n={}){return new o({expression:{image:e,appearance:t},sound:n.sound})}static sound(e){return new o({sound:e})}constructor(e){this.config=e}};function Sa(o,e){let{render:t,data:n,...i}=e,r=Y(o,i);return"render"in e?r.render=e.render:"render"in o&&(r.render=o.render),"data"in e?r.data=e.data:"data"in o&&(r.data=o.data),r}var Se=class Se{static isWord(e){return e instanceof Se}static color(e,t){return Se.isWord(e)?e.copy().assign({color:t}):new Se(e,{color:t})}static bold(e){return Se.isWord(e)?e.copy().assign({bold:!0}):new Se(e,{bold:!0})}static italic(e){return Se.isWord(e)?e.copy().assign({italic:!0}):new Se(e,{italic:!0})}static emphasis(e,t={}){return Se.isWord(e)?e.copy().assign({emphasis:t}):new Se(e,{emphasis:t})}static custom(e,t,n={}){let i={...n,render:t};return Se.isWord(e)?e.copy().assign(i):new Se(e,i)}static getText(e){return e.filter(t=>!t.isPause()&&!t.isTextEvent()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=Sa(Se.defaultConfig,t)}evaluate(e){if(ze.isPause(this.text))return[this];if(ut.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>Se.isWord(n)?n.inherit(this.config).evaluate(e):new Se(n,this.config)).flat():Se.isWord(t)?t.inherit(this.config).evaluate(e):[new Se(t,this.config)]}return[this]}inherit(e){return this.config.color=this.config.color||e.color,this.config.italic=this.config.italic??e.italic,this.config.bold=this.config.bold??e.bold,this.config.cps=this.config.cps??e.cps,this.config.emphasis=this.config.emphasis??e.emphasis,this.config.fontScale=this.config.fontScale??e.fontScale,this}assign(e){return this.config=Sa(this.config,e),this}copy(){return new Se(this.text,this.config)}isPause(){return ze.isPause(this.text)}isTextEvent(){return ut.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Se.defaultConfig={},Se.defaultColor="#000";var ie=Se;var pt=class pt{static isSentence(e){return e instanceof pt}static toSentence(e){return pt.isSentence(e)?e:new pt(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return ie.isWord(e)?e:new ie(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[ie.isWord(e)?e:new ie(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(pt.isSingleWord):pt.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||ie.isWord(e)||ze.isPause(e)||ut.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=pt.format(e),this.config=Y(pt.defaultConfig,{...t,voice:typeof t.voice=="string"?fe.voice(t.voice):fe.toSound(t.voice)}),this.state=_s(pt.defaultState)}toData(){return null}fromData(e){return this.state=Y(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...pt.formatStaticWord(i))}return t}copy(){return new pt([...this.text],this.config)}};pt.defaultConfig={voice:null,character:null,voiceId:null},pt.defaultState={};var me=pt;var Zi=class{constructor(e,t){this.game=e,this.prefix=t}log(e,...t){this.isEnabled("log")&&console.log(...this.colorLog("gray",e,...t))}info(e,...t){this.isEnabled("info")&&console.info(...this._log(e,...t))}warn(e,...t){this.isEnabled("warn")&&console.warn(...this._log(e,...t))}error(e,...t){this.isEnabled("error")&&console.error(...this._log(e,...t))}debug(e,...t){this.isEnabled("debug")&&console.debug(...this.colorLog("gray",e,...t))}trace(e,...t){this.isEnabled("trace")&&console.trace(this._log(e,...t))}weakWarn(e,...t){this.isEnabled("warn")&&console.log(...this.colorLog("yellow",e,...t))}weakError(e,...t){this.isEnabled("error")&&console.log(...this.colorLog("red",e,...t))}verbose(e,...t){this.isEnabled("verbose")&&console.log(...this.colorLog("gray",e,...t))}group(e,t=!1){let n=this._log(e).join(" ");return this.isEnabled("info")&&(t?console.groupCollapsed(n):console.group(n)),{end:()=>{this.isEnabled("info")&&console.groupEnd()}}}isEnabled(e){return typeof this.game.config.app.logger=="boolean"?this.game.config.app.logger:this.game.config.app.logger[e]}_log(e,...t){return t.length===0?[this.prefix||"",e]:[`${this.prefix||""} [${e}]`,...t]}colorLog(e,t,...n){if(n.length===0)return[`%c${this.prefix||""} ${t}`,`color: ${e}`];let i=[],r=[],s=[];return this.prefix?(i.push(`%c${this.prefix} [${t}]`),r.push(`color: ${e}`)):(i.push(`%c[${t}]`),r.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(i.push(`%c${a}`),r.push(`color: ${e}`)):(i.push("%O"),s.push(a),r.push(""))}),[i.join(" ")].concat(r,s)}};var an=class extends X{executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};an.ActionTypes=Ys;var xe=class o extends le{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new an(t,an.ActionTypes.action,new C().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new an(this.chain(),an.ActionTypes.action,new C().setContent(e))]}};var Vl={volume:1,limit:1/0},Ul=class ba{constructor(e,t,n,i){this.subChannels=new Map,this.tokens=new Set,this.tokenQueue=[],this.muted=!1,this.removed=!1,this.name=e,this.audioProvider=t,this.parentChannel=i??null,this.options={...Vl,...n},this.volume=this.options.volume;let r=this.audioProvider.getAudioContext();this.gainNode=r.createGain(),this.gainNode.gain.value=this.muted?0:this.volume,this.connectToParent()}connectToParent(){this.parentChannel?this.gainNode.connect(this.parentChannel.getGainNode()):this.gainNode.connect(this.audioProvider.getAudioContext().destination)}getGainNode(){return this.gainNode}ensureNotRemoved(){if(this.removed)throw new Error(`Channel "${this.name}" has been removed and cannot be used.`)}getName(){return this.name}async play(e,t){if(this.ensureNotRemoved(),this.tokens.size>=this.options.limit){let r=this.tokenQueue.shift();r&&r.stop()}let n=await this.audioProvider.createToken(e,t,this.gainNode);this.tokens.add(n),this.tokenQueue.push(n);let i=()=>{this.tokens.delete(n);let r=this.tokenQueue.indexOf(n);r!==-1&&this.tokenQueue.splice(r,1)};return n.once("ended",i),n.once("stop",i),n}createChannel(e,t){if(this.ensureNotRemoved(),this.subChannels.has(e))throw new Error(`Channel "${e}" already exists under "${this.name}".`);this.audioProvider.checkChannelLimit();let n=new ba(e,this.audioProvider,t,this);return this.subChannels.set(e,n),this.audioProvider.registerChannel(n),n}getChannel(e){return this.ensureNotRemoved(),this.subChannels.get(e)??null}getChannels(){return this.ensureNotRemoved(),Array.from(this.subChannels.values())}setVolume(e){return this.ensureNotRemoved(),this.volume=Math.max(0,Math.min(1,e)),this.muted||(this.gainNode.gain.value=this.volume),this}getVolume(){return this.volume}mute(e){return this.ensureNotRemoved(),this.muted=e!==void 0?e:!0,this.gainNode.gain.value=this.muted?0:this.volume,this}unmute(){return this.mute(!1)}isMuted(){return this.muted}remove(){if(this.removed)return this;this.removed=!0;for(let t of this.tokens)t.stop();this.tokens.clear();let e=Array.from(this.subChannels.values());this.subChannels.clear();for(let t of e)t.remove();try{this.gainNode.disconnect()}catch(t){console.warn("Failed to disconnect Channel gain node during remove().",t)}return this.audioProvider.unregisterChannel(this),this.parentChannel&&this.parentChannel.removeSubChannel(this.name),this}removeSubChannel(e){this.subChannels.delete(e)}getTokens(){this.ensureNotRemoved();let e=[...this.tokenQueue];for(let t of this.subChannels.values())e.push(...t.getTokens());return e}isRemoved(){return this.removed}getParent(){return this.parentChannel}getOptions(){return{...this.options}}},Aa=!1;function Wl(o){Aa=o}function cn(o,e){Aa||(e!==void 0?console.warn(o,e):console.warn(o))}var Bl=class{constructor(o,e){this.currentSource=null,this.mediaElementSource=null,this.endedHandler=null,this.eventListeners=new Map,this.audioContext=o,this.gainNode=e}setSource(o){this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.setupEventListeners()}getSource(){return this.currentSource}refreshSource(o){let e=new Map(this.eventListeners);this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.eventListeners=e,this.setupEventListeners()}disconnectSource(){if(this.currentSource){if(this.removeAllEventListeners(),this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.disconnect()}catch(o){cn("Failed to disconnect AudioBufferSourceNode in disconnectSource().",o)}else this.currentSource instanceof HTMLAudioElement&&(this.currentSource.pause(),this.currentSource.src="",this.currentSource.load());if(this.mediaElementSource){try{this.mediaElementSource.disconnect()}catch(o){cn("Failed to disconnect MediaElementAudioSourceNode in disconnectSource().",o)}this.mediaElementSource=null}this.currentSource=null}}setupEventListeners(){this.currentSource&&(this.endedHandler=o=>{this.emit("ended")},this.currentSource instanceof HTMLAudioElement?this.currentSource.addEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.addEventListener("ended",this.endedHandler))}removeAllEventListeners(){!this.currentSource||!this.endedHandler||(this.currentSource instanceof HTMLAudioElement?this.currentSource.removeEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.removeEventListener("ended",this.endedHandler),this.endedHandler=null)}emit(o){let e=this.eventListeners.get(o);e&&[...e].forEach((t,n)=>{try{t.callback()}catch(i){console.error(`Error in event listener for '${o}':`,i)}t.once&&e.splice(e.indexOf(t),1)})}on(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!1})}off(o,e){let t=this.eventListeners.get(o);if(!t)return;let n=t.findIndex(i=>i.callback===e);n!==-1&&t.splice(n,1)}once(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!0})}stop(){if(this.currentSource){if(this.currentSource instanceof HTMLAudioElement)this.currentSource.pause(),this.currentSource.currentTime=0;else if(this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.stop()}catch(o){cn("Failed to stop AudioBufferSourceNode in stop().",o)}}}destroy(){this.disconnectSource(),this.eventListeners.clear()}start(o=0,e=0){this.currentSource instanceof AudioBufferSourceNode?this.currentSource.start(o,e):this.currentSource instanceof HTMLAudioElement&&this.currentSource.play()}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},Ta=class{constructor(o,e){this.token=o,this.endVolume=e,this.cancelled=!1,this.finishedInternal=!1,this._finished=new Promise(t=>{this.resolveFinished=t})}get finished(){return this._finished}cancel(){this.cancelled||this.finishedInternal||(this.cancelled=!0,this.resolveFinished())}finish(){this.finishedInternal||(this.finishedInternal=!0,this.token.setVolume(this.endVolume),this.resolveFinished())}isCancelled(){return this.cancelled}isFinished(){return this.finishedInternal}getTargetVolume(){return this.endVolume}},zl=class{constructor(o,e,t={},n){this._isPlaying=!1,this._isPaused=!1,this._isMuted=!1,this.volume=1,this.rate=1,this.contextStartTime=0,this.startOffset=0,this.pauseOffset=0,this.duration=0,this.currentFade=null,this.audioContext=o,this.volume=t.volume??1,this.rate=t.rate??1,this.startOffset=t.startOffset??0,this.duration=t.duration??0,this.outputNode=n??o.destination,this.gainNode=o.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.outputNode),this.sourceController=new Bl(o,this.gainNode),this.sourceController.setSource(e);let i=this.startOffset;this.sourceController.start(0,i),this.contextStartTime=this.audioContext.currentTime,this._isPlaying=!0,this.duration>0&&setTimeout(()=>{this._isPlaying&&this.stop()},this.duration*1e3)}emit(o){if(this.sourceController.emit(o),o==="ended"){this._isPlaying=!1;try{this.gainNode.disconnect()}catch(e){cn("Failed to disconnect gain node on natural end.",e)}}}setVolume(o){return this.currentFade&&(this.currentFade.cancel(),this.currentFade=null),o=Math.max(0,Math.min(1,o)),this.volume=o,this._isMuted||(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=o),this}getVolume(){return this.volume}mute(o){let e=o!==void 0?o:!0;if(this._isMuted=e,this.currentFade&&!this.currentFade.isFinished()&&!this.currentFade.isCancelled()){let t=this.currentFade.getTargetVolume();this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.volume=t,this.gainNode.gain.value=e?0:t,this.currentFade.finish(),this.currentFade=null}else this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=e?0:this.volume;return this}unmute(){return this.mute(!1)}isMuted(){return this._isMuted}pause(){if(!this._isPlaying||this._isPaused)return this;let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?(o.pause(),this.pauseOffset=o.currentTime):o instanceof AudioBufferSourceNode&&(this.pauseOffset=this.getCurrentTime(),this.sourceController.stop()),this._isPlaying=!1,this._isPaused=!0,this.emit("pause"),this}resume(){if(!this._isPaused)return this;let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement){let e=o.play();e&&typeof e.catch=="function"&&e.catch(()=>{this._isPlaying=!1,this._isPaused=!0})}else if(o instanceof AudioBufferSourceNode){let e=this.audioContext.createBufferSource();e.buffer=o.buffer,e.playbackRate.value=this.rate,e.loop=o.loop,e.loopStart=o.loopStart,e.loopEnd=o.loopEnd,this.sourceController.refreshSource(e),this.startOffset=this.pauseOffset,this.contextStartTime=this.audioContext.currentTime,this.sourceController.start(0,this.pauseOffset)}return this._isPlaying=!0,this._isPaused=!1,this.emit("resume"),this}isPlaying(){return this._isPlaying}isPaused(){return this._isPaused}stop(o={}){let{fadeDuration:e=0}=o;return e>0?this.fade(this.getVolume(),0,e).finished.then(()=>{this.doStop()}):this.doStop(),this}doStop(){this.sourceController.stop(),this._isPlaying=!1,this._isPaused=!1,this.emit("stop"),this.sourceController.destroy();try{this.gainNode.disconnect()}catch(o){cn("Failed to disconnect gain node on stop().",o)}}setRate(o){o=Math.max(.001,o),this.rate=o;let e=this.sourceController.getSource();return e instanceof HTMLAudioElement?e.playbackRate=o:e instanceof AudioBufferSourceNode&&(e.playbackRate.value=o),this}getRate(){return this.rate}seek(o){o=Math.max(0,o);let e=this.sourceController.getSource();if(e instanceof HTMLAudioElement)e.currentTime=o,this.emit("seek");else if(e instanceof AudioBufferSourceNode){let t=this.getCurrentTime();if(Math.abs(o-t)>.01){if(this._isPlaying){this.sourceController.stop();let n=this.audioContext.createBufferSource();n.buffer=e.buffer,n.playbackRate.value=this.rate,n.loop=e.loop,n.loopStart=e.loopStart,n.loopEnd=e.loopEnd,this.sourceController.refreshSource(n),this.startOffset=this.audioContext.currentTime-o,this.sourceController.start(0,o)}else this._isPaused&&(this.pauseOffset=o);this.emit("seek")}}return this}getCurrentTime(){let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement)return o.currentTime;if(o instanceof AudioBufferSourceNode){if(this._isPaused)return this.pauseOffset;if(this._isPlaying)return(this.audioContext.currentTime-this.contextStartTime)*this.rate+this.startOffset}return 0}getDuration(){let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?o.duration||0:o instanceof AudioBufferSourceNode&&o.buffer?o.buffer.duration:this.duration}fade(o,e,t){if(this.currentFade&&this.currentFade.cancel(),o=Math.max(0,Math.min(1,o)),e=Math.max(0,Math.min(1,e)),t=Math.max(0,t),t===0){this.setVolume(e);let r=new Ta(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new Ta(this,e);this.currentFade=n;let i=this.audioContext.currentTime;return this.gainNode.gain.setValueAtTime(o,i),this.gainNode.gain.linearRampToValueAtTime(e,i+t/1e3),setTimeout(()=>{!n.isCancelled()&&!n.isFinished()&&(this.volume=e,n.finish(),this.currentFade=null)},t),n}on(o,e){return this.sourceController.on(o,e),this}off(o,e){return this.sourceController.off(o,e),this}once(o,e){return this.sourceController.once(o,e),this}},Kl=class{constructor(o){this.alive=!0,this.refCount=0,this.audioBuffer=o}addRef(){this.refCount++}releaseRef(){this.refCount>0&&this.refCount--}getRefCount(){return this.refCount}async unload(){this.refCount>0||(this.alive=!1)}async forceUnload(){this.alive=!1,this.refCount=0}isAlive(){return this.alive}raw(){if(!this.alive)throw new Error("CachedAudio has been unloaded.");return this.audioBuffer}},$l=10*1024*1024,jl=class{constructor(o){this.cache=new Map,this.loadingPromises=new Map,this.audioContext=o}async load(o){let e=this.cache.get(o);if(e&&e.isAlive())return e;let t=this.loadingPromises.get(o);if(t)return t;let n=this.doLoad(o);this.loadingPromises.set(o,n);try{let i=await n;return this.cache.set(o,i),i}finally{this.loadingPromises.delete(o)}}async doLoad(o){let e=await(await fetch(o)).arrayBuffer(),t=await this.audioContext.decodeAudioData(e);return new Kl(t)}clear(){for(let o of this.cache.values())o.forceUnload();this.cache.clear(),this.loadingPromises.clear()}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size}}},ql={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},Ca=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...ql,...o},Wl(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new jl(this.audioContext),this.masterChannel=new Ul("__master__",this,{volume:this.options.volume},null),this.initialize()}async onceReady(){return this.readyPromise?(await this.readyPromise,this):this}initialize(){this.isReady||(this.readyPromise=this.waitForUnlock())}waitForUnlock(){return typeof document>"u"?(this.isReady=!0,Promise.resolve()):this.audioContext.state==="running"?(this.isReady=!0,Promise.resolve()):new Promise(o=>{let e=()=>{if(this.destroyed){this.clearUnlockHandler(),o();return}this.audioContext.resume().then(()=>{this.audioContext.state==="running"&&(this.clearUnlockHandler(),this.isReady=!0,o())}).catch(t=>{cn("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:c=!1}=e??{},l,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")l=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),l=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),l=p}let d=new zl(this.audioContext,l,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(l instanceof AudioBufferSourceNode?(l.loop=c,c&&s!==void 0&&(l.loopStart=r,l.loopEnd=s)):l instanceof HTMLAudioElement&&(l.loop=c),u){let p=!1,h=()=>{p||(p=!0,u.releaseRef?.())};d.once("ended",h),d.once("stop",h)}return d}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<$l?"full":"stream"}catch(t){return cn("Failed to resolve load mode via HEAD request, falling back to 'stream'.",t),"stream"}}createStreamSource(o){let e=new Audio(o);return e.crossOrigin="anonymous",e}checkChannelLimit(){if(this.registeredChannels.size+1>=this.options.maxChannels)throw new Error(`Maximum number of channels (${this.options.maxChannels}) reached.`)}registerChannel(o){this.registeredChannels.add(o)}unregisterChannel(o){this.registeredChannels.delete(o)}setVolume(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.setVolume(o),this}getVolume(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getVolume()}mute(o){return this.ensureNotDestroyed(),this.ensureReady(),o===void 0?this.masterChannel.mute():this.masterChannel.mute(o),this}unmute(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.unmute(),this}isMuted(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.isMuted()}createChannel(o,e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.createChannel(o,e)}getChannel(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannel(o)}getChannels(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannels()}async load(o){return this.ensureNotDestroyed(),this.ensureReady(),this.audioCache.load(o)}async play(o,e){this.ensureNotDestroyed(),this.ensureReady();let t=this.masterChannel.getTokens();for(let n of t)try{n.stop()}catch{}return this.masterChannel.play(o,e)}getTokens(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getTokens()}destroy(){this.destroyed||(this.destroyed=!0,this.clearUnlockHandler(),this.audioCache.clear(),this.masterChannel.remove(),this.registeredChannels.clear(),this.audioContext.close().catch(o=>{cn("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var de=class de{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new Ca({maxChannels:de.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=de.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,de.BusRampTimeConstant),r.setValueAtTime(s,a+de.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${nt.sound}" instead.`)),this.channels.get(nt.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=de.defaultFade(e)){let n=new S;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=de.clipRegionOf(e),a=await i.play(r,{volume:0,...de.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,s);let c=e.state.muted??!1;a.mute(c),e.state.muted=c,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,!e.config.loop&&t.waitForEnd!==!1&&await new Promise(l=>{a.once("ended",()=>l())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t=de.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new E(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=await n.play(i,{volume:0,...de.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(s,r);let a=e.state.muted??!1;return s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:i,originalVolume:t.end}),t.duration>0?s.fade(0,t.end,t.duration):s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,s}catch(n){throw this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,n),n}}stop(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return this.arm(e,i),t===0?(i.token.stop(),this.state.delete(e),n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.token.stop(),this.state.delete(e),n.resolve()}),n}setVolume(e,t,n=0){let i=new S;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new S;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}arm(e,t){let n=(t.transport??0)+1;return t.transport=n,()=>this.state.get(e)===t&&t.transport===n}pause(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);e.markDirty();let r=this.arm(e,i);return t===0?(i.pausePosition=i.token.getCurrentTime(),i.token.pause(),e.state.paused=!0,n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{if(!r()){n.resolve();return}i.pausePosition=i.token.getCurrentTime(),i.token.pause(),i.token.setVolume(i.originalVolume),e.state.paused=!0,n.resolve()}),n}resume(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);e.markDirty();let r=this.arm(e,i);return t===0?(i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,n.resolve()):(i.token.setVolume(0),i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,i.token.fade(0,i.originalVolume,t).finished.then(()=>{if(!r()){n.resolve();return}e.state.paused=!1,n.resolve()})),n}seek(e,t){if(!this.state.has(e))return S.resolve(void 0);let n=this.state.get(e),i=de.clampToRegion(t,de.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),S.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,c=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=c<i?c:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,S.resolve(void 0)):S.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime(),...e.state.paused?{paused:!0}:{}}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...de.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(de.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let c=e.state.muted??!1;a.mute(c),e.state.muted=c;let l=t.paused??e.state.paused??!1;e.state.paused=l,l?a.pause():t.isPlaying||a.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}preload(e){return this.ready.then(()=>this.sound.load(e.config.src)).then(()=>{}).catch(t=>{this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${e.config.src}")`,t)})}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),this.isReady&&this.busTree&&this.busTree.getNodes().forEach(e=>{this.applyBusVolume(this.channels.get(e.id),this.mixer.getEffectiveVolume(e.id),!1)})}setBusVolume(e,t){this.mixer.setVolume(e,t)}getBusVolume(e){return this.mixer.getVolume(e)}getBuses(){return this.mixer.list()}setGroupVolume(e,t){this.setBusVolume(e,t)}getGroupVolume(e){return this.getBusVolume(e)}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}destroy(){this.reset(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};de.MaxChannels=1024,de.BusRampTimeConstant=.02,de.BusRampSettle=de.BusRampTimeConstant*5;var eo=de;var to=class{constructor(e){this.config=e;this.watching=null;this.warnings=[]}observe(e){return this.watching=e,this}warn(e,t){return this.warnings.push([e,t]),this.watching?.logger.warn(t),t}getWarnings(){return[...this.warnings]}};import*as Zl from"html-to-image";var we=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),ct(()=>{this.preventAttach()})}static proxy(e){let t=new S,n=new S,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new E("Cannot create an 'any' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new E("Cannot create an 'all' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let c=e[a];i.attachChild(c),c.then(l=>{r[a]=l,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new S,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?ct(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new U(()=>(i&&i.abort(),t))),i=e(t),i?ct(()=>s()):ct(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}isFailed(){return this._status==="failed"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onFailed(e){this._onFailed.push(e)}onSettled(e){this.isSettled()?ct(e):(this.onResolved(e),this.onCancelled(e),this.onFailed(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new E(`Attaching to this timeline violates the timeline's state.
|
|
19
19
|
Timeline attaching is only allowed synchronously after the timeline is created.
|
|
20
|
-
Current _ableToAttach: `+this._ableToAttach);let t=S.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){let e=this.children.find(t=>t.isFailed());this.awaitable.failed||e?this.setStatus("failed",this.emitEvents.bind(this)):this.awaitable.solved&&this.children.every(t=>t.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){if(this.isResolved())this._onResolved.forEach(e=>e());else if(this.isCancelled())this._onCancelled.forEach(e=>e());else if(this.isFailed()){let e=this.children.find(t=>t.isFailed());this._onFailed.forEach(t=>t(this.awaitable.error??e?.awaitable.error))}this._onResolved=[],this._onCancelled=[],this._onFailed=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},no=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof we?e:new we(e);return this.timelines.push(t),this.guard&&t.setGuard(this.guard),t}abortAll(){for(let e of this.timelines)e.abort();this.cleanupSettled()}cleanupSettled(){this.timelines=this.timelines.filter(e=>!e.isSettled())}};var io=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new _}addNotification(e){this.notifications.push(e),this.flush()}removeNotification(e){this.notifications=this.notifications.filter(t=>t!==e),this.flush()}clearNotifications(){this.notifications=[],this.flush()}consume(e){let t=new S,n=new we(t);return t.registerSkipController(new U(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};function oo(o,e,t){let n={},i={};Object.keys(e).forEach(s=>{let a=s;a==="style"&&e.style?Object.assign(n,e.style):e[a]!==void 0&&a!=="key"&&(i[a]=e[a])}),Object.keys(n).length>0&&Object.assign(o.style,n);let r=t?t(i):i;for(let[s,a]of Object.entries(r))o.getAttribute(s)!==a&&o.setAttribute(s,a)}var ql=4e3,Pa={zIndex:0,visibility:"visible"},Yl={...Pa,zIndex:1},wa={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function ii(){return{zIndex:"auto",visibility:"visible",opacity:1,transform:"none",translate:"none",filter:"none",clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat"}}function yr(){return{...ii(),visibility:"hidden"}}var ro=class{constructor(e){this.gameState=e;this.sceneElements=new Map;this.overlayHost=null;this.running=null}registerScene(e,t){t?(this.sceneElements.set(e.getId(),t),this.gameState.isSceneSuspended(e)&&Object.assign(t.style,yr())):this.sceneElements.delete(e.getId())}syncScenePose(e,t){if(this.running&&(this.running.roles.from===e||this.running.roles.to===e))return;let n=this.sceneElements.get(e.getId());n&&Object.assign(n.style,t?yr():ii())}registerOverlayHost(e){this.overlayHost=e}reset(){this.running?.controller.complete(),this.running=null}skip(){this.running&&(this.gameState.logger.debug("StageTransition","Transition skipped"),this.running.controller.complete())}apply(e,t,n){this.running?.controller.complete();let i=e;typeof i._setDetached=="function"&&i._setDetached(!0);let r=e.createTask(this.gameState),s=e.requestAnimations(r.animations),a=new S().registerSkipController(new U(s.cancel)),c=new we(a),l=[],u=r.resolve.map(h=>{if(typeof h=="function"){let m=this.createOverlay();return l.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(h.key==="target"?t.to:t.from).getId(),role:h.key}}),d={task:r,controller:s,roles:t,targets:u,overlays:l,cancelLoadGate:()=>{},stale:!1};this.running=d,s.onUpdate(h=>this.applyFrame(d,h)),s.onComplete(()=>{this.settle(d,[[t.to,ii()],[t.from,yr()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(d,[[t.from,ii()],[t.to,ii()]]),c.abort()}),this.applyFrame(d,r.animations.map(h=>h.start));let p=this.waitForSceneReady(t.to);return d.cancelLoadGate=p.cancel,p.promise.then(()=>{d.stale||s.start()}),c}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?r.element:this.sceneElements.get(r.sceneId)??null;if(!s)return;let a=typeof n=="function"?n:n.resolver,c=r.kind==="overlay"?wa:r.role==="target"?Yl:Pa,l=Y({style:c},a(...t));oo(s,l,Xl)})}settle(e,t){e.stale=!0,e.cancelLoadGate(),e.overlays.forEach(n=>n.remove()),e.overlays.length=0,t.forEach(([n,i])=>{let r=this.sceneElements.get(n.getId());r&&Object.assign(r.style,i)}),this.running===e&&(this.running=null)}createOverlay(){let e=document.createElement("div");return e.setAttribute("data-element-type","stage-transition-overlay"),Object.assign(e.style,wa),this.overlayHost?.appendChild(e),e}waitForSceneReady(e){let t=this.sceneElements.get(e.getId());if(!t)return{promise:Promise.resolve(),cancel:()=>{}};let n=()=>{},i=new Promise(s=>{n=this.gameState.schedule(()=>{this.gameState.logger.weakWarn("StageTransition","Timed out waiting for the incoming scene to load"),s()},ql)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(Ql)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},ka=["src","width","height"];function Xl(o){if(!ka.some(t=>t in o))return o;let e={...o};return ka.forEach(t=>delete e[t]),e}function Ql(o){return o.getAttribute("src")?typeof o.decode=="function"?o.decode().then(()=>{},()=>{}):o.complete?Promise.resolve():new Promise(e=>{let t=()=>{o.removeEventListener("load",t),o.removeEventListener("error",t),e()};o.addEventListener("load",t),o.addEventListener("error",t)}):Promise.resolve()}var so=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=ji(6),{action:r,timeline:s,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(l))}return{id:i}}has(e){return this.history.some(t=>t.id===e)}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var ao=class o{constructor(e){this.history=[];this.cursor=-1;this.resumingAtCursor=!1;this.actionHistoryMgr=e,this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){let t=this.history[this.cursor];if(this.resumingAtCursor&&t&&t.action===e.action)return this.history[this.cursor]={...e,token:t.token},this.resumingAtCursor=!1,this;this.resumingAtCursor=!1;let n=this.history[this.cursor+1];return n&&n.action===e.action?this.history[this.cursor+1]={...e,token:n.token}:(this.history.length=this.cursor+1,this.history.push(e)),this.cursor++,this}getHistory(){return this.history.slice(0,this.cursor+1)}getFuture(){return this.history.slice(this.cursor+1)}getCursor(){return this.cursor}getAt(e){return this.history[e]??null}indexOfToken(e){return this.history.findIndex(t=>t.token===e)}setCursor(e){return this.cursor=Math.max(-1,Math.min(e,this.history.length-1)),this.resumingAtCursor=!0,this}canUndo(){return this.cursor>0}canRedo(){return this.cursor<this.history.length-1}getByToken(e){return this.history.find(t=>t.token===e)??null}serialize(){return this.history.slice(0,this.cursor+1).map(e=>o.toSerialized(e))}serializeAll(){return this.history.map(e=>o.toSerialized(e))}load(e,t){this.history=[];for(let n of e){let i=n.actionId!=null?t.get(n.actionId):void 0;i&&this.history.push({token:n.token??ji(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1,this.resumingAtCursor=this.cursor>=0}reset(){this.history=[],this.cursor=-1,this.resumingAtCursor=!1}static toSerialized(e){return{token:e.token,actionId:e.action.getId(),element:e.element,isPending:e.isPending,snapshot:e.snapshot??null}}updateByToken(e,t){let n=this.history.find(i=>i.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(i=>i.id)),n=this.history.slice(0,this.cursor+1).filter(i=>t.has(i.token)).length;this.history=this.history.filter(i=>!t.has(i.token)),this.cursor=Math.max(-1,Math.min(this.cursor-n,this.history.length-1))}};var Qt=class Qt extends X{executeAction(e,t){if(this.type===pe.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===pe.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===pe.applyLoop){let[n,i]=this.contentNode.getContent();return this.applyLoop(e,this.callee,n,i,t)}else if(this.type===pe.stopLoop){let[n]=this.contentNode.getContent();return this.stopLoop(e,this.callee,n,t)}else if(this.type===pe.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}else if(this.type===pe.bringToFront)return this.bringToFront(e,this.callee,t);throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new S().registerSkipController(new U(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t),l=t.transformState.clone(),u=t._getLoop(),d=t._getLoopActionId();u&&(t._setLoop(null,{},null),t.markDirty());let p=c.applyTransform(n,a),h=e.timelines.attachTimeline(s).attachChild(p);return p.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:h},(g,m,y)=>{s.isSettled()||s.abort(),p.abort(),t.transformState.forceOverwrite(g.state),Qt.restoreLoop(e,t,m,y)},[l,u,d]),s}applyLoop(e,t,n,i,r){let s=t._getLoop(),a=t._getLoopActionId(),c=i??{};t._setLoop(n,c,this.getId()),t.markDirty(),e.getExposedState(t)?.applyLoop(n,c),e.actionHistory.push({action:this,stackModel:r.stackModel},(u,d)=>{Qt.restoreLoop(e,t,u,d)},[s,a]);let l=new S;return l.resolve(super.executeAction(e,r)),l}stopLoop(e,t,n,i){let r=t._getLoop(),s=t._getLoopActionId();t._setLoop(null,{},null),t.markDirty();let a=new S().registerSkipController(new U(()=>(e.logger.info("Displayable Loop","Skipped"),super.executeAction(e,i)))),c=()=>{a.isSettled()||a.resolve(super.executeAction(e,i))},l=e.getExposedState(t);if(!l||!r)return e.actionHistory.push({action:this,stackModel:i.stackModel},(p,h)=>{Qt.restoreLoop(e,t,p,h)},[r,s]),c(),a;let u=l.stopLoop(n,c),d=e.timelines.attachTimeline(a).attachChild(u);return u.onCancelled(c),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:d},(p,h)=>{a.isSettled()||a.abort(),u.abort(),Qt.restoreLoop(e,t,p,h)},[r,s]),a}static restoreLoop(e,t,n,i){if(!n&&!t._getLoop())return;t._setLoop(n?.transform??null,n?.options??{},i),t.markDirty();let r=e.getExposedState(t);r&&(n?r.applyLoop(n.transform,n.options):r.stopLoop(void 0,()=>{}))}applyTransition(e,t,n,i,r){let s=new S().registerSkipController(new U(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t).applyTransition(n,a),u=e.timelines.attachTimeline(s).attachChild(l);return l.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{s.isSettled()||s.abort(),l.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let l=e.findElementByDisplayable(this.callee,i);l&&e.disposeDisplayable(n,l.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new S().registerSkipController(new U(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:c},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}bringToFront(e,t,n){let i=e.findElementByDisplayable(t),r=i&&Qt.getLayerElements(i,t);if(!r)throw new E(`Displayable not found when bringing it to front. The element may not be on stage yet. (element: ${t.getId()})`);let s=r.indexOf(t);s!==r.length-1&&(r.splice(s,1),r.push(t),e.flush()),e.actionHistory.push({action:this,stackModel:n.stackModel},c=>{let l=e.findElementByDisplayable(t),u=l&&Qt.getLayerElements(l,t);if(!u)return;let d=u.indexOf(t);d!==c&&(u.splice(d,1),u.splice(c,0,t),e.flush())},[s]);let a=new S;return a.resolve(super.executeAction(e,n)),a}static getLayerElements(e,t){for(let n of e.layers.values())if(n.includes(t))return n;return null}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};Qt.ActionTypes=pe;var Te=Qt;var Ke=class o extends le{constructor(){super(...arguments);this.srcManager=new Re;this.loopTransform=null;this.loopOptions={};this.loopActionId=null}_getLoop(){return this.loopTransform?{transform:this.loopTransform,options:this.loopOptions}:null}_setLoop(t,n,i){return this.loopTransform=t,this.loopOptions=t?n:{},this.loopActionId=t?i:null,this}_getLoopActionId(){return this.loopActionId}_serializeLoop(){return this.loopActionId?{actionId:this.loopActionId,options:{...this.loopOptions}}:null}_deserializeLoop(t){return this.loopTransform=null,this.loopOptions=t?{...t.options}:{},this.loopActionId=t?t.actionId:null,this}_rebindLoop(t){if(!this.loopActionId||this.loopTransform)return this;let i=t.get(this.loopActionId)?.contentNode?.getContent(),r=Array.isArray(i)?i[0]:void 0;return r instanceof Z?(this.loopTransform=r,this):this._setLoop(null,{},null)}reset(){super.reset(),this._setLoop(null,{},null)}pos(t,n,i){return this.transform(new Z({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new Z({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new Z({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new Z({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new Z({scaleX:t,scaleY:n},{duration:i,ease:r}))}scaleXY(t,n,i,r){return this.scale(t,n,i,r)}rotate(t,n,i){return this.transform(new Z({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new Z({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new Z(t,n))}mask(t,n={}){let i=P.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c,...l}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c},l)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Fe,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Fe,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...c}=t,l={duration:s,ease:a,...c},u=o.wipeClipPath(n,100),d=o.wipeClipPath(n,0),p=o.createClipPathTransform([[i?d:u,{duration:0}],[i?u:d,l]]);return r?this.combineActions(new Fe,h=>h.transform(p).clearClip({duration:0})):this.transform(p)}filter(t,n){return this.effect({filter:t},n)}clearFilter(t){return this.effect({filter:"none"},t)}backdrop(t,n){return this.effect({backdropFilter:t},n)}blend(t,n){return this.effect({mixBlendMode:t},n)}transform(t){let n=this.chain(),i=new Te(n,pe.applyTransform,new C().setContent([t.copy()]));return n.chain(i)}loop(t,n){let i=this.chain(),r=new Te(i,pe.applyLoop,new C().setContent([t.copy(),n]));return i.chain(r)}stopLoop(t){let n=this.chain(),i=new Te(n,pe.stopLoop,new C().setContent([t]));return n.chain(i)}bringToFront(){let t=this.chain(),n=new Te(t,pe.bringToFront,new C().setContent([]));return t.chain(n)}registerEffectSrc(t){let n=t.maskImage;if(typeof n=="string")for(let i of o.extractCSSUrls(n))this.srcManager.registerRawSrc(i)}static toCSSUrl(t){return`url("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}")`}static extractCSSUrls(t){let n=[],i=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g,r;for(;r=i.exec(t);){let s=r[1]||r[2]||r[3];s&&n.push(s.trim())}return n}static createClipPathTransform(t){return new Z(t.map(([n,i])=>({props:{clipPath:n},options:i})))}static circleClipPath(t,n){return`circle(${t}% at ${n})`}static wipeClipPath(t,n){switch(t){case"right":return`inset(0 0 0 ${n}%)`;case"top":return`inset(0 0 ${n}% 0)`;case"bottom":return`inset(${n}% 0 0 0)`;case"left":default:return`inset(0 ${n}% 0 0)`}}show(t){let n=this.chain(),i=t instanceof Z?t.copy():new Z({opacity:1},t),r=new Te(n,pe.applyTransform,new C().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof Z?t.copy():new Z({opacity:0},t),r=new Te(n,pe.applyTransform,new C().setContent([i]));return n.chain(r)}};var ln=class ln extends le{constructor(e,t={}){super(),this.config=Y(ln.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>me.isSingleWord(c))){let c=e,l=me.format([t,...n]),u=new me(Zs(c,l),{character:this}),d=new it(this.chain(),it.ActionTypes.say,new C().setContent(u));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new me(r,{...i,character:this}):(me.isSentence(r)?r:new me(r,{...i,character:this})).copy();s.setCharacter(this);let a=new it(this.chain(),it.ActionTypes.say,new C().setContent(s));return this.chain(a)}setName(e){let t=new it(this.chain(),it.ActionTypes.setName,new C().setContent([e]));return this.chain(t)}setAvatar(e){return this.config.avatar=e===null?null:e,this}addPortrait(e,t={}){return this.config.portraits.push({image:e,avatar:t.avatar}),this}setPortraits(e){return this.config.portraits=[...e],this}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&me.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):me.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:ln.StateSerializer.serialize(this.state)}}fromData(e){return this.state=ln.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};ln.defaultCharacterColor="#000",ln.defaultConfig={portraits:[]},ln.StateSerializer=new qe;var co=ln,_t=new co(null);var Q=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},vr=class o extends le{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new o().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new Oe(`ELSE condition already set
|
|
20
|
+
Current _ableToAttach: `+this._ableToAttach);let t=S.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){let e=this.children.find(t=>t.isFailed());this.awaitable.failed||e?this.setStatus("failed",this.emitEvents.bind(this)):this.awaitable.solved&&this.children.every(t=>t.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){if(this.isResolved())this._onResolved.forEach(e=>e());else if(this.isCancelled())this._onCancelled.forEach(e=>e());else if(this.isFailed()){let e=this.children.find(t=>t.isFailed());this._onFailed.forEach(t=>t(this.awaitable.error??e?.awaitable.error))}this._onResolved=[],this._onCancelled=[],this._onFailed=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},no=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof we?e:new we(e);return this.timelines.push(t),this.guard&&t.setGuard(this.guard),t}abortAll(){for(let e of this.timelines)e.abort();this.cleanupSettled()}cleanupSettled(){this.timelines=this.timelines.filter(e=>!e.isSettled())}};var io=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new _}addNotification(e){this.notifications.push(e),this.flush()}removeNotification(e){this.notifications=this.notifications.filter(t=>t!==e),this.flush()}clearNotifications(){this.notifications=[],this.flush()}consume(e){let t=new S,n=new we(t);return t.registerSkipController(new U(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};function oo(o,e,t){let n={},i={};Object.keys(e).forEach(s=>{let a=s;a==="style"&&e.style?Object.assign(n,e.style):e[a]!==void 0&&a!=="key"&&(i[a]=e[a])}),Object.keys(n).length>0&&Object.assign(o.style,n);let r=t?t(i):i;for(let[s,a]of Object.entries(r))o.getAttribute(s)!==a&&o.setAttribute(s,a)}var Yl=4e3,Pa={zIndex:0,visibility:"visible"},Xl={...Pa,zIndex:1},wa={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function ii(){return{zIndex:"auto",visibility:"visible",opacity:1,transform:"none",translate:"none",filter:"none",clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat"}}function yr(){return{...ii(),visibility:"hidden"}}var ro=class{constructor(e){this.gameState=e;this.sceneElements=new Map;this.overlayHost=null;this.running=null}registerScene(e,t){t?(this.sceneElements.set(e.getId(),t),this.gameState.isSceneSuspended(e)&&Object.assign(t.style,yr())):this.sceneElements.delete(e.getId())}syncScenePose(e,t){if(this.running&&(this.running.roles.from===e||this.running.roles.to===e))return;let n=this.sceneElements.get(e.getId());n&&Object.assign(n.style,t?yr():ii())}registerOverlayHost(e){this.overlayHost=e}reset(){this.running?.controller.complete(),this.running=null}skip(){this.running&&(this.gameState.logger.debug("StageTransition","Transition skipped"),this.running.controller.complete())}apply(e,t,n){this.running?.controller.complete();let i=e;typeof i._setDetached=="function"&&i._setDetached(!0);let r=e.createTask(this.gameState),s=e.requestAnimations(r.animations),a=new S().registerSkipController(new U(s.cancel)),c=new we(a),l=[],u=r.resolve.map(h=>{if(typeof h=="function"){let m=this.createOverlay();return l.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(h.key==="target"?t.to:t.from).getId(),role:h.key}}),d={task:r,controller:s,roles:t,targets:u,overlays:l,cancelLoadGate:()=>{},stale:!1};this.running=d,s.onUpdate(h=>this.applyFrame(d,h)),s.onComplete(()=>{this.settle(d,[[t.to,ii()],[t.from,yr()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(d,[[t.from,ii()],[t.to,ii()]]),c.abort()}),this.applyFrame(d,r.animations.map(h=>h.start));let p=this.waitForSceneReady(t.to);return d.cancelLoadGate=p.cancel,p.promise.then(()=>{d.stale||s.start()}),c}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?r.element:this.sceneElements.get(r.sceneId)??null;if(!s)return;let a=typeof n=="function"?n:n.resolver,c=r.kind==="overlay"?wa:r.role==="target"?Xl:Pa,l=Y({style:c},a(...t));oo(s,l,Ql)})}settle(e,t){e.stale=!0,e.cancelLoadGate(),e.overlays.forEach(n=>n.remove()),e.overlays.length=0,t.forEach(([n,i])=>{let r=this.sceneElements.get(n.getId());r&&Object.assign(r.style,i)}),this.running===e&&(this.running=null)}createOverlay(){let e=document.createElement("div");return e.setAttribute("data-element-type","stage-transition-overlay"),Object.assign(e.style,wa),this.overlayHost?.appendChild(e),e}waitForSceneReady(e){let t=this.sceneElements.get(e.getId());if(!t)return{promise:Promise.resolve(),cancel:()=>{}};let n=()=>{},i=new Promise(s=>{n=this.gameState.schedule(()=>{this.gameState.logger.weakWarn("StageTransition","Timed out waiting for the incoming scene to load"),s()},Yl)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(_l)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},ka=["src","width","height"];function Ql(o){if(!ka.some(t=>t in o))return o;let e={...o};return ka.forEach(t=>delete e[t]),e}function _l(o){return o.getAttribute("src")?typeof o.decode=="function"?o.decode().then(()=>{},()=>{}):o.complete?Promise.resolve():new Promise(e=>{let t=()=>{o.removeEventListener("load",t),o.removeEventListener("error",t),e()};o.addEventListener("load",t),o.addEventListener("error",t)}):Promise.resolve()}var so=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=ji(6),{action:r,timeline:s,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(l))}return{id:i}}has(e){return this.history.some(t=>t.id===e)}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var ao=class o{constructor(e){this.history=[];this.cursor=-1;this.resumingAtCursor=!1;this.actionHistoryMgr=e,this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){let t=this.history[this.cursor];if(this.resumingAtCursor&&t&&t.action===e.action)return this.history[this.cursor]={...e,token:t.token},this.resumingAtCursor=!1,this;this.resumingAtCursor=!1;let n=this.history[this.cursor+1];return n&&n.action===e.action?this.history[this.cursor+1]={...e,token:n.token}:(this.history.length=this.cursor+1,this.history.push(e)),this.cursor++,this}getHistory(){return this.history.slice(0,this.cursor+1)}getFuture(){return this.history.slice(this.cursor+1)}getCursor(){return this.cursor}getAt(e){return this.history[e]??null}indexOfToken(e){return this.history.findIndex(t=>t.token===e)}setCursor(e){return this.cursor=Math.max(-1,Math.min(e,this.history.length-1)),this.resumingAtCursor=!0,this}canUndo(){return this.cursor>0}canRedo(){return this.cursor<this.history.length-1}getByToken(e){return this.history.find(t=>t.token===e)??null}serialize(){return this.history.slice(0,this.cursor+1).map(e=>o.toSerialized(e))}serializeAll(){return this.history.map(e=>o.toSerialized(e))}load(e,t){this.history=[];for(let n of e){let i=n.actionId!=null?t.get(n.actionId):void 0;i&&this.history.push({token:n.token??ji(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1,this.resumingAtCursor=this.cursor>=0}reset(){this.history=[],this.cursor=-1,this.resumingAtCursor=!1}static toSerialized(e){return{token:e.token,actionId:e.action.getId(),element:e.element,isPending:e.isPending,snapshot:e.snapshot??null}}updateByToken(e,t){let n=this.history.find(i=>i.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(i=>i.id)),n=this.history.slice(0,this.cursor+1).filter(i=>t.has(i.token)).length;this.history=this.history.filter(i=>!t.has(i.token)),this.cursor=Math.max(-1,Math.min(this.cursor-n,this.history.length-1))}};var Qt=class Qt extends X{executeAction(e,t){if(this.type===pe.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===pe.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===pe.applyLoop){let[n,i]=this.contentNode.getContent();return this.applyLoop(e,this.callee,n,i,t)}else if(this.type===pe.stopLoop){let[n]=this.contentNode.getContent();return this.stopLoop(e,this.callee,n,t)}else if(this.type===pe.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}else if(this.type===pe.bringToFront)return this.bringToFront(e,this.callee,t);throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new S().registerSkipController(new U(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t),l=t.transformState.clone(),u=t._getLoop(),d=t._getLoopActionId();u&&(t._setLoop(null,{},null),t.markDirty());let p=c.applyTransform(n,a),h=e.timelines.attachTimeline(s).attachChild(p);return p.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:h},(g,m,y)=>{s.isSettled()||s.abort(),p.abort(),t.transformState.forceOverwrite(g.state),Qt.restoreLoop(e,t,m,y)},[l,u,d]),s}applyLoop(e,t,n,i,r){let s=t._getLoop(),a=t._getLoopActionId(),c=i??{};t._setLoop(n,c,this.getId()),t.markDirty(),e.getExposedState(t)?.applyLoop(n,c),e.actionHistory.push({action:this,stackModel:r.stackModel},(u,d)=>{Qt.restoreLoop(e,t,u,d)},[s,a]);let l=new S;return l.resolve(super.executeAction(e,r)),l}stopLoop(e,t,n,i){let r=t._getLoop(),s=t._getLoopActionId();t._setLoop(null,{},null),t.markDirty();let a=new S().registerSkipController(new U(()=>(e.logger.info("Displayable Loop","Skipped"),super.executeAction(e,i)))),c=()=>{a.isSettled()||a.resolve(super.executeAction(e,i))},l=e.getExposedState(t);if(!l||!r)return e.actionHistory.push({action:this,stackModel:i.stackModel},(p,h)=>{Qt.restoreLoop(e,t,p,h)},[r,s]),c(),a;let u=l.stopLoop(n,c),d=e.timelines.attachTimeline(a).attachChild(u);return u.onCancelled(c),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:d},(p,h)=>{a.isSettled()||a.abort(),u.abort(),Qt.restoreLoop(e,t,p,h)},[r,s]),a}static restoreLoop(e,t,n,i){if(!n&&!t._getLoop())return;t._setLoop(n?.transform??null,n?.options??{},i),t.markDirty();let r=e.getExposedState(t);r&&(n?r.applyLoop(n.transform,n.options):r.stopLoop(void 0,()=>{}))}applyTransition(e,t,n,i,r){let s=new S().registerSkipController(new U(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t).applyTransition(n,a),u=e.timelines.attachTimeline(s).attachChild(l);return l.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{s.isSettled()||s.abort(),l.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let l=e.findElementByDisplayable(this.callee,i);l&&e.disposeDisplayable(n,l.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new S().registerSkipController(new U(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:c},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}bringToFront(e,t,n){let i=e.findElementByDisplayable(t),r=i&&Qt.getLayerElements(i,t);if(!r)throw new E(`Displayable not found when bringing it to front. The element may not be on stage yet. (element: ${t.getId()})`);let s=r.indexOf(t);s!==r.length-1&&(r.splice(s,1),r.push(t),e.flush()),e.actionHistory.push({action:this,stackModel:n.stackModel},c=>{let l=e.findElementByDisplayable(t),u=l&&Qt.getLayerElements(l,t);if(!u)return;let d=u.indexOf(t);d!==c&&(u.splice(d,1),u.splice(c,0,t),e.flush())},[s]);let a=new S;return a.resolve(super.executeAction(e,n)),a}static getLayerElements(e,t){for(let n of e.layers.values())if(n.includes(t))return n;return null}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};Qt.ActionTypes=pe;var Te=Qt;var Ke=class o extends le{constructor(){super(...arguments);this.srcManager=new Re;this.loopTransform=null;this.loopOptions={};this.loopActionId=null}_getLoop(){return this.loopTransform?{transform:this.loopTransform,options:this.loopOptions}:null}_setLoop(t,n,i){return this.loopTransform=t,this.loopOptions=t?n:{},this.loopActionId=t?i:null,this}_getLoopActionId(){return this.loopActionId}_serializeLoop(){return this.loopActionId?{actionId:this.loopActionId,options:{...this.loopOptions}}:null}_deserializeLoop(t){return this.loopTransform=null,this.loopOptions=t?{...t.options}:{},this.loopActionId=t?t.actionId:null,this}_rebindLoop(t){if(!this.loopActionId||this.loopTransform)return this;let i=t.get(this.loopActionId)?.contentNode?.getContent(),r=Array.isArray(i)?i[0]:void 0;return r instanceof Z?(this.loopTransform=r,this):this._setLoop(null,{},null)}reset(){super.reset(),this._setLoop(null,{},null)}pos(t,n,i){return this.transform(new Z({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new Z({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new Z({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new Z({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new Z({scaleX:t,scaleY:n},{duration:i,ease:r}))}scaleXY(t,n,i,r){return this.scale(t,n,i,r)}rotate(t,n,i){return this.transform(new Z({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new Z({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new Z(t,n))}mask(t,n={}){let i=P.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c,...l}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c},l)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Fe,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Fe,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...c}=t,l={duration:s,ease:a,...c},u=o.wipeClipPath(n,100),d=o.wipeClipPath(n,0),p=o.createClipPathTransform([[i?d:u,{duration:0}],[i?u:d,l]]);return r?this.combineActions(new Fe,h=>h.transform(p).clearClip({duration:0})):this.transform(p)}filter(t,n){return this.effect({filter:t},n)}clearFilter(t){return this.effect({filter:"none"},t)}backdrop(t,n){return this.effect({backdropFilter:t},n)}blend(t,n){return this.effect({mixBlendMode:t},n)}transform(t){let n=this.chain(),i=new Te(n,pe.applyTransform,new C().setContent([t.copy()]));return n.chain(i)}loop(t,n){let i=this.chain(),r=new Te(i,pe.applyLoop,new C().setContent([t.copy(),n]));return i.chain(r)}stopLoop(t){let n=this.chain(),i=new Te(n,pe.stopLoop,new C().setContent([t]));return n.chain(i)}bringToFront(){let t=this.chain(),n=new Te(t,pe.bringToFront,new C().setContent([]));return t.chain(n)}registerEffectSrc(t){let n=t.maskImage;if(typeof n=="string")for(let i of o.extractCSSUrls(n))this.srcManager.registerRawSrc(i)}static toCSSUrl(t){return`url("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}")`}static extractCSSUrls(t){let n=[],i=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g,r;for(;r=i.exec(t);){let s=r[1]||r[2]||r[3];s&&n.push(s.trim())}return n}static createClipPathTransform(t){return new Z(t.map(([n,i])=>({props:{clipPath:n},options:i})))}static circleClipPath(t,n){return`circle(${t}% at ${n})`}static wipeClipPath(t,n){switch(t){case"right":return`inset(0 0 0 ${n}%)`;case"top":return`inset(0 0 ${n}% 0)`;case"bottom":return`inset(${n}% 0 0 0)`;case"left":default:return`inset(0 ${n}% 0 0)`}}show(t){let n=this.chain(),i=t instanceof Z?t.copy():new Z({opacity:1},t),r=new Te(n,pe.applyTransform,new C().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof Z?t.copy():new Z({opacity:0},t),r=new Te(n,pe.applyTransform,new C().setContent([i]));return n.chain(r)}};var ln=class ln extends le{constructor(e,t={}){super(),this.config=Y(ln.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>me.isSingleWord(c))){let c=e,l=me.format([t,...n]),u=new me(Zs(c,l),{character:this}),d=new it(this.chain(),it.ActionTypes.say,new C().setContent(u));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new me(r,{...i,character:this}):(me.isSentence(r)?r:new me(r,{...i,character:this})).copy();s.setCharacter(this);let a=new it(this.chain(),it.ActionTypes.say,new C().setContent(s));return this.chain(a)}setName(e){let t=new it(this.chain(),it.ActionTypes.setName,new C().setContent([e]));return this.chain(t)}setAvatar(e){return this.config.avatar=e===null?null:e,this}addPortrait(e,t={}){return this.config.portraits.push({image:e,avatar:t.avatar}),this}setPortraits(e){return this.config.portraits=[...e],this}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&me.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):me.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:ln.StateSerializer.serialize(this.state)}}fromData(e){return this.state=ln.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};ln.defaultCharacterColor="#000",ln.defaultConfig={portraits:[]},ln.StateSerializer=new qe;var co=ln,_t=new co(null);var Q=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},vr=class o extends le{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new o().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new Oe(`ELSE condition already set
|
|
21
21
|
You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:Q.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new Oe(`ELSE condition already set
|
|
22
22
|
You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let i={gameState:n};if(t.If.condition?.evaluate(i)?.value)return t.If.action||null;for(let s of t.ElseIf)if(s.condition?.evaluate(i)?.value)return s.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(Ot,[this,Ot.ActionTypes.action,new C().setContent(t.conditions)])]}construct(t,n,i){let r=this.narrativeToActions(t);for(let s=0;s<r.length;s++){let a=r[s].contentNode,c=r[s+1]?.contentNode;c&&a.setChild(c),s===r.length-1&&n&&a.setChild(n),s===0&&i&&i.setChild(a)}return r}_getFutureActions(){return Be.toActions([this.conditions.If.action?.[0]||[],...this.conditions.ElseIf.flatMap(t=>t.action?.[0]||[]),this.conditions.Else.action?.[0]||[]])}createIfCondition(t,n){this.conditions.If.condition=Q.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new Ot(i,Ot.ActionTypes.action,new C().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?_t.say(n).getActions():Be.toActions([n]))}};var bn=class extends X{executeAction(e,t){let n=new S().registerSkipController(new U(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.reset()},e.gameHistory.updateByToken(l,p=>{p&&p.element.type==="menu"&&(p.element.selected=u.evaluated,p.isPending=!1)})}),{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{c.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:l,action:this,element:{type:"menu",text:c.prompt,selected:null},isPending:!0,snapshot:e.getLiveGame().captureGameState()}),n}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};bn.ActionTypes=Xs;var An=class An extends le{constructor(t,n={}){super();this.choices=[];this.prompt=me.isSentence(t)?t:t===null?null:new me(t),this.config=Y(An.defaultConfig,n)}static prompt(t,n={}){return new An(t!==void 0?t:null,n)}static choose(t,n){return new An(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return me.isSentence(t)&&n?i.choices.push({prompt:me.toSentence(t),action:this.narrativeToActions(n),config:{}}):(ie.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:me.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:me.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?Q.from(t.config.disabled):void 0,hidden:t.config?.hidden?Q.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),i}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Oe("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.hideIf` before `menu.choose`");return n.config.hidden=Q.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Oe("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.disableIf` before `menu.choose`");return n.config.disabled=Q.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:Q.not(Q.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:Q.not(Q.from(t))}})}fromChained(t){return[new bn(this.chain(),bn.ActionTypes.action,new C().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?_t.say(n).getActions():Be.toActions([n])))}constructNodes(t,n,i){for(let r=0;r<t.length;r++){let s=t[r].contentNode,a=t[r+1]?.contentNode;a&&s.setChild(a),r===this.choices.length-1&&n&&s.setChild(n),r===0&&i&&i.setChild(s)}return t}constructChoices(){return this.choices.map(t=>({action:this.constructNodes(t.action),prompt:t.prompt,config:t.config??{}}))}};An.defaultConfig={},An.targetAction=bn;var Sr=An;var oi=class oi extends X{executeAction(e,t){let n=this;if(n.is(oi,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let c=s.get(i);s.set(i,r(c))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.set(i,c)},[a]),super.executeAction(e,t)}else if(n.is(oi,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(c=>{s[c]=r.get(c),r.set(c,a[c])}),e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{Object.keys(c).forEach(l=>{r.set(l,c[l])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};oi.ActionTypes=Yn;var lo=oi;var uo=class uo extends le{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new Ht(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Yn.set,[e,t]))}assign(e){return this.chain(this.createAction(Yn.assign,[e]))}equals(e,t){return new Q(n=>{let i=n.storable.getNamespace(this.namespace),r=Q.isLambda(t)||Q.isLambdaHandler(t)?Q.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new Q(n=>{let i=n.storable.getNamespace(this.namespace),r=Q.isLambda(t)||Q.isLambdaHandler(t)?Q.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new Q(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new Q(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new Q(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new ie(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new ie(i=>Q.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new Q(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=uo.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new lo(this.chain(),e,C.create(t))}};uo.NamespacePrefix="persistent";var Fn=uo,po=class po extends Fn{constructor(e){super(e,{}),this.namespace=this.prefix(e,po.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new Ht(this.namespace,this.defaultContent))}};po.LocalNamespacePrefix="local";var On=po;var vt={shutter:0,shutterColor:"#000",vignette:0,vignetteColor:"#000",vignetteInner:"44%",vignetteOuter:"78%"};function Tr(o){return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(1,o))}function ri(o,e){return typeof o=="string"&&o.length>0?o:e}function Ea(o){let e=Tr(o.shutter);return{backgroundColor:ri(o.shutterColor,vt.shutterColor),clipPath:`inset(0 0 ${100-50*e}% 0)`}}function Da(o){let e=Tr(o.shutter);return{backgroundColor:ri(o.shutterColor,vt.shutterColor),clipPath:`inset(${100-50*e}% 0 0 0)`}}function La(o){let e=ri(o.vignetteInner,vt.vignetteInner),t=ri(o.vignetteOuter,vt.vignetteOuter),n=`radial-gradient(circle at center, transparent ${e}, black ${t})`;return{backgroundColor:ri(o.vignetteColor,vt.vignetteColor),opacity:Tr(o.vignette),maskImage:n,WebkitMaskImage:n,maskSize:"100% 100%",WebkitMaskSize:"100% 100%",maskPosition:"center",WebkitMaskPosition:"center",maskRepeat:"no-repeat",WebkitMaskRepeat:"no-repeat",maskMode:"alpha",WebkitMaskMode:"alpha"}}var dt=class dt extends Ke{static get DefaultUserConfig(){return dt._defaultUserConfig??(dt._defaultUserConfig=new j({...ne.DefaultTransformState.getDefaultConfig(),opacity:1,...vt}))}constructor(e={}){super();let t=dt.DefaultUserConfig.create(e),n=dt.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}shutter(e,t,n){return this.lens({shutter:dt.clampLens(e)},{duration:t,ease:n})}vignette(e,t,n){return this.lens({vignette:dt.clampLens(e)},{duration:t,ease:n})}lens(e,t){return this.transform(new Z(e,t))}resetCamera(e,t){return this.transform(new Z([{props:{filter:"none"},options:{duration:0}},{props:{position:new lt("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,shutter:vt.shutter,vignette:vt.vignette},options:{duration:e,ease:t}},{props:{shutterColor:vt.shutterColor,vignetteColor:vt.vignetteColor,vignetteInner:vt.vignetteInner,vignetteOuter:vt.vignetteOuter},options:{duration:0}}]))}static clampLens(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}bringToFront(){throw new E(`A camera cannot be brought to front. It is not an element inside a layer, it is what the layers are viewed through, so it has nothing to be in front of \u2014 waiting for it to be added to the stage will not help. Use a camera transform such as Camera.zoom or Camera.pan to change what is in view. (camera: ${this.config.name})`)}reset(){return super.reset(),this.transformState.resetTo(this.getInitialTransformState().get()),this}toData(){return{transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.transformState.resetTo(ne.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}copy(){return new dt(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(dt.DefaultUserConfig.keys());return new ne(dt.DefaultUserConfig.create(e.get()).get())}};dt._defaultUserConfig=null,dt.DefaultConfig=new j({name:"(camera)"});var si=dt;var un=class un extends Nn{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.elementBaseline=null;this.hashCache=new Map;this.name=t;let{camera:i,...r}=n;this.config=Y(un.defaultConfig,r),this._camera=i??new si}static empty(){return new un("empty").entry(new Ye("empty"))}get camera(){return this._camera}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let i=new Fn(t,n);return this.registerPersistent(i),i}registerService(t,n){return this.services.set(t,n),this}getService(t){let n=this.services.get(t);if(!n)throw new Oe(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){let n=this.hashCache.get(t);if(n!==void 0)return n;let i=sa(this.stringify(t));return this.hashCache.set(t,i),i}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,i)=>{if(!n.serialize||typeof n.serialize!="function")return;let r=n.serialize();if(r!==null){{if(r instanceof Promise)throw new J(`Service ${i} serialize method should not return a promise`);if(!ar(r))throw new J(`Service ${i} serialize method should return a pure object.
|
|
23
23
|
A pure object should:
|
|
@@ -26,10 +26,10 @@ A pure object should:
|
|
|
26
26
|
3. no circular reference
|
|
27
27
|
4. sub objects should also be pure objects or serializable data
|
|
28
28
|
Return null if nothing needs to be saved. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description
|
|
29
|
-
Returned value ${r} violates the above rules`)}t[i]=r}}),t}deserializeServices(t){this.services.forEach((n,i)=>{!n.deserialize||typeof n.deserialize!="function"||t[i]&&n.deserialize(t[i])})}getScene(t,n=!1,i){if(Ye.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||J,[`Scene with name ${t} not found`]);return r}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.hashCache.clear(),this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this.captureElementBaseline(),this.scheduleHashWarmUp(),this}scheduleHashWarmUp(){let t=globalThis.requestIdleCallback;typeof t=="function"&&t(()=>{try{this.hash()}catch{}})}captureElementBaseline(){let t=new Map;this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).forEach(n=>{let i=n.toData();i&&t.set(n.getId(),JSON.stringify(i))}),this.elementBaseline=t}getAllElementStates(){let t=this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]),n=this.elementBaseline,i=[];for(let r of t){if(n&&!r.isDirty())continue;let s=r.toData();s&&(n&&JSON.stringify(s)===n.get(r.getId())||i.push({id:r.getId(),data:s}))}return i}findUnmarkedElements(){let t=this.elementBaseline;return t?this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).filter(n=>{if(n.isDirty())return!1;let i=n.toData();return!!i&&JSON.stringify(i)!==t.get(n.getId())}):[]}constructSceneRoots(t){let n=new Set,i=[],r=0;for(t.constructSceneRoot(this),i.push(t.getSceneRoot());i.length;){if(r++,r>un.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${un.MAX_DEPTH})`);let s=i.shift();if(Ye.isScene(s.callee)){if(n.has(s.callee))continue;s.callee.isSceneRootConstructed()||s.callee.constructSceneRoot(this),n.add(s.callee)}let a=s.getFutureActions(this,{allowFutureScene:!0});i.push(...a)}return this}initPersistent(t){return this.persistent.forEach(n=>{n.init(t)}),this}getInversionConfig(){let{origin:t}=this.config;return{invertY:t==="bottom left"||t==="bottom right",invertX:t==="bottom right"||t==="top right"}}runStaticCheck(t){return new mo(t).run(this)}};un.defaultConfig={origin:"bottom left"},un.MAX_DEPTH=32767;var ai=un;var pn=class extends X{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Oi.setText){let i=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.text=r},[i]),super.executeAction(e,t)}else if(this.type===Oi.setFontSize){let i=this.callee.state.fontSize;this.callee.state.fontSize=this.contentNode.getContent()[0];let r=e.getExposedStateForce(this.callee);return r.flush(),r.updateStyleSync(),e.actionHistory.push(n,s=>{this.callee.state.fontSize=s},[i]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};pn.ActionTypes=Oi;var St=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(St||{});import{animate as
|
|
29
|
+
Returned value ${r} violates the above rules`)}t[i]=r}}),t}deserializeServices(t){this.services.forEach((n,i)=>{!n.deserialize||typeof n.deserialize!="function"||t[i]&&n.deserialize(t[i])})}getScene(t,n=!1,i){if(Ye.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||J,[`Scene with name ${t} not found`]);return r}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.hashCache.clear(),this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this.captureElementBaseline(),this.scheduleHashWarmUp(),this}scheduleHashWarmUp(){let t=globalThis.requestIdleCallback;typeof t=="function"&&t(()=>{try{this.hash()}catch{}})}captureElementBaseline(){let t=new Map;this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).forEach(n=>{let i=n.toData();i&&t.set(n.getId(),JSON.stringify(i))}),this.elementBaseline=t}getAllElementStates(){let t=this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]),n=this.elementBaseline,i=[];for(let r of t){if(n&&!r.isDirty())continue;let s=r.toData();s&&(n&&JSON.stringify(s)===n.get(r.getId())||i.push({id:r.getId(),data:s}))}return i}findUnmarkedElements(){let t=this.elementBaseline;return t?this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).filter(n=>{if(n.isDirty())return!1;let i=n.toData();return!!i&&JSON.stringify(i)!==t.get(n.getId())}):[]}constructSceneRoots(t){let n=new Set,i=[],r=0;for(t.constructSceneRoot(this),i.push(t.getSceneRoot());i.length;){if(r++,r>un.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${un.MAX_DEPTH})`);let s=i.shift();if(Ye.isScene(s.callee)){if(n.has(s.callee))continue;s.callee.isSceneRootConstructed()||s.callee.constructSceneRoot(this),n.add(s.callee)}let a=s.getFutureActions(this,{allowFutureScene:!0});i.push(...a)}return this}initPersistent(t){return this.persistent.forEach(n=>{n.init(t)}),this}getInversionConfig(){let{origin:t}=this.config;return{invertY:t==="bottom left"||t==="bottom right",invertX:t==="bottom right"||t==="top right"}}runStaticCheck(t){return new mo(t).run(this)}};un.defaultConfig={origin:"bottom left"},un.MAX_DEPTH=32767;var ai=un;var pn=class extends X{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Oi.setText){let i=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.text=r},[i]),super.executeAction(e,t)}else if(this.type===Oi.setFontSize){let i=this.callee.state.fontSize;this.callee.state.fontSize=this.contentNode.getContent()[0];let r=e.getExposedStateForce(this.callee);return r.flush(),r.updateStyleSync(),e.actionHistory.push(n,s=>{this.callee.state.fontSize=s},[i]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};pn.ActionTypes=Oi;var St=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(St||{});import{animate as Jl}from"motion/react";var Vt=class{requestAnimations(e){let t=e.map(m=>m.start),n=[],i=0,r=!1,s=!1,a=!1,c=[],l=[],u=[],d=()=>{e.forEach((m,y)=>{t[y]=m.end}),i=e.length,c.forEach(m=>m(t)),l.forEach(m=>m())};return{onUpdate:m=>(c.push(m),{cancel:()=>{let y=c.indexOf(m);y!==-1&&c.splice(y,1)}}),onComplete:m=>(l.push(m),{cancel:()=>{let y=l.indexOf(m);y!==-1&&l.splice(y,1)}}),onCanceled:m=>(u.push(m),{cancel:()=>{let y=u.indexOf(m);y!==-1&&u.splice(y,1)}}),complete:()=>{if(!(i===e.length||s)){if(!r){a=!0;return}n.forEach(m=>m.complete())}},start:()=>{if(!(r||s||i===e.length)){if(r=!0,a){d();return}e.forEach((m,y)=>{n.push(this.requestMotion(m,{onComplete:()=>{t[y]=m.end,c.forEach(T=>T(t)),i++,i===e.length&&l.forEach(T=>T())},onUpdate:T=>{t[y]=T,c.forEach(f=>f(t))}}))})}},cancel:()=>{s=!0,n.forEach(m=>m.cancel()),u.forEach(m=>m())}}}toFinalStyle(e){return e.resolve.map(t=>typeof t=="function"?t(...e.animations.map(n=>n.end)):t.resolver(...e.animations.map(n=>n.end)))}asPrev(e){return{resolver:e,key:"current"}}asTarget(e){return{resolver:e,key:"target"}}requestMotion(e,t){return Jl(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Vt.AnimationType=St;var ci=class extends Vt{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new E(`Trying to access text state, but element is not set
|
|
30
30
|
This should not happen, please report this issue to the developers`);return this._element.state}};var fo=class o extends ci{constructor(e){super(),this.fontSize=e.fontSize,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.fontSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{fontSize:`${e}px`}}))]}}copy(){return new o({fontSize:this.fontSize,duration:this.duration,easing:this.easing})}};var ke=class ke extends Ke{static get DefaultUserConfig(){return ke._defaultUserConfig??(ke._defaultUserConfig=new j({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:"",...ne.DefaultTransformState.getDefaultConfig()},{position:e=>O.tryParsePosition(e)}))}static get DefaultTextTransformState(){return ke._defaultTextTransformState??(ke._defaultTextTransformState=new j({fontColor:"#000000",...ne.DefaultTransformState.getDefaultConfig()}))}constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=ke.DefaultUserConfig.create(n),r=ke.DefaultTextConfig.create(i.get());this.userConfig=i,this.config=r.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(i)}setText(e){let t=this.chain(),n=new pn(t,pn.ActionTypes.setText,new C().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new Z({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Fe,i=>{if(t){let s=new fo({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new pn(i,pn.ActionTypes.setFontSize,new C().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:ke.StateSerializer.serialize(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.state=ke.StateSerializer.deserialize(e.state),this.transformState.resetTo(ne.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}_init(e){return new Te(this.chain(),pe.init,new C().setContent([e||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}getInitialTransformState(e){let[t]=e.extract(ke.DefaultTextTransformState.keys());return new ne(ke.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Te(e,pe.applyTransition,new C().setContent([t,n=>n._setElement(this)]))}getInitialState(){return ke.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};ke._defaultUserConfig=null,ke.DefaultTextConfig=new j({alignX:"center",alignY:"center",className:"",layer:void 0}),ke.DefaultTextState=new j({fontSize:16,display:!1,text:""}),ke._defaultTextTransformState=null,ke.StateSerializer=new qe;var Cn=ke;var ho=class extends X{executeAction(e,t){let[n,i]=this.contentNode.getContent(),r=this.callee.triggerAction(xe.getCtx({gameState:e}),n,i);return S.isAwaitable(r)?S.forward(r,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var br=class extends le{constructor(){super(...arguments);this._handlers={}}on(t,n){return this._registerActionHandler(t,n),this}trigger(t,...n){let i=this.chain();return i.chain(this._createAction(i,t,n))}triggerAction(t,n,i){let r=this._handlers[n];if(!r){t.gameState.logger.warn(`(in User-Defined Service) Trying to trigger action ${n} before it's registered, please use "service.on" to register the action`);return}if(ia(r)){let s=[],a=new S().registerSkipController(new U(()=>{for(let l of s)l?.()}));return r({...t,onAbort:l=>{s.push(l)}},...i).then(()=>a.resolve()),a}r({...t,onAbort:()=>{}},...i)}_registerActionHandler(t,n){this._handlers[t]=n}_createAction(t,n,i){return new ho(t,"service:action",new C().setContent([n,i]))}},Ar=class extends br{},li=class extends Ar{};var Hn=class extends X{executeAction(e,t){if(this.type===yn.action)return super.executeAction(e,t);if(this.type===yn.setZIndex){let[n]=this.contentNode.getContent(),i=this.callee.state.zIndex;return this.callee.state.zIndex=n,e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.zIndex=r},[i]),e.stage.update(),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("LayerAction")}};Hn.ActionTypes=yn;var ot=class ot extends Ke{static get DefaultUserConfig(){return ot._defaultUserConfig??(ot._defaultUserConfig=new j({zIndex:0,...ne.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e,t={}){super();let n=ot.DefaultUserConfig.create(t),i=ot.DefaultConfig.create({...n.get(),name:e});this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState()}include(e){return(Array.isArray(e)?e:[e]).forEach(n=>{n.useLayer(this)}),this}setZIndex(e){return this.chain(new Hn(this.chain(),yn.setZIndex,new C().setContent([e])))}bringToFront(){throw new E(`A layer cannot be brought to front. Layers are ordered by z-index, not by the order they were added in \u2014 use Layer.setZIndex to raise one. (layer: ${this.config.name})`)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState().get()),this}toData(){return{state:ot.StateSerializer.serialize(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.state=ot.StateSerializer.deserialize(e.state),this.transformState.resetTo(ne.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}copy(){return new ot(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new Hn(this.chain(),yn.action,new C),new Te(this.chain(),pe.init,new C().setContent([e,null,!1]))]}getInitialState(){return ot.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(ne.DefaultTransformState.keys());return new ne(ne.DefaultTransformState.create(e.get()).get())}};ot._defaultUserConfig=null,ot.DefaultConfig=new j({name:"(anonymous)",zIndex:0}),ot.StateSerializer=new qe,ot.DefaultState=new j({zIndex:0});var Vn=ot;var Dt=class Dt extends X{executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(Dt,"video:preload"))return e.isVideoAdded(i)?S.resolve(super.executeAction(e,t)):(e.addVideo(i),e.stage.update(),e.actionHistory.push(r,()=>{e.isVideoAdded(i)&&(e.removeVideo(i),e.stage.update())}),S.resolve(super.executeAction(e,t)));if(n.is(Dt,"video:play"))return this.changeStateAsync(e,s=>s.play(),t);if(n.is(Dt,"video:pause"))return this.changeState(e,s=>s.pause(),t);if(n.is(Dt,"video:stop"))return this.changeState(e,s=>s.stop(),t);if(n.is(Dt,"video:seek"))return this.changeState(e,s=>s.seek(n.contentNode.getContent()[0]),t);if(n.is(Dt,"video:show")){let s=i.state.display;return e.isVideoAdded(i)||(e.addVideo(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,a=>{i.state.display=a},[s]),this.changeState(e,a=>a.show(),t)}else if(n.is(Dt,"video:hide")){let s=i.state.display;return this.changeState(e,a=>{i.state.display=!1,e.actionHistory.push(r,c=>{i.state.display=c},[s]),a.hide(),e.removeVideo(i),e.stage.update()},t)}else if(n.is(Dt,"video:resume"))return this.changeState(e,s=>s.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new E(`Video is being used before it is added to the game
|
|
31
31
|
Use video.show() to add the video to the game`);let i=this.callee,r=new S,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new U(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};Dt.ActionTypes=Pt;var go=Dt;var Un=class Un extends le{constructor(e){super();let t=Un.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new J("Video must have a src")}preload(){return this.chain(this.createAction(Pt.preload,[]))}show(){return this.chain(this.createAction(Pt.show,[]))}hide(){return this.chain(this.createAction(Pt.hide,[]))}play(){return this.chain(this.createAction(Pt.play,[]))}pause(){return this.chain(this.createAction(Pt.pause,[]))}resume(){return this.chain(this.createAction(Pt.resume,[]))}stop(){return this.chain(this.createAction(Pt.stop,[]))}seek(e){return this.chain(this.createAction(Pt.seek,[e]))}toData(){return{state:{display:this.state.display}}}fromData(e){let{state:t}=e;return this.state={display:t.display},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return Un.DefaultVideoState.create().get()}createAction(e,t){return new go(this.chain(),e,C.create(t))}};Un.DefaultVideoConfig=new j({src:"",muted:!1}),Un.DefaultVideoState=new j({display:!1});var Cr=Un;var Jt=class Jt extends X{executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(Jt,"vfx:preload"))return e.isVfxAdded(i)?S.resolve(super.executeAction(e,t)):(e.addVfx(i),e.stage.update(),e.actionHistory.push(r,()=>{e.isVfxAdded(i)&&(e.removeVfx(i),e.stage.update())}),S.resolve(super.executeAction(e,t)));if(n.is(Jt,"vfx:show")){let[s]=n.contentNode.getContent(),a=i.state.display;return e.isVfxAdded(i)||(e.addVfx(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,c=>{i.state.display=c},[a]),this.changeStateAsync(e,c=>c.show(s),t)}else if(n.is(Jt,"vfx:hide")){if(!e.isVfxAdded(i)||!i.state.display)return e.logger.weakWarn("NarraLeaf-React: Vfx","Hiding a Vfx that is not shown, ignored. (src: "+i.config.src+")"),S.resolve(super.executeAction(e,t));let[s]=n.contentNode.getContent(),a=i.state.display;return this.changeStateAsync(e,async c=>{await c.hide(s),i.state.display=!1,e.actionHistory.push(r,l=>{i.state.display=l},[a])},t)}else{if(n.is(Jt,"vfx:pause"))return this.changeState(e,s=>{i.state.paused=!0,s.pause()},t);if(n.is(Jt,"vfx:resume"))return this.changeState(e,s=>{i.state.paused=!1,s.resume()},t);if(n.is(Jt,"vfx:setRate"))return this.changeState(e,s=>s.setRate(n.contentNode.getContent()[0]),t)}throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVfxAdded(this.callee))throw new E(`Vfx is being used before it is added to the game
|
|
32
|
-
Use vfx.show() to add the vfx to the game`);let i=this.callee,r=new S,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Vfx Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new U(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VfxAction")}};Jt.ActionTypes=Xt;var yo=Jt;var Wn=class Wn extends le{constructor(e){super();let t=Wn.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new J("Vfx must have a src")}preload(){return this.chain(this.createAction(Xt.preload,[]))}show(e){return this.chain(this.createAction(Xt.show,[e]))}hide(e){return this.chain(this.createAction(Xt.hide,[e]))}pause(){return this.chain(this.createAction(Xt.pause,[]))}resume(){return this.chain(this.createAction(Xt.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(Xt.setRate,[e]))}toData(){return{state:{display:this.state.display,paused:this.state.paused}}}fromData(e){let{state:t}=e;return this.state={display:t.display,paused:t.paused},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return Wn.DefaultVfxState.create().get()}createAction(e,t){return new yo(this.chain(),e,C.create(t))}};Wn.DefaultVfxConfig=new j({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),Wn.DefaultVfxState=new j({display:!1,paused:!1});var xr=Wn;var ui=class extends X{executeAction(e,t){if(this.type===et.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===et.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===et.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===et.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===et.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===et.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let c=new S().registerSkipController(new U(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{c.isSettled()||c.resolve(super.executeAction(e,t))});let l=e.timelines.attachTimeline(c);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:l},()=>{c.isSettled()||c.abort()}),c}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};ui.ActionTypes=et;var He=class He extends Ke{constructor(t){super();this.events=new _;this.instance=null;this.status="unmounted";let n=He.DefaultUserConfig.create(t),i=He.DefaultPuppetConfig.create(n.get());if(this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(n),!this.config.backend)throw new J("Puppet must have a backend name");if(!this.config.src)throw new J("Puppet must have a src")}static get DefaultUserConfig(){return He._defaultUserConfig??(He._defaultUserConfig=new j({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...ne.DefaultTransformState.getDefaultConfig()},{position:t=>O.tryParsePosition(t)}))}static normalizeState(t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{...n,motion:typeof n.motion=="string"?n.motion:null,expression:typeof n.expression=="string"?n.expression:null,skin:typeof n.skin=="string"?n.skin:null,params:He.copyParams(n.params),slots:He.copySlots(n.slots)}}static mergeState(t,n){return He.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(et.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(et.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(et.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(et.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(et.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(et.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:He.normalizeState(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(t){return this.state=He.normalizeState(t.state),this.transformState.resetTo(ne.deserialize(t.transformState).get()),this._deserializeLoop(t.loop),this}_init(t){return new Te(this.chain(),pe.init,new C().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}_resolveSize(t){let n=this.config.size;return n?{width:n.width,height:n.height}:{width:t.width,height:t.height}}_getStatus(){return this.getStatus()}_setStatus(t){this.status!==t&&(this.status=t,this.events.emit("event:puppet.statusChange",t))}_onStatusChange(t){return this.onStatusChange(t)}_attachInstance(t){this.instance=t}_getInstance(){return this.instance}_patchState(t){let n=He.normalizeState(this.state);return this.state=He.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(He.normalizeState(this.state))}async _runCommand(t,n){let i=this.instance;return i?(await i.command(t,n),!0):!1}async _describe(){let t=this.instance;return!t||typeof t.describe!="function"?null:await t.describe()}createAction(t,n){return new ui(this.chain(),t,C.create(n))}getInitialTransformState(t){let[n]=t.extract(ne.DefaultTransformState.keys());return new ne(ne.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return He.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};He._defaultUserConfig=null,He.DefaultPuppetConfig=new j({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var Lt=He;var pi=class extends le{constructor(e){super(),this.scene=e}show(e){let t=new ee(this.scene.chain(),z.nvlShow,new C().setContent([e]));return this.chain(t)}hide(e){let t=new ee(this.scene.chain(),z.nvlHide,new C().setContent([e]));return this.chain(t)}end(){let e=new ee(this.scene.chain(),z.nvlEnd,new C().setContent([]));return this.chain(e)}};function kr(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function Ia(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return Ra(o);let i=wr(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=wr(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=wr(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function wr(o,e){if(o===!1||typeof o>"u")return{resolved:!1,source:null};if(typeof o=="function"){let t=o(e);return{resolved:typeof t<"u",source:t??null}}return{resolved:!0,source:o}}function Ra(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}function Ma(o,e){let t=[],n=i=>{i&&typeof i!="function"&&P.isImageSrc(i)&&t.push(i)};n(e?.config.avatar),n(o.config.avatar);for(let i of o.config.portraits||[])n(kr(i).avatar);return t}var ue=class ue{constructor(e,t){this.state={sounds:[],videos:[],vfx:[],srcManagers:[],elements:[]};this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1};this._suppressNextNvlTyping=!1;this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new Xn;this.htmlToImage=Jl;this.pageRouter=null;this.stageClickBuffer=null;this.advanceSuspensions=new Set;this.nvlAdvanceWaiters=new Map;this.advDialogState=null;this._fastForwarding=!1;this.stage=t,this.game=e,this.events=new _,this.logger=new Zi(e,"NarraLeaf-React"),this.audioManager=new eo(this),this.guard=new to(e.config.app.guard).observe(this),this.timelines=new no(this.guard),this.notificationMgr=new io(this,[]),this.idManager=new Ui,this.actionHistory=new so(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new ao(this.actionHistory),this.stageTransition=new ro(this),this.events.on(ue.EventTypes["event:state.player.skip"],()=>{this.game.config.allowSkipSceneTransition&&this.stageTransition.skip()})}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}addVfx(e){return this.state.vfx.push(e),this}removeVfx(e){let t=this.state.vfx.indexOf(e);return t===-1?(this.logger.weakWarn("Vfx not found when removing",e.getId()),this):(this.state.vfx.splice(t,1),this)}isVfxAdded(e){return this.state.vfx.includes(e)}getVfx(){return this.state.vfx}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let i of n.layers.values())if(i.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=Ye.isScene(e)?e:e.entryScene;if(!t)throw new E("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(ue.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}settlePendingLines(e){let t=this.findElementByScene(e);return!t||!t.texts.length?this:([...t.texts].forEach(n=>n.onClick()),this)}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){for(let e=this.state.elements.length-1;e>=0;e--){let t=this.state.elements[e];if(!t.suspended)return t.scene}return null}setSceneSuspended(e,t){let n=this.findElementByScene(e);return n?(n.suspended=t,this.stageTransition.syncScenePose(e,t),this.logger.debug("GameState",t?"Suspending scene":"Resuming scene",e.getId()),this.stage.update(),this):(this.logger.weakWarn("Scene not found when suspending",e.getId()),this)}isSceneSuspended(e){return this.findElementByScene(e)?.suspended===!0}getSuspendedScenes(){return this.state.elements.filter(e=>e.suspended).map(e=>e.scene)}getCurrentScene(){return this.state.elements[0]?.scene||null}isFastForwarding(){return this._fastForwarding}setFastForwarding(e){this._fastForwarding=e}hasActiveMenu(){let e=this.getLastScene();return e?(this.findElementByScene(e)?.menus.length??0)>0:!1}findCurrentPortraitForCharacter(e){let t=(e.config.portraits||[]).map(kr);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let c=s[a];for(let l=c.length-1;l>=0;l--){let u=c[l],d=r.get(u);if(d&&this.isDisplayableVisible(u))return d}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(xe.getCtx({gameState:this}));this.game.getLiveGame().events.emit(Ut.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:ie.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1)},text:ie.getText(s)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let i=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!i)throw this.sceneNotFound();let r=e.prompt?.evaluate(xe.getCtx({gameState:this}))||null,s=this.createWaitableAction({...e,words:r},a=>{i.splice(i.indexOf(s),1),t&&t(a),this.game.getLiveGame().events.emit(Ut.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return i.push(s),{cancel:()=>{let a=i.indexOf(s);a!==-1&&i.splice(a,1)},prompt:r?ie.getText(r):null}}enterNvlMode(e){let t=this.idManager.generateId();return this.nvlState={active:!0,visible:!0,sessionId:t,dialogs:[],options:e||null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.events.emit(ue.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!0,e?.showTransition),this.emitNvlStateChange(),this}exitNvlMode(e){let t=e?.hideTransition||this.nvlState.options?.hideTransition;return this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(ue.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],e),this.emitNvlStateChange(),this}removeNvlDialog(e){let t=this.nvlState.dialogs.findIndex(r=>r.id===e);if(t===-1)return this;let n=[...this.nvlState.dialogs],[i]=n.splice(t,1);return this.nvlState.dialogs=n,this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],i),this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState()),this.emitNvlStateChange(),this}getNvlDialogs(){return this.nvlState.dialogs}isNvlMode(){return this.nvlState.active}getNvlState(){return this.nvlState}createNvlSnapshot(){return{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,dialogs:this.nvlState.dialogs.map(e=>({...e})),options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,isTyping:this.nvlState.isTyping}}createPresentationSnapshot(){return{scenes:this.state.elements.map(({scene:e})=>ee.createSceneSnapshot(e,this)),nvlState:this.createNvlSnapshot()}}restoreNvlSnapshot(e){let t=e.activeDialogId&&e.dialogs.some(n=>n.id===e.activeDialogId)?e.activeDialogId:null;return this.nvlState={active:e.active,visible:e.visible,sessionId:e.sessionId,dialogs:e.dialogs.map(n=>({...n})),options:e.options?{...e.options}:null,activeDialogId:t,phase:t?"awaitAdvance":"idle",pendingAdvance:!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active?(this.events.emit(ue.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(ue.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{ee.restoreSceneSnapshot(t,this)}),this.restoreNvlSnapshot(e.nvlState),this.rebindLoops(),this}rebindLoops(){let[e,t]=this.getLiveGame().constructMaps();return t.forEach(n=>{n instanceof Ke&&n._rebindLoop(e)}),this}clearNvlDialogs(){return this.nvlState.dialogs=[],this.emitNvlStateChange(),this}setNvlActiveDialog(e,t){return this.nvlState.activeDialogId=e,this.nvlState.phase=e?t?"typing":"awaitAdvance":"idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),this}setNvlTyping(e){return this.nvlState.phase=e?"typing":this.nvlState.activeDialogId?"awaitAdvance":"idle",this.syncNvlDerivedState(),this.emitNvlStateChange(),this}getNvlDialog(e){return this.nvlState.dialogs.find(t=>t.id===e)||null}getActiveNvlDialogForAction(e){if(!this.nvlState.activeDialogId)return null;let t=this.getNvlDialog(this.nvlState.activeDialogId);return!t||t.actionId!==e?null:t}getLatestNvlDialogForAction(e){for(let t=this.nvlState.dialogs.length-1;t>=0;t--){let n=this.nvlState.dialogs[t];if(n.actionId===e)return n}return null}allocateNvlDialogId(e){let t=-1;for(let n of this.nvlState.dialogs){if(n.actionId!==e)continue;let i=n.id.startsWith(`${e}:`)?Number.parseInt(n.id.slice(e.length+1),10):Number.NaN;Number.isNaN(i)||(t=Math.max(t,i))}return`${e}:${t+1}`}ensureNvlDialog(e){let t=this.getNvlDialog(e.id);return t?(t.character=e.character,t.sentence=e.sentence,t.text=e.text,this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],t),this.emitNvlStateChange(),{created:!1,entry:t}):(this.appendNvlDialog(e),{created:!0,entry:e})}activateNvlDialog(e,t="typing",n=!0){return n&&this.nvlState.activeDialogId===e&&this.nvlState.phase!=="idle"||(this.nvlState.activeDialogId=e,this.nvlState.phase=t,this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}waitForNvlAdvance(e,t){return this.nvlAdvanceWaiters.set(e,t),{cancel:()=>{this.nvlAdvanceWaiters.get(e)===t&&this.nvlAdvanceWaiters.delete(e)}}}requestNvlAdvance(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?"ignore":this.nvlState.phase==="typing"?"typing":this.nvlState.phase==="awaitAdvance"?(this.resolveNvlAdvance(e),"advance"):"ignore"}requestNvlSkip(e){return this.requestNvlAdvance(e)}completeNvlTyping(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?!1:(this.nvlState.phase="awaitAdvance",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.events.emit(ue.EventTypes["event:state.nvl.dialogComplete"],e),this.emitNvlStateChange(),!0)}settleNvlDialog(e){return this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}suppressNextNvlTyping(){return this._suppressNextNvlTyping=!0,this}consumeNvlTypingSuppression(){return this._suppressNextNvlTyping?(this._suppressNextNvlTyping=!1,!0):!1}beginAdvDialog(e,t){return this.advDialogState={dialogId:e,actionId:t,ended:!1},this.events.emit(ue.EventTypes["event:state.dialog.change"]),this}completeAdvDialogTyping(e){return!e||!this.advDialogState||this.advDialogState.dialogId!==e?this:(this.advDialogState.ended||(this.advDialogState.ended=!0,this.events.emit(ue.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(ue.EventTypes["event:state.dialog.change"])),this}getAdvDialogState(){return this.advDialogState}recordStageClick(){return this.stageClickBuffer={timestamp:Date.now()},this}suspendAdvance(){let e=Symbol("advance-suspension");return this.advanceSuspensions.add(e),()=>{this.advanceSuspensions.delete(e)}}isAdvanceSuspended(){return this.advanceSuspensions.size>0}consumeStageClick(e=200){if(!this.stageClickBuffer)return!1;let{timestamp:t}=this.stageClickBuffer,n=Date.now()-t;return this.stageClickBuffer=null,n>=0&&n<=e}createDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i);if(!r)throw this.sceneNotFound();let s=r.layers.get(n||i.config.defaultDisplayableLayer);if(!s)throw this.layerNotFound();return s.push(e),this}disposeDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i)?.layers.get(n||i.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();let s=r.indexOf(e);if(s===-1)throw new E(`Displayables not found when disposing. (disposing: ${e.getId()})`);return r.splice(s,1),this}forceReset(){[...this.state.elements].forEach(({scene:t})=>{this.offSrcManager(t.srcManager),this.removeScene(t),t.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.state.vfx=[],this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return Na.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new E("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=we.proxy(S.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof Ke&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(Z.immediate({}),()=>{});t.attachChild(s),r.updateStyleSync(),"flush"in r&&r.flush()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new Ae("State already mounted");if(!e)throw new Ae("Invalid state key");return this.exposedState.set(e,t),this.events.emit(ue.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new E("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let i=this.events.on(ue.EventTypes["event.state.onExpose"],(r,s)=>{r===e&&(t(s),i.cancel())});return i}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),...e.suspended?{suspended:!0}:{},elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(i=>i.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()]),vfx:this.state.vfx.map(e=>[e.getId(),e.toData()]),nvlState:{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,dialogIds:this.nvlState.dialogs.map(e=>e.id),dialogs:this.nvlState.dialogs.map(e=>({id:e.id,actionId:e.actionId,text:e.text,characterId:e.character?e.character.getId():null}))}}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:i,audio:r,videos:s}=e;if(i.forEach(({sceneId:a,elements:c,suspended:l})=>{this.logger.debug("Loading scene: "+a);let u=t.get(a);if(!u)throw new E("Scene not found, id: "+a+`
|
|
32
|
+
Use vfx.show() to add the vfx to the game`);let i=this.callee,r=new S,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Vfx Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new U(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VfxAction")}};Jt.ActionTypes=Xt;var yo=Jt;var Wn=class Wn extends le{constructor(e){super();let t=Wn.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new J("Vfx must have a src")}preload(){return this.chain(this.createAction(Xt.preload,[]))}show(e){return this.chain(this.createAction(Xt.show,[e]))}hide(e){return this.chain(this.createAction(Xt.hide,[e]))}pause(){return this.chain(this.createAction(Xt.pause,[]))}resume(){return this.chain(this.createAction(Xt.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(Xt.setRate,[e]))}toData(){return{state:{display:this.state.display,paused:this.state.paused}}}fromData(e){let{state:t}=e;return this.state={display:t.display,paused:t.paused},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return Wn.DefaultVfxState.create().get()}createAction(e,t){return new yo(this.chain(),e,C.create(t))}};Wn.DefaultVfxConfig=new j({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),Wn.DefaultVfxState=new j({display:!1,paused:!1});var xr=Wn;var ui=class extends X{executeAction(e,t){if(this.type===et.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===et.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===et.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===et.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===et.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===et.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let c=new S().registerSkipController(new U(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{c.isSettled()||c.resolve(super.executeAction(e,t))});let l=e.timelines.attachTimeline(c);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:l},()=>{c.isSettled()||c.abort()}),c}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};ui.ActionTypes=et;var He=class He extends Ke{constructor(t){super();this.events=new _;this.instance=null;this.status="unmounted";let n=He.DefaultUserConfig.create(t),i=He.DefaultPuppetConfig.create(n.get());if(this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(n),!this.config.backend)throw new J("Puppet must have a backend name");if(!this.config.src)throw new J("Puppet must have a src")}static get DefaultUserConfig(){return He._defaultUserConfig??(He._defaultUserConfig=new j({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...ne.DefaultTransformState.getDefaultConfig()},{position:t=>O.tryParsePosition(t)}))}static normalizeState(t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{...n,motion:typeof n.motion=="string"?n.motion:null,expression:typeof n.expression=="string"?n.expression:null,skin:typeof n.skin=="string"?n.skin:null,params:He.copyParams(n.params),slots:He.copySlots(n.slots)}}static mergeState(t,n){return He.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(et.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(et.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(et.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(et.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(et.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(et.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:He.normalizeState(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(t){return this.state=He.normalizeState(t.state),this.transformState.resetTo(ne.deserialize(t.transformState).get()),this._deserializeLoop(t.loop),this}_init(t){return new Te(this.chain(),pe.init,new C().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}_resolveSize(t){let n=this.config.size;return n?{width:n.width,height:n.height}:{width:t.width,height:t.height}}_getStatus(){return this.getStatus()}_setStatus(t){this.status!==t&&(this.status=t,this.events.emit("event:puppet.statusChange",t))}_onStatusChange(t){return this.onStatusChange(t)}_attachInstance(t){this.instance=t}_getInstance(){return this.instance}_patchState(t){let n=He.normalizeState(this.state);return this.state=He.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(He.normalizeState(this.state))}async _runCommand(t,n){let i=this.instance;return i?(await i.command(t,n),!0):!1}async _describe(){let t=this.instance;return!t||typeof t.describe!="function"?null:await t.describe()}createAction(t,n){return new ui(this.chain(),t,C.create(n))}getInitialTransformState(t){let[n]=t.extract(ne.DefaultTransformState.keys());return new ne(ne.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return He.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};He._defaultUserConfig=null,He.DefaultPuppetConfig=new j({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var Lt=He;var pi=class extends le{constructor(e){super(),this.scene=e}show(e){let t=new ee(this.scene.chain(),z.nvlShow,new C().setContent([e]));return this.chain(t)}hide(e){let t=new ee(this.scene.chain(),z.nvlHide,new C().setContent([e]));return this.chain(t)}end(){let e=new ee(this.scene.chain(),z.nvlEnd,new C().setContent([]));return this.chain(e)}};function kr(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function Ia(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return Ra(o);let i=wr(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=wr(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=wr(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function wr(o,e){if(o===!1||typeof o>"u")return{resolved:!1,source:null};if(typeof o=="function"){let t=o(e);return{resolved:typeof t<"u",source:t??null}}return{resolved:!0,source:o}}function Ra(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}function Ma(o,e){let t=[],n=i=>{i&&typeof i!="function"&&P.isImageSrc(i)&&t.push(i)};n(e?.config.avatar),n(o.config.avatar);for(let i of o.config.portraits||[])n(kr(i).avatar);return t}var ue=class ue{constructor(e,t){this.state={sounds:[],videos:[],vfx:[],srcManagers:[],elements:[]};this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1};this._suppressNextNvlTyping=!1;this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new Xn;this.htmlToImage=Zl;this.pageRouter=null;this.stageClickBuffer=null;this.advanceSuspensions=new Set;this.nvlAdvanceWaiters=new Map;this.advDialogState=null;this._fastForwarding=!1;this.stage=t,this.game=e,this.events=new _,this.logger=new Zi(e,"NarraLeaf-React"),this.audioManager=new eo(this),this.guard=new to(e.config.app.guard).observe(this),this.timelines=new no(this.guard),this.notificationMgr=new io(this,[]),this.idManager=new Ui,this.actionHistory=new so(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new ao(this.actionHistory),this.stageTransition=new ro(this),this.events.on(ue.EventTypes["event:state.player.skip"],()=>{this.game.config.allowSkipSceneTransition&&this.stageTransition.skip()})}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}addVfx(e){return this.state.vfx.push(e),this}removeVfx(e){let t=this.state.vfx.indexOf(e);return t===-1?(this.logger.weakWarn("Vfx not found when removing",e.getId()),this):(this.state.vfx.splice(t,1),this)}isVfxAdded(e){return this.state.vfx.includes(e)}getVfx(){return this.state.vfx}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let i of n.layers.values())if(i.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=Ye.isScene(e)?e:e.entryScene;if(!t)throw new E("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(ue.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}settlePendingLines(e){let t=this.findElementByScene(e);return!t||!t.texts.length?this:([...t.texts].forEach(n=>n.onClick()),this)}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){for(let e=this.state.elements.length-1;e>=0;e--){let t=this.state.elements[e];if(!t.suspended)return t.scene}return null}setSceneSuspended(e,t){let n=this.findElementByScene(e);return n?(n.suspended=t,this.stageTransition.syncScenePose(e,t),this.logger.debug("GameState",t?"Suspending scene":"Resuming scene",e.getId()),this.stage.update(),this):(this.logger.weakWarn("Scene not found when suspending",e.getId()),this)}isSceneSuspended(e){return this.findElementByScene(e)?.suspended===!0}getSuspendedScenes(){return this.state.elements.filter(e=>e.suspended).map(e=>e.scene)}getCurrentScene(){return this.state.elements[0]?.scene||null}isFastForwarding(){return this._fastForwarding}setFastForwarding(e){this._fastForwarding=e}hasActiveMenu(){let e=this.getLastScene();return e?(this.findElementByScene(e)?.menus.length??0)>0:!1}findCurrentPortraitForCharacter(e){let t=(e.config.portraits||[]).map(kr);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let c=s[a];for(let l=c.length-1;l>=0;l--){let u=c[l],d=r.get(u);if(d&&this.isDisplayableVisible(u))return d}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(xe.getCtx({gameState:this}));this.game.getLiveGame().events.emit(Ut.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:ie.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1)},text:ie.getText(s)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let i=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!i)throw this.sceneNotFound();let r=e.prompt?.evaluate(xe.getCtx({gameState:this}))||null,s=this.createWaitableAction({...e,words:r},a=>{i.splice(i.indexOf(s),1),t&&t(a),this.game.getLiveGame().events.emit(Ut.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return i.push(s),{cancel:()=>{let a=i.indexOf(s);a!==-1&&i.splice(a,1)},prompt:r?ie.getText(r):null}}enterNvlMode(e){let t=this.idManager.generateId();return this.nvlState={active:!0,visible:!0,sessionId:t,dialogs:[],options:e||null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.events.emit(ue.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!0,e?.showTransition),this.emitNvlStateChange(),this}exitNvlMode(e){let t=e?.hideTransition||this.nvlState.options?.hideTransition;return this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(ue.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],e),this.emitNvlStateChange(),this}removeNvlDialog(e){let t=this.nvlState.dialogs.findIndex(r=>r.id===e);if(t===-1)return this;let n=[...this.nvlState.dialogs],[i]=n.splice(t,1);return this.nvlState.dialogs=n,this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],i),this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState()),this.emitNvlStateChange(),this}getNvlDialogs(){return this.nvlState.dialogs}isNvlMode(){return this.nvlState.active}getNvlState(){return this.nvlState}createNvlSnapshot(){return{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,dialogs:this.nvlState.dialogs.map(e=>({...e})),options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,isTyping:this.nvlState.isTyping}}createPresentationSnapshot(){return{scenes:this.state.elements.map(({scene:e})=>ee.createSceneSnapshot(e,this)),nvlState:this.createNvlSnapshot()}}restoreNvlSnapshot(e){let t=e.activeDialogId&&e.dialogs.some(n=>n.id===e.activeDialogId)?e.activeDialogId:null;return this.nvlState={active:e.active,visible:e.visible,sessionId:e.sessionId,dialogs:e.dialogs.map(n=>({...n})),options:e.options?{...e.options}:null,activeDialogId:t,phase:t?"awaitAdvance":"idle",pendingAdvance:!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active?(this.events.emit(ue.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(ue.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{ee.restoreSceneSnapshot(t,this)}),this.restoreNvlSnapshot(e.nvlState),this.rebindLoops(),this}rebindLoops(){let[e,t]=this.getLiveGame().constructMaps();return t.forEach(n=>{n instanceof Ke&&n._rebindLoop(e)}),this}clearNvlDialogs(){return this.nvlState.dialogs=[],this.emitNvlStateChange(),this}setNvlActiveDialog(e,t){return this.nvlState.activeDialogId=e,this.nvlState.phase=e?t?"typing":"awaitAdvance":"idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),this}setNvlTyping(e){return this.nvlState.phase=e?"typing":this.nvlState.activeDialogId?"awaitAdvance":"idle",this.syncNvlDerivedState(),this.emitNvlStateChange(),this}getNvlDialog(e){return this.nvlState.dialogs.find(t=>t.id===e)||null}getActiveNvlDialogForAction(e){if(!this.nvlState.activeDialogId)return null;let t=this.getNvlDialog(this.nvlState.activeDialogId);return!t||t.actionId!==e?null:t}getLatestNvlDialogForAction(e){for(let t=this.nvlState.dialogs.length-1;t>=0;t--){let n=this.nvlState.dialogs[t];if(n.actionId===e)return n}return null}allocateNvlDialogId(e){let t=-1;for(let n of this.nvlState.dialogs){if(n.actionId!==e)continue;let i=n.id.startsWith(`${e}:`)?Number.parseInt(n.id.slice(e.length+1),10):Number.NaN;Number.isNaN(i)||(t=Math.max(t,i))}return`${e}:${t+1}`}ensureNvlDialog(e){let t=this.getNvlDialog(e.id);return t?(t.character=e.character,t.sentence=e.sentence,t.text=e.text,this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],t),this.emitNvlStateChange(),{created:!1,entry:t}):(this.appendNvlDialog(e),{created:!0,entry:e})}activateNvlDialog(e,t="typing",n=!0){return n&&this.nvlState.activeDialogId===e&&this.nvlState.phase!=="idle"||(this.nvlState.activeDialogId=e,this.nvlState.phase=t,this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}waitForNvlAdvance(e,t){return this.nvlAdvanceWaiters.set(e,t),{cancel:()=>{this.nvlAdvanceWaiters.get(e)===t&&this.nvlAdvanceWaiters.delete(e)}}}requestNvlAdvance(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?"ignore":this.nvlState.phase==="typing"?"typing":this.nvlState.phase==="awaitAdvance"?(this.resolveNvlAdvance(e),"advance"):"ignore"}requestNvlSkip(e){return this.requestNvlAdvance(e)}completeNvlTyping(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?!1:(this.nvlState.phase="awaitAdvance",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.events.emit(ue.EventTypes["event:state.nvl.dialogComplete"],e),this.emitNvlStateChange(),!0)}settleNvlDialog(e){return this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}suppressNextNvlTyping(){return this._suppressNextNvlTyping=!0,this}consumeNvlTypingSuppression(){return this._suppressNextNvlTyping?(this._suppressNextNvlTyping=!1,!0):!1}beginAdvDialog(e,t){return this.advDialogState={dialogId:e,actionId:t,ended:!1},this.events.emit(ue.EventTypes["event:state.dialog.change"]),this}completeAdvDialogTyping(e){return!e||!this.advDialogState||this.advDialogState.dialogId!==e?this:(this.advDialogState.ended||(this.advDialogState.ended=!0,this.events.emit(ue.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(ue.EventTypes["event:state.dialog.change"])),this}getAdvDialogState(){return this.advDialogState}recordStageClick(){return this.stageClickBuffer={timestamp:Date.now()},this}suspendAdvance(){let e=Symbol("advance-suspension");return this.advanceSuspensions.add(e),()=>{this.advanceSuspensions.delete(e)}}isAdvanceSuspended(){return this.advanceSuspensions.size>0}consumeStageClick(e=200){if(!this.stageClickBuffer)return!1;let{timestamp:t}=this.stageClickBuffer,n=Date.now()-t;return this.stageClickBuffer=null,n>=0&&n<=e}createDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i);if(!r)throw this.sceneNotFound();let s=r.layers.get(n||i.config.defaultDisplayableLayer);if(!s)throw this.layerNotFound();return s.push(e),this}disposeDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i)?.layers.get(n||i.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();let s=r.indexOf(e);if(s===-1)throw new E(`Displayables not found when disposing. (disposing: ${e.getId()})`);return r.splice(s,1),this}forceReset(){[...this.state.elements].forEach(({scene:t})=>{this.offSrcManager(t.srcManager),this.removeScene(t),t.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.state.vfx=[],this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return Na.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new E("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=we.proxy(S.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof Ke&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(Z.immediate({}),()=>{});t.attachChild(s),r.updateStyleSync(),"flush"in r&&r.flush()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new Ae("State already mounted");if(!e)throw new Ae("Invalid state key");return this.exposedState.set(e,t),this.events.emit(ue.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new E("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let i=this.events.on(ue.EventTypes["event.state.onExpose"],(r,s)=>{r===e&&(t(s),i.cancel())});return i}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),...e.suspended?{suspended:!0}:{},elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(i=>i.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()]),vfx:this.state.vfx.map(e=>[e.getId(),e.toData()]),nvlState:{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,dialogIds:this.nvlState.dialogs.map(e=>e.id),dialogs:this.nvlState.dialogs.map(e=>({id:e.id,actionId:e.actionId,text:e.text,characterId:e.character?e.character.getId():null}))}}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:i,audio:r,videos:s}=e;if(i.forEach(({sceneId:a,elements:c,suspended:l})=>{this.logger.debug("Loading scene: "+a);let u=t.get(a);if(!u)throw new E("Scene not found, id: "+a+`
|
|
33
33
|
NarraLeaf cannot find the element with the id from the saved game`);let d={scene:u,layers:this.constructLayerMap(c.layers,t),menus:[],texts:[],suspended:l===!0};this.state.elements.push(d),this.registerSrcManager(u.srcManager),d.suspended||this.getExposedStateAsync(u,p=>{ee.initBackgroundMusic(u,p,this)})}),this.audioManager.fromData(r,t),this.state.videos=s.map(([a,c])=>{let l=t.get(a);if(!l)throw new E("Video not found, id: "+a+`
|
|
34
34
|
NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),this.state.vfx=(e.vfx??[]).flatMap(([a,c])=>{let l=t.get(a);return l?(l.fromData(c),[l]):(this.logger.weakWarn("NarraLeaf-React: Vfx","Vfx not found when loading a saved game, skipped. (id: "+a+")"),[])}),e.nvlState){let a=(e.nvlState.dialogs||[]).map(c=>{let l=c.characterId&&t.get(c.characterId)||null,u=c.text||"";return{id:c.id,actionId:c.actionId||c.id,character:l,sentence:new me(u,{character:l}),text:u}});this.nvlState={active:e.nvlState.active,visible:e.nvlState.visible,sessionId:e.nvlState.sessionId,dialogs:a,options:e.nvlState.options||null,activeDialogId:e.nvlState.activeDialogId||null,phase:e.nvlState.phase||(e.nvlState.activeDialogId?"awaitAdvance":"idle"),pendingAdvance:e.nvlState.pendingAdvance||!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active&&this.events.emit(ue.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.nvlState.visible&&this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!0,this.nvlState.options?.showTransition),this.emitNvlStateChange()}}getLastSceneIfNot(e){let t=e||this.getLastScene();if(!t||!this.sceneExists(t))throw new E('Scene not found, please call "scene.activate()" first.');return t}createElementSnapshot(e){return{scene:e.scene,suspended:e.suspended===!0,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(i=>[i,i.toData()])]))}}fromElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(([i,r])=>(i.fromData(r),i))])),texts:[],menus:[]}}removeElements(e){let t=this.state.elements.findIndex(n=>n.scene===e);return t===-1?(this.logger.weakWarn("Scene not found when removing elements",e.getId()),this):(this.resetLayers(this.state.elements[t].layers),this.state.elements.splice(t,1),this.logger.debug("GameState","Removing elements",e.getId()),this)}resetLayers(e){let t=this.getLiveGame().story?.camera??null;e.forEach((n,i)=>{i.reset(),n.forEach(r=>{t&&r===t||r.reset()})})}syncNvlDerivedState(){this.nvlState.isTyping=this.nvlState.phase==="typing",this.nvlState.activeDialogId||(this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.nvlState.isTyping=!1)}emitNvlStateChange(){this.syncNvlDerivedState(),this.events.emit(ue.EventTypes["event:state.nvl.change"],this.getNvlState()),this.stage.update()}resolveNvlAdvance(e){let t=this.nvlAdvanceWaiters.get(e);return t?(this.nvlAdvanceWaiters.delete(e),this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),t(),!0):!1}isDisplayableVisible(e){return(e.transformState.get().opacity??0)>0}createWaitableAction(e,t){return{action:e,onClick:(i=>{t&&t(i)})}}sceneNotFound(){return new E("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new E("Layer not found, target layer may not be activated. You may forget to add the layer to the scene config")}constructLayerMap(e,t){return new Map(Object.entries(e).map(([n,i])=>{let r=t.get(n);if(!r)throw new E("Layer not found, id: "+n+`
|
|
35
35
|
NarraLeaf cannot find the element with the id from the saved game`);return[r,i.map(s=>{if(!t.has(s))throw new E("Displayable not found, id: "+s+`
|
|
@@ -39,30 +39,30 @@ To prevent unintended behavior and unexpected results, the sound have to be on t
|
|
|
39
39
|
Maybe you bind the same wearable image to multiple parent images
|
|
40
40
|
Parent Conflict (src: `+d.get(y)?.state.currentSrc+`)
|
|
41
41
|
Current Parent (src: `+m.state.currentSrc+")");d.set(y,m)}});let p=[...this._initScene(this),...l.map(m=>m._init(this)),...u.map(m=>{if(!d.has(m))throw new Error("Wearable image must have a parent image");return d.get(m)._initWearable(m)}),...a.map(m=>m._init()),...c.map(m=>m._init()),...r],h=super.constructNodes(p),g=new C(this.sceneRoot,void 0,h||void 0).setContent(this);return h?.setParent(g),this.sceneRoot?.setContentNode(g),this._futureActions_=p,this.constructLabels(t),this}constructLabels(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!1}),i=new Map;for(let r of n)if(r instanceof se&&r.type===re.label){let[s]=r.contentNode.getContent();if(i.has(s))throw new Oe(`Duplicate label "${s}" in scene "${this.config.name}". Label names must be unique within a scene.`);i.set(s,r)}this.labelMap=i;for(let r of n)if(r instanceof se&&r.type===re.jump){let[s]=r.contentNode.getContent(),a=i.get(s);if(!a)throw new Oe(`Jump target label "${s}" not found in scene "${this.config.name}". Control.jump can only jump to a Control.label declared in the same scene.`);r.setJumpTarget(a)}}getLabel(t){return this.labelMap.get(t)||null}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?_t.say(n).getActions():Be.toActions([n]))}isSceneRootConstructed(){return!!this.sceneRoot}registerSrc(t,n=new Set){if(!this.sceneRoot)return;let i=new Set,r=new Set,s=[this.sceneRoot],a=new Set;for(;s.length;){let c=s.shift();if(!i.has(c)){if(i.add(c),c instanceof ee){let l=c.callee;if(P.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:P.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===z.jumpTo||c.type===z.callTo){let d=c,p=d.contentNode.getContent()[0],h=Pe.getScene(t,p);if(!h)throw c._sceneNotFoundError(c.getSceneName(p));let g=Re.getPreloadableSrc(t,c);if(g&&this.srcManager.register(g),!r.has(d)&&!n.has(h))r.add(d),a.add(h),n.add(h);else if(c.type===z.jumpTo)continue}}else if(c instanceof ve){let l=Re.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof tt)this.srcManager.register(c.callee);else if(c instanceof it){let l=c.type===Yt.say?c.contentNode.getContent():null;for(let u of Ma(c.callee,l))this.srcManager.register({type:"image",src:P.srcToURL(u)})}else if(c instanceof se){let u=c.getFutureActions(t,{allowFutureScene:!0});s.push(...u)}else c instanceof Te&&this.srcManager.register(c.callee.srcManager.getSrc());s.push(...c.getFutureActions(t,{allowFutureScene:!0}))}}a.forEach(c=>{c.registerSrc(t,n),this.srcManager.registerFuture(c.srcManager)})}assignActionId(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}),i=new Set;n.forEach(a=>{let c=a.getStaticId();if(c){if(i.has(c))throw new Oe(`Duplicate static action id: ${c}`);i.add(c)}});let r=0,s=()=>{let a=`a-${r++}`;for(;i.has(a);)a=`a-${r++}`;return i.add(a),a};n.forEach(a=>{let c=a.getStaticId();a.resolveId(c||s())})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((s,a)=>{s.resolveId(`e-${a}`)});let i=new Set;this.getAllChildren(t,this.sceneRoot||[]).forEach(s=>{Pe.getOwnedSounds(s).forEach(a=>i.add(a))});let r=0;i.forEach(s=>{s.getId()||s.resolveId(`s-${r}`),r++})}getVoice(t){if(!t)return null;let n=this.config.voices;if(n){if(typeof n=="function"){let r=n(t);return typeof r=="string"?this.voiceOfSrc(r):(Pe.validateVoice(r),r)}let i=n[t];return typeof i=="string"?this.voiceOfSrc(i):i||null}return null}voiceOfSrc(t){let n=this.voiceCache.get(t);if(n)return n;let i=fe.voice(t);return this.voiceCache.set(t,i),i}getSceneRoot(){if(!this.sceneRoot)throw new Error("Scene root is not constructed");return this.sceneRoot}stringify(t,n,i){return super.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).map(r=>r.stringify(t,n,i)).join(";")}reset(){super.reset(),this.state.backgroundImage.reset(),this.state.backgroundMusic?.reset(),this.state=this.getInitialState()}getInitialState(){let t=this.userConfig.get();if(t.backgroundMusic&&!Ji(t.backgroundMusic.config.type,[nt.bgm]))throw new Oe(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
|
|
42
|
-
To prevent unintended behavior and unexpected results, the sound have to be on the music bus (or any bus beneath it). Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new F({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new ee(this.chain(),"scene:jumpTo",new C().setContent([t])))}_callTo(t){return this.chain(new ee(this.chain(),"scene:callTo",new C().setContent([t])))}_resume(t){return this.chain(new ee(this.chain(),"scene:resume",new C().setContent([t])))}_preSuspend(t){return new ee(this.chain(),"scene:preSuspend",new C().setContent([t]))}_exit(){return new ee(this.chain(),"scene:exit",new C().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new ee(i,z.transitionToScene,new C().setContent([t,n]))):i}_init(t){return new ee(this.chain(),"scene:init",new C().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};Pe.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},Pe.DefaultUserConfig=new j({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),Pe._defaultSceneConfig=null;var Ye=Pe;var Ga=3;var Fa="scene:resume",Oa=32767,
|
|
42
|
+
To prevent unintended behavior and unexpected results, the sound have to be on the music bus (or any bus beneath it). Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new F({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new ee(this.chain(),"scene:jumpTo",new C().setContent([t])))}_callTo(t){return this.chain(new ee(this.chain(),"scene:callTo",new C().setContent([t])))}_resume(t){return this.chain(new ee(this.chain(),"scene:resume",new C().setContent([t])))}_preSuspend(t){return new ee(this.chain(),"scene:preSuspend",new C().setContent([t]))}_exit(){return new ee(this.chain(),"scene:exit",new C().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new ee(i,z.transitionToScene,new C().setContent([t,n]))):i}_init(t){return new ee(this.chain(),"scene:init",new C().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};Pe.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},Pe.DefaultUserConfig=new j({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),Pe._defaultSceneConfig=null;var Ye=Pe;var Ga=3;var Fa="scene:resume",Oa=32767,eu=1e3,Xe=class o{constructor(e,t=void 0){this.liveGame=e;this.__tag=void 0;this.waitingAction=null;this.executingWaitingAction=!1;this.loopConfig=null;this.loopBodyActions=[];this.loopCondition=null;this.loopStartTime=0;this.loopDebugCheckpoint=0;this.__tag=t,this.stack=new Bi().addPushValidator(n=>{let i=this.stack.peek();if(n===i)throw new Ae("StackModel: Unexpected self-push in stack.");if(o.isCalledActionResult(i)){if(i.wait&&o.isStackModelsAwaiting(i.wait.type,i.wait.stackModels))throw new Ae("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(S.isAwaitable(i)&&!i.isSettled())throw new Ae("StackModel: Unexpected unsettled Awaitable in stack.");if(!o.isCalledActionResult(n)&&!S.isAwaitable(n))throw new Ae("StackModel: Unexpected non-CalledActionResult or Awaitable in stack.");return!0})}static isStackModel(e){return e instanceof o}static createStackModel(e,t,n){let i=new o(e);return i.deserialize(t,n),i}static createCountLoop(e,t,n){let i=new o(e,"loop:count");return i.initLoop({type:"count",counter:0,limit:t,bodyActionIds:n.map(r=>r.getId()),broken:!1},n,null),i}static createConditionLoop(e,t,n,i){let r=new o(e,"loop:condition");return r.initLoop({type:"condition",counter:0,conditionActionId:n,bodyActionIds:i.map(s=>s.getId()),broken:!1},i,t),r}static isCalledActionResult(e){return!!e&&!this.isStackModel(e)&&!S.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?S.any(...t.map(n=>n.execute())):S.all(...t.map(n=>n.execute()))}static isStackModelsAwaiting(e,t){if(t.length===0)throw new Error("StackModel: StackModels are empty.");return e==="any"?t.every(n=>!n.isEmpty()):t.some(n=>!n.isEmpty())}initLoop(e,t,n){this.loopConfig=e,this.loopBodyActions=t,this.loopCondition=n,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=0,this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody()}shouldContinueLoop(e){return!this.loopConfig||this.loopConfig.broken?!1:this.loopConfig.type==="count"?this.loopConfig.counter<(this.loopConfig.limit??0):this.loopCondition?this.loopCondition.evaluate({gameState:e}).value:!1}pushLoopBody(){if(this.loopBodyActions.length!==0)for(let e=this.loopBodyActions.length-1;e>=0;e--)this.stack.push(o.fromAction(this.loopBodyActions[e]))}onIterationComplete(){!this.loopConfig||this.loopConfig.broken||(this.loopConfig.counter++,this.liveGame.game.config.app.debug&&this.checkInfiniteLoop(),this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody())}checkInfiniteLoop(){if(!this.loopConfig)return;let e=this.loopConfig.counter;if(e>0&&e%Oa===0){let t=Date.now()-this.loopStartTime;if(e-this.loopDebugCheckpoint>=Oa&&t<eu){let i=new E(`[NarraLeaf] Potential infinite loop detected!
|
|
43
43
|
Loop has executed ${e} iterations in ${t}ms.
|
|
44
44
|
This is likely a bug in your game script. Check your loop conditions.
|
|
45
45
|
Loop type: ${this.loopConfig.type}, broken: ${this.loopConfig.broken}`);throw this.liveGame.getGameStateForce().logger.error("StackModel",i.message),i}this.loopDebugCheckpoint=e,this.loopStartTime=Date.now()}}breakLoop(){if(!this.loopConfig)throw new E("Cannot break: StackModel is not a loop");this.loopConfig.broken=!0,this.stack.clear()}isLoop(){return this.loopConfig!==null}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(S.isAwaitable(e)&&!e.isSettled())return e;if(o.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(o.isStackModelsAwaiting(e.wait.type,n))return n.forEach(i=>i.rollNext()),e;n.forEach(i=>{i.isEmpty()||i.abandon()})}this.waitingAction=null;let t=this.stack.pop();if(S.isAwaitable(t)){if(t.isFailed())throw t.error;let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=null,t=!1,n=new S().registerSkipController(new U(()=>{t=!0,e?.abort()}));return(async()=>{let r=0;for(;!t;){if(r++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){if(this.loopConfig&&!this.loopConfig.broken&&(this.onIterationComplete(),!this.stack.isEmpty()))continue;t=!0;break}let s=this.rollNext();if(s){if(S.isAwaitable(s)){if(s.isFailed())throw s.error;if(s.isSettled())continue;if(e=s,await new Promise(a=>{s.onSettled(a)}),s.isFailed())throw s.error;if(s.isAborted()){t=!0;break}}else if(o.isCalledActionResult(s))if(s.wait)e=o.executeStackModelGroup(s.wait.type,s.wait.stackModels),await e;else continue}}})().then(()=>n.resolve()).catch(r=>n.fail(r)),n}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&S.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):o.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getWaitingAwaitable(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&S.isAwaitable(e)&&!e.isSettled()?e:null}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(o.isCalledActionResult(n))return n;if(e)throw new Ae("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}peekTopActionId(){for(let e=this.stack.size()-1;e>=0;e--){let t=this.stack.get(e);if(o.isCalledActionResult(t))return t.node?.action?.getId()??null}return null}peekExecutingActionId(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&o.isCalledActionResult(e)?e.node?.action?.getId()??null:null}snapshot(){let e=[];for(let n=this.stack.size()-1;n>=0;n--){let i=this.stack.get(n);if(!o.isCalledActionResult(i))continue;let r={actionId:i.node?.action?.getId()??null,actionType:i.node?.action?.type??null};i.wait?.stackModels&&(r.branchWaitType=i.wait.type,r.branches=i.wait.stackModels.map(s=>s.snapshot())),e.push(r)}let t={frames:e};return this.__tag&&(t.tag=this.__tag),this.loopConfig&&(t.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,broken:this.loopConfig.broken}),t}executeActions(e){if(!e.node?.action)return null;this.executingWaitingAction=!0;let t;try{t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this})}finally{this.executingWaitingAction=!1}let n=i=>i?S.isAwaitable(i)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",i),this.stack.push(i),i):i.node?.action||i.wait?.stackModels.length?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",i),this.stack.push(i),i):null:null;if(Array.isArray(t)){let i=null;for(let r of t){let s=n(r);s&&(i=s)}return i}else{let i=n(t);if(i)return i}return null}isWaiting(){let e=this.stack.peek();return e?S.isAwaitable(e)?!e.isSettled():o.isCalledActionResult(e)&&e.wait?o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(e=!0){let t=a=>{if(o.isCalledActionResult(a)){let c=a.node?.action?.getId()??null,l=a.node?.action?.type??null;return a.wait?.stackModels?{type:"link",actionType:l,action:c,stacks:a.wait.stackModels.map(u=>u.serialize()),stackWaitType:a.wait.type}:{type:"action",actionType:l,action:c}}return null},n=this.stack.map(t).filter(function(a){return a!==null}),i=this.stack.peek(),r=this.executingWaitingAction||S.isAwaitable(i);if(e&&this.waitingAction&&r){let a=t(this.waitingAction);a&&n.push(a)}let s={items:n};return this.loopConfig&&(s.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,conditionActionId:this.loopConfig.conditionActionId,bodyActionIds:this.loopConfig.bodyActionIds,broken:this.loopConfig.broken}),s}abandon(){let e=[];if(this.collectCallFrames(e),e.length){let t=this.liveGame.getGameStateForce();e.forEach(n=>n.abandon(t))}return this.reset(),this}collectCallFrames(e){let t=n=>{if(!o.isCalledActionResult(n))return;n.wait?.stackModels.forEach(r=>r.collectCallFrames(e));let i=n.node?.action;i&&i.type===Fa&&e.push(i)};t(this.waitingAction??void 0);for(let n=this.stack.size()-1;n>=0;n--)t(this.stack.get(n))}reset(){this.stack.forEach(e=>{o.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):S.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear(),this.loopConfig=null,this.loopBodyActions=[],this.loopCondition=null,this.loopStartTime=0,this.loopDebugCheckpoint=0}deserialize(e,t){this.reset();let n=e.items;for(let i of n){if(this.topIsGroupStillRunning()){this.liveGame.getGameStateForce?.().logger?.debug("StackModel","Dropping an item restored above a running group",i.action);break}if(i.type==="action"){if(!i.action)continue;let{actionType:r,action:s}=i,a=t.get(s);if(!a)throw new Error(`Action not found: ${s}`);this.stack.push({type:r,node:a.contentNode,wait:null})}else if(i.type==="link"){let{actionType:r,action:s,stacks:a,stackWaitType:c}=i;if(c==null)throw new Error(`Missing stackWaitType for link action: ${s}`);this.stack.push({type:r,node:s?t.get(s)?.contentNode??null:null,wait:{type:c,stackModels:a.map(l=>o.createStackModel(this.liveGame,l,t))}})}}if(e.loop){let i=e.loop,r=[];for(let a of i.bodyActionIds){let c=t.get(a);if(!c)throw new Error(`Loop body action not found: ${a}`);r.push(c)}let s=null;if(i.type==="condition"&&i.conditionActionId){let a=t.get(i.conditionActionId);if(a){let c=a.contentNode.getContent();Array.isArray(c)&&c.length>=2&&Q.isLambda(c[1])&&(s=c[1])}}this.loopConfig={type:i.type,counter:i.counter,limit:i.limit,conditionActionId:i.conditionActionId,bodyActionIds:i.bodyActionIds,broken:i.broken},this.loopBodyActions=r,this.loopCondition=s,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=i.counter}return this}isEmpty(){return this.stack.isEmpty()}topIsGroupStillRunning(){let e=this.stack.peek();return o.isCalledActionResult(e)&&!!e.wait&&o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels)}clearAboveCallFrame(){for(let e=this.stack.size()-1;e>=0;e--){let t=this.stack.get(e);if(o.isCalledActionResult(t)&&t.node?.action?.type===Fa){for(;this.stack.size()>e+1;){let n=this.stack.pop();S.isAwaitable(n)?n.abort():o.isCalledActionResult(n)&&n.wait?.stackModels.forEach(i=>i.reset())}return this.waitingAction=null,this}}return this.reset(),this}push(...e){return this.stack.push(...e),this}};var Ie=class Ie{constructor(e){this.events=new _;this.story=null;this.gameLock=new Ln;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.elementAuditCountdown=0;this.lastDialog=null;this.mapCache=null;this._currentActionId=null;this.game=e,this._storable=new Zn,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new Ht(Ie.GameSpacesKey.game,Ie.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.story;if(!e)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");return{name:this.currentSavedGame.name,meta:{version:Ga,created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:e.hash()},game:{...this.serializeGameState(),history:this.gameState.gameHistory.serialize()}}}serializeGameState(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");let n=this._storable.toData(),i=e.toData(),r=t.getAllElementStates();this.auditElementDirtyMarks(t);let s=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(c=>c.serialize());return{store:n,stage:i,elementStates:r,stackModel:s,asyncStackModels:a,services:t.serializeServices()}}auditElementDirtyMarks(e){if(!this.game.config.app.debug||this.elementAuditCountdown-- >0)return;this.elementAuditCountdown=Ie.ElementAuditInterval;let t=e.findUnmarkedElements();t.length&&(t.forEach(n=>n.markDirty()),this.gameState?.logger.warn("LiveGame.auditElementDirtyMarks",`${t.length} element(s) had state that no longer matches the script but were never marked dirty, so the save just written left them out. They have been marked, so the next save will carry them - but something is writing element state outside the action dispatch: ${t.map(n=>n.getId()).join(", ")}`))}captureGameState(){try{return this.serializeGameState()}catch(e){return this.gameState?.logger.warn("LiveGame.captureGameState",e),null}}deserialize(e){if(!e)throw new Error("No saved game provided when trying to deserialize game state");this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");this.game.hooks.trigger("beforeRestore",[]),t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:i,stage:r,elementStates:s,services:a,stackModel:c,asyncStackModels:l}}=e,[u,d]=this.constructMaps();this.initNamespaces(),this._storable.load(i),d.forEach(p=>p.reset()),s.forEach(({id:p,data:h})=>{t.logger.debug("restore element",p);let g=d.get(p);if(!g)throw new Error("Element not found, id: "+p+`
|
|
46
46
|
NarraLeaf cannot find the element with the id from the saved game`);g instanceof Ye?g.fromData(h,d):g.fromData(h),g.markDirty()}),d.forEach(p=>{p instanceof Ke&&p._rebindLoop(u)}),this.currentSavedGame=e,t.loadData(r,d),this.stackModel.deserialize(c,u),l.forEach(p=>{let h=Xe.createStackModel(this,p,u);this.asyncStackModels.add(h),t.timelines.attachTimeline(this.executeAsyncStackModel(h))}),n.deserializeServices(a),t.gameHistory.load(e.game.history??[],u),this.game.hooks.trigger("afterRestore",[]),t.events.once(L.EventTypes["event:state.onRender"],()=>{t.schedule(()=>{t.rollLock.unlock(),t.stage.next()},0)}),t.stage.forceUpdate()}getHistory(){return this.assertGameState(),this.gameState.gameHistory.getHistory()}getFuture(){return this.assertGameState(),this.gameState.gameHistory.getFuture()}canUndo(){return this.assertGameState(),this.gameState.gameHistory.canUndo()}canRedo(){return this.assertGameState(),this.gameState.gameHistory.canRedo()}undo(){this.assertGameState();let e=this.gameState.gameHistory;return e.canUndo()?this.restoreToIndex(e.getCursor()-1,"LiveGame.undo"):(this.gameState.logger.warn("LiveGame.undo","No line to step back to"),!1)}redo(){this.assertGameState();let e=this.gameState.gameHistory;return e.canRedo()?this.restoreToIndex(e.getCursor()+1,"LiveGame.redo"):(this.gameState.logger.warn("LiveGame.redo","No line to step forward to"),!1)}restoreToHistory(e){this.assertGameState();let t=this.gameState.gameHistory.indexOfToken(e);return t<0?(this.gameState.logger.warn("LiveGame.restoreToHistory","No history entry for token",e),!1):this.restoreToIndex(t,"LiveGame.restoreToHistory")}restoreToIndex(e,t){this.assertGameState();let n=this.gameState.gameHistory,i=n.getAt(e);if(!i)return this.gameState.logger.warn(t,"No history entry at",e),!1;if(e<n.getCursor()&&this.gameState.actionHistory.has(i.token)){let a=n.getCursor();if(n.setCursor(e),this.undoInPlace(i,t))return this.auditRestoredLine(i,t),!0;n.setCursor(a)}if(!i.snapshot)return this.gameState.logger.warn(t,"History entry has no restore snapshot",i.token),!1;let r=i.token,s={name:this.currentSavedGame?.name??"",meta:this.currentSavedGame?.meta??this.getNewSavedGame().meta,game:{...i.snapshot,history:n.serializeAll()}};return this.deserialize(s),this.gameState.gameHistory.setCursor(this.gameState.gameHistory.indexOfToken(r)),i.action.type===Yt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),!0}undoInPlace(e,t){this.assertGameState();let n=this.gameState.actionHistory;if(!n.has(e.token))return!1;let i=this.gameLock.register().lock();this.stackModel.abortStackTop();let r=n.undoUntil(e.token);if(!r)return this.gameLock.off(i.unlock()),!1;let[s]=this.constructMaps(),{rootStackSnapshot:a,stackModel:c}=r;return r.action.type===Yt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),this.stackModel.deserialize(a,s),c===this.stackModel&&this.stackModel.push(Xe.fromAction(r.action)),this.gameLock.off(i.unlock()),this.gameState.logger.debug(t,"Stepped back in place to",e.token),this.gameState.stage.forceUpdate(),this.gameState.stage.next(),this.gameState.schedule(()=>{this.gameState&&this.gameState.forceAnimation()},0),!0}auditRestoredLine(e,t){if(!this.game.config.app.debug||!e.snapshot)return;let n=JSON.stringify([...e.snapshot.elementStates].sort((r,s)=>r.id.localeCompare(s.id))),i=JSON.stringify([...this.serializeGameState().elementStates].sort((r,s)=>r.id.localeCompare(s.id)));n!==i&&this.gameState?.logger.warn(t,`Stepping back in place did not reproduce the state this line's snapshot describes, so an action's undo does not fully reverse it. Restoring the snapshot would have been correct; this path was not.
|
|
47
47
|
expected: ${n}
|
|
48
|
-
actual: ${i}`)}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=S.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new fe({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(L.EventTypes["event:state.player.skip"],!0)}async fastForward(e={}){this.assertGameState();let t=this.gameState,n=e.until??"menu",i=typeof n=="object"?n.actionId:null,r=n==="menu"||i!==null,s=e.maxSteps??t.game.config.maxStackModelLoop,a=e.stepTimeout??Ie.FastForwardStepTimeout,c=i!==null?{reachedTarget:!1}:{},l=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let u=0;for(;u++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...c};if(this.stackModel.isEmpty())return{reason:"end",...c};let d=this.stackModel.getWaitingAwaitable();if(d){if(!await Ie.settleSuspendedStep(t,d,a))return{reason:"stalled",...c}}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...c}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(l)}}static settleSuspendedStep(e,t,n){return new Promise(i=>{let r=!1,s=null,a,c=d=>{r||(r=!0,s!==null&&(clearTimeout(s),s=null),a?.cancel?.(),i(d))};if(a=t.onSettled(()=>c(!0)),r){a?.cancel?.();return}let l=Date.now()+n,u=()=>{if(!r&&(e.events.emit(L.EventTypes["event:state.player.skip"],!0),!r)){if(Date.now()>=l){c(!1);return}s=setTimeout(u,Ie.FastForwardSkipInterval)}};u()})}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(Ie.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(Ie.EventTypes["event:menu.choose"],e)}onCurrentActionChange(e){return this.events.on(Ie.EventTypes["event:action.current"],e)}getCurrentActionId(){return this._currentActionId}getStackSnapshot(){return this.stackModel?{root:this.stackModel.snapshot(),async:Array.from(this.asyncStackModels).map(e=>e.snapshot())}:{root:{frames:[]},async:[]}}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(Xe.fromAction(i)):e.logger.warn("No scene root found");let r=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return r?r.forEach(s=>{e.logger.debug("reset element",s),s.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],i=>{t.set(i.getId(),i),n.set(i.callee.getId(),i.callee);for(let r of Ye.getOwnedSounds(i)){let s=r.getId();s&&n.set(s,r)}},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let i=this.gameState.playerCurrent;return i?(i.addEventListener(e,t,n),{cancel:()=>i.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new Xe(this);return this.asyncStackModels.add(t),t.push(...e),t}executeAsyncStackModel(e){this.assertGameState();let t=e.execute();return t.onFailed(n=>{this.gameState.logger.error("Async StackModel",n)}),t.onSettled(()=>{this.asyncStackModels.delete(e)}),t}createStackModel(e){let t=new Xe(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");this._currentActionId=t.getId(),this.events.hasListeners(Ie.EventTypes["event:action.current"])&&this.events.emit(Ie.EventTypes["event:action.current"],{actionId:t.getId(),actionType:t.type}),t.callee?.markDirty();let i=t.executeAction(e,n);return S.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new Ae("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Xe(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new Ae("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let i=t?.contentNode||null,r=[],s=[],a=new Set;for(;(i||s.length)&&!(n&&r.length>=n);){if(i||(i=s.pop().contentNode),[Ot].some(c=>i?.action&&i.action instanceof c)){i=null;continue}if(i.action&&i.action.is(ee,z.jumpTo)){let[c]=i.action.contentNode.getContent(),l=e.getScene(c);if(!l)throw i.action._sceneNotFoundError(i.action.getSceneName(c));if(a.has(l)){i=null;continue}a.add(l),i=l.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(se,re.do)){let[c]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=c[0]?.contentNode||null}i?.action&&r.push(i.action),i=i?.getChild()||null}return r}clearMainStack(){if(!this.stackModel)throw new Ae("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new Ae("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:oa(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:{items:[]},asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new E("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new E("Player Element Not Mounted")}};Ie.DefaultNamespaces={game:{}},Ie.GameSpacesKey={game:"game"},Ie.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose","event:action.current":"event:action.current"},Ie.ElementAuditInterval=50,Ie.FastForwardStepTimeout=1e4,Ie.FastForwardSkipInterval=16;var Ut=Ie;var di=class di{constructor(e){this.events=new _;this.settings={...e},this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(di.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(di.EventTypes["event:game.preference.change"],(n,i)=>{typeof e=="string"?e===n&&t&&t(i):e(n,i)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};di.EventTypes={"event:game.preference.change":"event:game.preference.change"};var mi=di;import"client-only";import Vc,{useEffect as ed}from"react";import"client-only";import Ha,{useContext as Va,useState as eu}from"react";var Pr=Ha.createContext(null);function Ua({children:o,game:e}){"use client";let t=new te({}),[n]=eu(e||t);return Ha.createElement(Pr,{value:n},o)}function M(){let o=Va(Pr);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function Wa(){return Va(Pr)}import tu,{createContext as nu,useContext as Ba}from"react";var za="/",vo=class vo{constructor(e,t=vo.rootPath){this.events=new _;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,c]=s.split("=");a&&(i[decodeURIComponent(a)]=c?decodeURIComponent(c):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let c=a.slice(1);n[c]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new E(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new E(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),i=t.split("/"),r=[];r.push(...n);for(let s=0;s<i.length;s++){let a=i[s];a===""||a==="."||(a===".."?r.length>0&&r.pop():r.push(a))}return this.buildPath(r)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),s=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(s)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),ct(()=>{t()}))})}else ct(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};vo.rootPath=za;var dn=vo,Er=nu(null);function Ka({children:o}){let e=M();return tu.createElement(Er,{value:{router:e.router}},o)}function Wt(){if(!Ba(Er))throw new Error("useRouter must be used within a RouterProvider");return Ba(Er).router}import ja from"react";import lu from"clsx";import iu,{createContext as ou,useContext as ru,useLayoutEffect as su,useReducer as au,useState as cu}from"react";var Zt=class Zt{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new _().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(Zt.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(Zt.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(Zt.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(Zt.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(Zt.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(Zt.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};Zt.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var Dr=Zt,Lr=ou(null);function $a({children:o}){"use client";let[e]=cu(()=>new Dr);return iu.createElement(Lr,{value:{ratio:e}},o)}function he(){let o=ru(Lr),[,e]=au(n=>n+1,0);if(!Lr||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return su(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function Bt({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=he(),s=r.getStyle();return ja.createElement("div",{className:lu("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},ja.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import uu,{useEffect as pu}from"react";function mn(o){let e=M(),[t,n]=uu.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return pu(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import Rr from"react";import So from"react";import qa from"clsx";function To({children:o,className:e,style:t,...n}){let{ratio:i}=he(),r=M();return So.createElement(Bt,{className:qa("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${i.state.scale})`,transformOrigin:"left top",width:r.config.width,height:r.config.height,pointerEvents:"none"},"data-element-type":"full",...n},So.createElement("div",{className:"absolute inset-0 w-full h-full"},So.createElement("div",{className:"inset-0 w-full h-full"},So.createElement("div",{className:qa("pointer-events-auto-rest",e),style:t},o))))}function du({children:o,className:e,style:t}){return Rr.createElement(Rr.Fragment,null,Rr.createElement(To,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import Ya from"clsx";import Xa from"react";function bo({className:o,children:e,...t}){let{ratio:n}=he();return Xa.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:Ya("w-full h-full")},Xa.createElement("div",{className:Ya("z-20",o),...t},e))}import Ct,{useState as Qa}from"react";import{motion as mu}from"motion/react";function Ao({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let c=M(),[l,u]=Qa(!1);if(!c.config.app.inspector)return Ct.createElement(r,{...a,ref:s},o);let d={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return Ct.createElement(r,{...d,ref:s},n&&l&&Ct.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function fu({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=M(),[a,c]=Qa(!1);if(!s.config.app.inspector)return Ct.createElement(i,{...r});let l={...r,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return Ct.createElement("div",null,Ct.createElement(i,{...l}),t&&a&&Ct.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function hu(o){return Ct.createElement(Ao,{...o,as:"div"})}function gu(o){return Ct.createElement(Ao,{...o,as:"span"})}function yu(o){return Ct.createElement(fu,{...o,as:"img"})}function vu(o){return Ct.createElement(Ao,{...o,as:"button"})}function Su(o){return Ct.createElement(Ao,{...o,as:mu.div,ref:o.ref,layout:o.layout})}var Tu={Div:hu,Span:gu,Button:vu,Img:yu,mDiv:Su},zt=Tu;import Eo from"clsx";import Ve,{useEffect as kn,useMemo as Uu,useRef as hc,useState as Br}from"react";import{useEffect as bu,useState as Au}from"react";function ae(o){let[e,t]=Au(0);bu(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import _a from"react";var xn=_a.createContext(null);function It(){let o=_a.useContext(xn);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}function Ir({active:o,forced:e}){return o?e?"forceSkip":"requestComplete":"ignore"}function Ja(o,e){let t=Ir(e);return t==="forceSkip"?(o.setIdle(!0),o.forceSkip()):t==="requestComplete"&&o.requestComplete(),t}import Co,{useCallback as Cu,useLayoutEffect as fi,useMemo as Za,useRef as ec}from"react";import{useIsPresent as xu}from"motion/react";var Mt=class Mt{constructor(e){this.events=new _;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.voiceWaitDisposer=null;this.config=e,this._state="pending",this.autoForwardScheduler=new Hi,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}isActive(){return this._active}setActive(e){return this._active=e,e?this.state==="ended"&&(this._idle=!0):this.cancelAutoForward(),this}requestComplete(){this._active&&(this.state==="ended"?this.safeEmit(Mt.Events.complete):this.safeEmit(Mt.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Mt.Events.forceSkip)))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(Mt.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",this.config.gameState.completeAdvDialogTyping(this.config.action.id),e.getPreference(te.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(Mt.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.releaseVoiceWait(),this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(Mt.Events.onFlush),this}onFlush(e){return this.events.on(Mt.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;if(!this._active||!e.getPreference(te.Preferences.autoForward)||this.state!=="ended")return;this.releaseVoiceWait();let t=this.getPlayingVoiceToken();if(!t){this.scheduleAutoForwardDelay();return}let n=()=>{this.releaseVoiceWait(),this.scheduleAutoForwardDelay()};t.once("ended",n),t.once("stop",n),this.voiceWaitDisposer=()=>{t.off("ended",n),t.off("stop",n)}}scheduleAutoForwardDelay(){let e=this.config.gameState.game.preference;!this._active||!e.getPreference(te.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(Mt.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(te.Preferences.gameSpeed))}getPlayingVoiceToken(){let e=this.config.action.sentence;if(!e)return null;try{let t=it.getVoice(this.config.gameState,e);if(!t)return null;let n=this.config.gameState.audioManager.getToken(t);return n&&n.isPlaying()?n:null}catch{return null}}releaseVoiceWait(){let e=this.voiceWaitDisposer;this.voiceWaitDisposer=null,e?.()}};Mt.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Me=Mt;function hi({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=xu(),s=i&&r,a=ec(!1),c=ec(o),l=c.current!==o,u=Za(()=>o.sentence?.evaluate(xe.getCtx({gameState:n})),[o.sentence,n]),d=Za(()=>new Me({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:l}),[o,n]),p=n.game.config.dialog,h=Cu(g=>{!s||a.current||(a.current=!0,e?.(g))},[s,e]);return fi(()=>{a.current=!1},[d]),fi(()=>{c.current=o},[o]),fi(()=>(d.setActive(s),()=>{d.setActive(!1)}),[d,s]),fi(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",d),d.events.on(Me.Events.complete,g=>{n.logger.log("NarraLeaf-React: Say","Complete",d.isIdle()),s&&(d.isIdle()||g?h(!1):d.setIdle(!0))}).cancel),[d,h,n,s]),fi(()=>{let g=T=>{Ja(d,{active:s,forced:T===!0})},m=n.events.on(L.EventTypes["event:state.player.skip"],g),y=n.events.on(L.EventTypes["event:state.player.stageClick"],()=>g(!1));return()=>{m.cancel(),y.cancel()}},[d,n,s]),Co.createElement(Co.Fragment,null,Co.createElement(xn,{value:d},Co.createElement(p,null)))}import{useCallback as Pu,useEffect as xo,useState as Eu}from"react";function tc(o,e,{dialogId:t,active:n,forced:i}){let r=Ir({active:n,forced:i});return r==="ignore"?"ignore":o.requestNvlAdvance(t)!=="typing"?"pageHandled":r==="forceSkip"?(e.forceSkip(),"forceSkip"):(e.requestComplete(),"requestComplete")}import{useEffect as wu,useState as ku}from"react";function wn(o){let e=M(),[t,n]=ku(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return wu(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var Bn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Bn||{});function wo({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=M(),[s]=wn("nextAction"),[a]=Eu(()=>{let l=o.firedTextEvents??(o.firedTextEvents=new Set);return new Me({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e,firedTextEvents:l})}),c=Pu(l=>{tc(e,a,{dialogId:o.id,active:n,forced:l})},[a,o.id,e,n]);return xo(()=>{if(!n)return;let l=e.events.on(L.EventTypes["event:state.player.stageClick"],()=>c(!1)),u=e.events.on(L.EventTypes["event:state.player.skip"],d=>c(d===!0));return()=>{l.cancel(),u.cancel()}},[c,e,n]),xo(()=>{if(!n)return;let l=d=>{d.repeat||r.keyMap.match("nextAction",d.key)&&c(!1)};if(r.config.useWindowListener){let d=r.getLiveGame().onWindowEvent("keydown",l);return()=>{d.cancel()}}let u=r.getLiveGame().onPlayerEvent("keydown",l);return()=>{u.cancel()}},[c,r,n,s]),xo(()=>{let l=a.events.on(Me.Events.complete,u=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!u&&a.setIdle(!0))});return()=>{l.cancel()}},[a,o.id,e,n]),xo(()=>{let l=a.events.on(Me.Events.simulateClick,()=>c(!1));return()=>{l.cancel()}},[c,a]),a}function Du(o,e){let{expression:t,sound:n}=o.config;if(t){let{image:i,appearance:r}=t;i._setAppearanceSync(r),e.stage.update();let s=e.getExposedState(i);s&&(F.isLayeredSrc(i)?s.flush():s.updateStyleSync())}n&&e.audioManager.play(n,{end:n.state.volume,duration:0})}function ko(o,e,t){e.has(o)||(e.add(o),Du(o,t))}function nc(o,e,t){let n=[];for(let i of o)if(i.isTextEvent()){let r=i.text;e.has(r)||n.push(r),ko(r,e,t)}return n}var zn=new Map,Mr=new Set;function Lu(o,e){return zn.set(o,e),Mr.delete(o),()=>{zn.get(o)===e&&zn.delete(o)}}function Ru(o){zn.delete(o)}function Iu(o){return zn.get(o)??null}function Nr(o){if(!o)return null;if(typeof o!="string")return o;let e=zn.get(o);return e||(Mr.has(o)||(Mr.add(o),console.warn(`NarraLeaf-React: no word renderer is registered as "${o}"; the word is rendered as plain text. Call registerWordRenderer before the line plays.`)),null)}import{useCallback as Mu,useLayoutEffect as ic,useRef as Gr,useState as Nu}from"react";var oc=.5,Gu=.005,Fu=12,rc=.05,ac=12,Po="--nl-text-scale",cc=`var(${Po}, 1)`;function gi(o){return o==null||o===""?void 0:`calc(${typeof o=="number"?`${o}px`:String(o)} * ${cc})`}function lc(){return`calc(1em * ${cc})`}function sc(o,e){let t=getComputedStyle(o);return e?o.clientWidth-parseFloat(t.paddingLeft||"0")-parseFloat(t.paddingRight||"0"):o.clientHeight-parseFloat(t.paddingTop||"0")-parseFloat(t.paddingBottom||"0")}function uc({enabled:o,minFontSize:e,vertical:t,revealed:n}){let i=Gr(null),[r,s]=Nu(1),a=Gr(1),c=Gr(0);a.current=r;let l=Mu(u=>{let d=i.current,p=d?.parentElement;if(!d||!p)return;let h=sc(p,t);if(!Number.isFinite(h)||h<=0)return;c.current=h;let g=()=>t?d.offsetWidth:d.offsetHeight,m=A=>{d.style.setProperty(Po,String(A))},y=A=>(m(A),g()<=h+oc);if(y(u)){u!==a.current&&s(u);return}m(1);let T=parseFloat(getComputedStyle(d).fontSize)||0,f=T>0?Math.min(1,Math.max(rc,e/T)):rc,v;if(f>=u||!y(f))v=f;else{let A=f,w=u;for(let k=0;k<Fu&&w-A>Gu;k++){let b=(A+w)/2;y(b)?A=b:w=b}v=A}m(v),s(v)},[e,t]);return ic(()=>{if(!o){a.current!==1&&s(1);return}l(a.current)},[o,l,n]),ic(()=>{let u=i.current?.parentElement;if(!o||!u||typeof ResizeObserver>"u")return;let d=new ResizeObserver(()=>{Math.abs(sc(u,t)-c.current)>oc&&l(1)});d.observe(u);let p=!1;return document.fonts?.ready.then(()=>{p||l(a.current)}),()=>{p=!0,d.disconnect()}},[o,l,t]),{containerRef:i,scale:r}}function pc(o,e){return o.fontSize!==void 0?gi(o.fontSize):o.fontScale!==void 0?mc(o.fontScale):gi(e)}function dc(o,e){return o.fontSize!==void 0?o.fontSize:o.fontScale!==void 0?mc(o.fontScale):e}function mc(o){return`${o}em`}function Fr(o){return o?{textEmphasis:`${o.fill??"filled"} ${o.mark??"dot"}`,textEmphasisPosition:`${o.position??"over"} right`}:{}}import Or from"react";var Ou=2;function yi(o){return o==="vertical-rl"||o==="vertical-lr"}function Hu(o){return o===!1?0:typeof o=="number"?Number.isFinite(o)?Math.max(0,Math.round(o)):0:Ou}function Vr(o,e){return yi(o)?{writingMode:o,textOrientation:e??"mixed"}:o?{writingMode:o}:{}}var Hr=/[0-9A-Za-z]+(?:[.:\-/][0-9A-Za-z]+)*/g;function Vu(o,e){if(e<=0)return[{text:o,combineUpright:!1}];let t=[],n=0;Hr.lastIndex=0;for(let i=Hr.exec(o);i;i=Hr.exec(o))i[0].length>e||(i.index>n&&t.push({text:o.slice(n,i.index),combineUpright:!1}),t.push({text:i[0],combineUpright:!0}),n=i.index+i[0].length);return(n<o.length||t.length===0)&&t.push({text:o.slice(n),combineUpright:!1}),t}function Ur(){return{wordBreak:"normal",lineBreak:"strict",overflowWrap:"break-word"}}function Wr(o,e,t){if(!e)return o;let n=Hu(t);if(n<=0)return o;let i=Vu(o,n);return i.some(r=>r.combineUpright)?i.map((r,s)=>r.combineUpright?Or.createElement("span",{key:s,style:{textCombineUpright:"all"}},r.text):Or.createElement(Or.Fragment,{key:s},r.text)):o}function*Kr(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if(ze.isPause(n.text)){yield ze.from(n.text);continue}if(ut.isTextEvent(n.text)){yield n.text;continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
|
|
48
|
+
actual: ${i}`)}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=S.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new fe({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(L.EventTypes["event:state.player.skip"],!0)}async fastForward(e={}){this.assertGameState();let t=this.gameState,n=e.until??"menu",i=typeof n=="object"?n.actionId:null,r=n==="menu"||i!==null,s=e.maxSteps??t.game.config.maxStackModelLoop,a=e.stepTimeout??Ie.FastForwardStepTimeout,c=i!==null?{reachedTarget:!1}:{},l=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let u=0;for(;u++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...c};if(this.stackModel.isEmpty())return{reason:"end",...c};let d=this.stackModel.getWaitingAwaitable();if(d){if(!await Ie.settleSuspendedStep(t,d,a))return{reason:"stalled",...c}}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...c}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(l)}}static settleSuspendedStep(e,t,n){return new Promise(i=>{let r=!1,s=null,a,c=d=>{r||(r=!0,s!==null&&(clearTimeout(s),s=null),a?.cancel?.(),i(d))};if(a=t.onSettled(()=>c(!0)),r){a?.cancel?.();return}let l=Date.now()+n,u=()=>{if(!r&&(e.events.emit(L.EventTypes["event:state.player.skip"],!0),!r)){if(Date.now()>=l){c(!1);return}s=setTimeout(u,Ie.FastForwardSkipInterval)}};u()})}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(Ie.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(Ie.EventTypes["event:menu.choose"],e)}onCurrentActionChange(e){return this.events.on(Ie.EventTypes["event:action.current"],e)}getCurrentActionId(){return this._currentActionId}getStackSnapshot(){return this.stackModel?{root:this.stackModel.snapshot(),async:Array.from(this.asyncStackModels).map(e=>e.snapshot())}:{root:{frames:[]},async:[]}}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(Xe.fromAction(i)):e.logger.warn("No scene root found");let r=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return r?r.forEach(s=>{e.logger.debug("reset element",s),s.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],i=>{t.set(i.getId(),i),n.set(i.callee.getId(),i.callee);for(let r of Ye.getOwnedSounds(i)){let s=r.getId();s&&n.set(s,r)}},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let i=this.gameState.playerCurrent;return i?(i.addEventListener(e,t,n),{cancel:()=>i.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new Xe(this);return this.asyncStackModels.add(t),t.push(...e),t}executeAsyncStackModel(e){this.assertGameState();let t=e.execute();return t.onFailed(n=>{this.gameState.logger.error("Async StackModel",n)}),t.onSettled(()=>{this.asyncStackModels.delete(e)}),t}createStackModel(e){let t=new Xe(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");this._currentActionId=t.getId(),this.events.hasListeners(Ie.EventTypes["event:action.current"])&&this.events.emit(Ie.EventTypes["event:action.current"],{actionId:t.getId(),actionType:t.type}),t.callee?.markDirty();let i=t.executeAction(e,n);return S.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new Ae("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Xe(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new Ae("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let i=t?.contentNode||null,r=[],s=[],a=new Set;for(;(i||s.length)&&!(n&&r.length>=n);){if(i||(i=s.pop().contentNode),[Ot].some(c=>i?.action&&i.action instanceof c)){i=null;continue}if(i.action&&i.action.is(ee,z.jumpTo)){let[c]=i.action.contentNode.getContent(),l=e.getScene(c);if(!l)throw i.action._sceneNotFoundError(i.action.getSceneName(c));if(a.has(l)){i=null;continue}a.add(l),i=l.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(se,re.do)){let[c]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=c[0]?.contentNode||null}i?.action&&r.push(i.action),i=i?.getChild()||null}return r}clearMainStack(){if(!this.stackModel)throw new Ae("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new Ae("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:oa(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:{items:[]},asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new E("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new E("Player Element Not Mounted")}};Ie.DefaultNamespaces={game:{}},Ie.GameSpacesKey={game:"game"},Ie.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose","event:action.current":"event:action.current"},Ie.ElementAuditInterval=50,Ie.FastForwardStepTimeout=1e4,Ie.FastForwardSkipInterval=16;var Ut=Ie;var di=class di{constructor(e){this.events=new _;this.settings={...e},this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(di.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(di.EventTypes["event:game.preference.change"],(n,i)=>{typeof e=="string"?e===n&&t&&t(i):e(n,i)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};di.EventTypes={"event:game.preference.change":"event:game.preference.change"};var mi=di;import"client-only";import Vc,{useEffect as td}from"react";import"client-only";import Ha,{useContext as Va,useState as tu}from"react";var Pr=Ha.createContext(null);function Ua({children:o,game:e}){"use client";let t=new te({}),[n]=tu(e||t);return Ha.createElement(Pr,{value:n},o)}function M(){let o=Va(Pr);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function Wa(){return Va(Pr)}import nu,{createContext as iu,useContext as Ba}from"react";var za="/",vo=class vo{constructor(e,t=vo.rootPath){this.events=new _;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,c]=s.split("=");a&&(i[decodeURIComponent(a)]=c?decodeURIComponent(c):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let c=a.slice(1);n[c]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new E(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new E(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),i=t.split("/"),r=[];r.push(...n);for(let s=0;s<i.length;s++){let a=i[s];a===""||a==="."||(a===".."?r.length>0&&r.pop():r.push(a))}return this.buildPath(r)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),s=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(s)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),ct(()=>{t()}))})}else ct(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};vo.rootPath=za;var dn=vo,Er=iu(null);function Ka({children:o}){let e=M();return nu.createElement(Er,{value:{router:e.router}},o)}function Wt(){if(!Ba(Er))throw new Error("useRouter must be used within a RouterProvider");return Ba(Er).router}import ja from"react";import uu from"clsx";import ou,{createContext as ru,useContext as su,useLayoutEffect as au,useReducer as cu,useState as lu}from"react";var Zt=class Zt{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new _().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(Zt.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(Zt.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(Zt.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(Zt.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(Zt.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(Zt.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};Zt.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var Dr=Zt,Lr=ru(null);function $a({children:o}){"use client";let[e]=lu(()=>new Dr);return ou.createElement(Lr,{value:{ratio:e}},o)}function he(){let o=su(Lr),[,e]=cu(n=>n+1,0);if(!Lr||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return au(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function Bt({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=he(),s=r.getStyle();return ja.createElement("div",{className:uu("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},ja.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import pu,{useEffect as du}from"react";function mn(o){let e=M(),[t,n]=pu.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return du(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import Rr from"react";import So from"react";import qa from"clsx";function To({children:o,className:e,style:t,...n}){let{ratio:i}=he(),r=M();return So.createElement(Bt,{className:qa("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${i.state.scale})`,transformOrigin:"left top",width:r.config.width,height:r.config.height,pointerEvents:"none"},"data-element-type":"full",...n},So.createElement("div",{className:"absolute inset-0 w-full h-full"},So.createElement("div",{className:"inset-0 w-full h-full"},So.createElement("div",{className:qa("pointer-events-auto-rest",e),style:t},o))))}function mu({children:o,className:e,style:t}){return Rr.createElement(Rr.Fragment,null,Rr.createElement(To,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import Ya from"clsx";import Xa from"react";function bo({className:o,children:e,...t}){let{ratio:n}=he();return Xa.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:Ya("w-full h-full")},Xa.createElement("div",{className:Ya("z-20",o),...t},e))}import Ct,{useState as Qa}from"react";import{motion as fu}from"motion/react";function Ao({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let c=M(),[l,u]=Qa(!1);if(!c.config.app.inspector)return Ct.createElement(r,{...a,ref:s},o);let d={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return Ct.createElement(r,{...d,ref:s},n&&l&&Ct.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function hu({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=M(),[a,c]=Qa(!1);if(!s.config.app.inspector)return Ct.createElement(i,{...r});let l={...r,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return Ct.createElement("div",null,Ct.createElement(i,{...l}),t&&a&&Ct.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function gu(o){return Ct.createElement(Ao,{...o,as:"div"})}function yu(o){return Ct.createElement(Ao,{...o,as:"span"})}function vu(o){return Ct.createElement(hu,{...o,as:"img"})}function Su(o){return Ct.createElement(Ao,{...o,as:"button"})}function Tu(o){return Ct.createElement(Ao,{...o,as:fu.div,ref:o.ref,layout:o.layout})}var bu={Div:gu,Span:yu,Button:Su,Img:vu,mDiv:Tu},zt=bu;import Eo from"clsx";import Ve,{useEffect as kn,useMemo as Wu,useRef as hc,useState as Br}from"react";import{useEffect as Au,useState as Cu}from"react";function ae(o){let[e,t]=Cu(0);Au(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import _a from"react";var xn=_a.createContext(null);function It(){let o=_a.useContext(xn);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}function Ir({active:o,forced:e}){return o?e?"forceSkip":"requestComplete":"ignore"}function Ja(o,e){let t=Ir(e);return t==="forceSkip"?(o.setIdle(!0),o.forceSkip()):t==="requestComplete"&&o.requestComplete(),t}import Co,{useCallback as xu,useLayoutEffect as fi,useMemo as Za,useRef as ec}from"react";import{useIsPresent as wu}from"motion/react";var Mt=class Mt{constructor(e){this.events=new _;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.voiceWaitDisposer=null;this.config=e,this._state="pending",this.autoForwardScheduler=new Hi,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}isActive(){return this._active}setActive(e){return this._active=e,e?this.state==="ended"&&(this._idle=!0):this.cancelAutoForward(),this}requestComplete(){this._active&&(this.state==="ended"?this.safeEmit(Mt.Events.complete):this.safeEmit(Mt.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Mt.Events.forceSkip)))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(Mt.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",this.config.gameState.completeAdvDialogTyping(this.config.action.id),e.getPreference(te.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(Mt.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.releaseVoiceWait(),this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(Mt.Events.onFlush),this}onFlush(e){return this.events.on(Mt.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;if(!this._active||!e.getPreference(te.Preferences.autoForward)||this.state!=="ended")return;this.releaseVoiceWait();let t=this.getPlayingVoiceToken();if(!t){this.scheduleAutoForwardDelay();return}let n=()=>{this.releaseVoiceWait(),this.scheduleAutoForwardDelay()};t.once("ended",n),t.once("stop",n),this.voiceWaitDisposer=()=>{t.off("ended",n),t.off("stop",n)}}scheduleAutoForwardDelay(){let e=this.config.gameState.game.preference;!this._active||!e.getPreference(te.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(Mt.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(te.Preferences.gameSpeed))}getPlayingVoiceToken(){let e=this.config.action.sentence;if(!e)return null;try{let t=it.getVoice(this.config.gameState,e);if(!t)return null;let n=this.config.gameState.audioManager.getToken(t);return n&&n.isPlaying()?n:null}catch{return null}}releaseVoiceWait(){let e=this.voiceWaitDisposer;this.voiceWaitDisposer=null,e?.()}};Mt.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Me=Mt;function hi({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=wu(),s=i&&r,a=ec(!1),c=ec(o),l=c.current!==o,u=Za(()=>o.sentence?.evaluate(xe.getCtx({gameState:n})),[o.sentence,n]),d=Za(()=>new Me({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:l}),[o,n]),p=n.game.config.dialog,h=xu(g=>{!s||a.current||(a.current=!0,e?.(g))},[s,e]);return fi(()=>{a.current=!1},[d]),fi(()=>{c.current=o},[o]),fi(()=>(d.setActive(s),()=>{d.setActive(!1)}),[d,s]),fi(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",d),d.events.on(Me.Events.complete,g=>{n.logger.log("NarraLeaf-React: Say","Complete",d.isIdle()),s&&(d.isIdle()||g?h(!1):d.setIdle(!0))}).cancel),[d,h,n,s]),fi(()=>{let g=T=>{Ja(d,{active:s,forced:T===!0})},m=n.events.on(L.EventTypes["event:state.player.skip"],g),y=n.events.on(L.EventTypes["event:state.player.stageClick"],()=>g(!1));return()=>{m.cancel(),y.cancel()}},[d,n,s]),Co.createElement(Co.Fragment,null,Co.createElement(xn,{value:d},Co.createElement(p,null)))}import{useCallback as Eu,useEffect as xo,useState as Du}from"react";function tc(o,e,{dialogId:t,active:n,forced:i}){let r=Ir({active:n,forced:i});return r==="ignore"?"ignore":o.requestNvlAdvance(t)!=="typing"?"pageHandled":r==="forceSkip"?(e.forceSkip(),"forceSkip"):(e.requestComplete(),"requestComplete")}import{useEffect as ku,useState as Pu}from"react";function wn(o){let e=M(),[t,n]=Pu(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return ku(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var Bn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Bn||{});function wo({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=M(),[s]=wn("nextAction"),[a]=Du(()=>{let l=o.firedTextEvents??(o.firedTextEvents=new Set);return new Me({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e,firedTextEvents:l})}),c=Eu(l=>{tc(e,a,{dialogId:o.id,active:n,forced:l})},[a,o.id,e,n]);return xo(()=>{if(!n)return;let l=e.events.on(L.EventTypes["event:state.player.stageClick"],()=>c(!1)),u=e.events.on(L.EventTypes["event:state.player.skip"],d=>c(d===!0));return()=>{l.cancel(),u.cancel()}},[c,e,n]),xo(()=>{if(!n)return;let l=d=>{d.repeat||r.keyMap.match("nextAction",d.key)&&c(!1)};if(r.config.useWindowListener){let d=r.getLiveGame().onWindowEvent("keydown",l);return()=>{d.cancel()}}let u=r.getLiveGame().onPlayerEvent("keydown",l);return()=>{u.cancel()}},[c,r,n,s]),xo(()=>{let l=a.events.on(Me.Events.complete,u=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!u&&a.setIdle(!0))});return()=>{l.cancel()}},[a,o.id,e,n]),xo(()=>{let l=a.events.on(Me.Events.simulateClick,()=>c(!1));return()=>{l.cancel()}},[c,a]),a}function Lu(o,e){let{expression:t,sound:n}=o.config;if(t){let{image:i,appearance:r}=t;i._setAppearanceSync(r),e.stage.update();let s=e.getExposedState(i);s&&(F.isLayeredSrc(i)?s.flush():s.updateStyleSync())}n&&e.audioManager.play(n,{end:n.state.volume,duration:0})}function ko(o,e,t){e.has(o)||(e.add(o),Lu(o,t))}function nc(o,e,t){let n=[];for(let i of o)if(i.isTextEvent()){let r=i.text;e.has(r)||n.push(r),ko(r,e,t)}return n}var zn=new Map,Mr=new Set;function Ru(o,e){return zn.set(o,e),Mr.delete(o),()=>{zn.get(o)===e&&zn.delete(o)}}function Iu(o){zn.delete(o)}function Mu(o){return zn.get(o)??null}function Nr(o){if(!o)return null;if(typeof o!="string")return o;let e=zn.get(o);return e||(Mr.has(o)||(Mr.add(o),console.warn(`NarraLeaf-React: no word renderer is registered as "${o}"; the word is rendered as plain text. Call registerWordRenderer before the line plays.`)),null)}import{useCallback as Nu,useLayoutEffect as ic,useRef as Gr,useState as Gu}from"react";var oc=.5,Fu=.005,Ou=12,rc=.05,ac=12,Po="--nl-text-scale",cc=`var(${Po}, 1)`;function gi(o){return o==null||o===""?void 0:`calc(${typeof o=="number"?`${o}px`:String(o)} * ${cc})`}function lc(){return`calc(1em * ${cc})`}function sc(o,e){let t=getComputedStyle(o);return e?o.clientWidth-parseFloat(t.paddingLeft||"0")-parseFloat(t.paddingRight||"0"):o.clientHeight-parseFloat(t.paddingTop||"0")-parseFloat(t.paddingBottom||"0")}function uc({enabled:o,minFontSize:e,vertical:t,revealed:n}){let i=Gr(null),[r,s]=Gu(1),a=Gr(1),c=Gr(0);a.current=r;let l=Nu(u=>{let d=i.current,p=d?.parentElement;if(!d||!p)return;let h=sc(p,t);if(!Number.isFinite(h)||h<=0)return;c.current=h;let g=()=>t?d.offsetWidth:d.offsetHeight,m=A=>{d.style.setProperty(Po,String(A))},y=A=>(m(A),g()<=h+oc);if(y(u)){u!==a.current&&s(u);return}m(1);let T=parseFloat(getComputedStyle(d).fontSize)||0,f=T>0?Math.min(1,Math.max(rc,e/T)):rc,v;if(f>=u||!y(f))v=f;else{let A=f,w=u;for(let k=0;k<Ou&&w-A>Fu;k++){let b=(A+w)/2;y(b)?A=b:w=b}v=A}m(v),s(v)},[e,t]);return ic(()=>{if(!o){a.current!==1&&s(1);return}l(a.current)},[o,l,n]),ic(()=>{let u=i.current?.parentElement;if(!o||!u||typeof ResizeObserver>"u")return;let d=new ResizeObserver(()=>{Math.abs(sc(u,t)-c.current)>oc&&l(1)});d.observe(u);let p=!1;return document.fonts?.ready.then(()=>{p||l(a.current)}),()=>{p=!0,d.disconnect()}},[o,l,t]),{containerRef:i,scale:r}}function pc(o,e){return o.fontSize!==void 0?gi(o.fontSize):o.fontScale!==void 0?mc(o.fontScale):gi(e)}function dc(o,e){return o.fontSize!==void 0?o.fontSize:o.fontScale!==void 0?mc(o.fontScale):e}function mc(o){return`${o}em`}function Fr(o){return o?{textEmphasis:`${o.fill??"filled"} ${o.mark??"dot"}`,textEmphasisPosition:`${o.position??"over"} right`}:{}}import Or from"react";var Hu=2;function yi(o){return o==="vertical-rl"||o==="vertical-lr"}function Vu(o){return o===!1?0:typeof o=="number"?Number.isFinite(o)?Math.max(0,Math.round(o)):0:Hu}function Vr(o,e){return yi(o)?{writingMode:o,textOrientation:e??"mixed"}:o?{writingMode:o}:{}}var Hr=/[0-9A-Za-z]+(?:[.:\-/][0-9A-Za-z]+)*/g;function Uu(o,e){if(e<=0)return[{text:o,combineUpright:!1}];let t=[],n=0;Hr.lastIndex=0;for(let i=Hr.exec(o);i;i=Hr.exec(o))i[0].length>e||(i.index>n&&t.push({text:o.slice(n,i.index),combineUpright:!1}),t.push({text:i[0],combineUpright:!0}),n=i.index+i[0].length);return(n<o.length||t.length===0)&&t.push({text:o.slice(n),combineUpright:!1}),t}function Ur(){return{wordBreak:"normal",lineBreak:"strict",overflowWrap:"break-word"}}function Wr(o,e,t){if(!e)return o;let n=Vu(t);if(n<=0)return o;let i=Uu(o,n);return i.some(r=>r.combineUpright)?i.map((r,s)=>r.combineUpright?Or.createElement("span",{key:s,style:{textCombineUpright:"all"}},r.text):Or.createElement(Or.Fragment,{key:s},r.text)):o}function*Kr(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if(ze.isPause(n.text)){yield ze.from(n.text);continue}if(ut.isTextEvent(n.text)){yield n.text;continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
|
|
49
49
|
`?yield`
|
|
50
50
|
`:yield{text:r,full:n.text,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function zr(o){let e=Kr(o),t=[];for(let n of e){if(ze.isPause(n)||ut.isTextEvent(n))continue;let i=t[t.length-1];if(i&&i!==`
|
|
51
51
|
`&&n!==`
|
|
52
52
|
`&&i.tag===n.tag){t[t.length-1]={...n,text:i.text+n.text,config:n.config};continue}t.push(n)}return t}function gc(o,e){o(t=>{let n=t[t.length-1];return n&&n!==`
|
|
53
53
|
`&&e!==`
|
|
54
|
-
`&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function
|
|
54
|
+
`&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function Bu(o,e,t){return t||(o!==void 0?me.formatStaticWord(o):e?e.text.flatMap(n=>typeof n.text=="function"?[]:new ie(n.text,n.config)):[])}function zu(o,e,t){let n=Math.max(0,e??t);return typeof o=="object"?{enabled:o.enabled??!0,delay:Math.max(0,o.delay??n)}:{enabled:o??!0,delay:n}}function fc(o,e){let t=Math.max(.01,o),n=Math.max(.01,e);return 1e3/(t*n)}function Do(o){return o===void 0?void 0:Rn(o)}function yc(o){return typeof o.tag2=="number"?o.tag2>=o.full.length-1:o.text.length>=o.full.length}function vc({word:o,vertical:e,tateChuYoko:t,done:n,style:i,renderer:r}){let s=o.config.ruby?Ve.createElement("ruby",{className:"align-bottom inline-block"},Ve.createElement("rt",{className:"block text-center"},o.config.ruby),Wr(o.text,e,t)):Wr(o.text,e,t);return r?Ve.createElement(r,{text:o.text,fullText:o.full,revealed:yc(o),done:n,style:i,config:o.config,data:o.config.data},s):s}function Ku(o,e){return!!e&&yc(o)}function $r({defaultColor:o,className:e,style:t,dialog:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,writingMode:c,textOrientation:l,tateChuYoko:u,autoFit:d,autoFitMinFontSize:p,...h}){let g=M(),m=g.getLiveGame().getGameState(),y=hc(null),[T,f]=Br(()=>n&&!n.config.useTypeEffect?zr(n.config.evaluatedWords):[]),[v,A]=ae();if(!n)throw new Error("Dialog state is required");kn(()=>{if(!(!n.config.action.sentence||y.current))return m.logger.info("Initializing the sentence",n,y.current),m.schedule(({onCleanup:B})=>{if(!n.config.useTypeEffect){nc(n.config.evaluatedWords,n.config.firedTextEvents??new Set,m),n.dispatchComplete();return}f([]),y.current=I(),v(),y.current.onComplete(()=>{n.dispatchComplete()}),B(()=>{y.current?.timeline?.abort()})},0)},[]),kn(()=>n.events.depends([n.events.on(Me.Events.requestComplete,()=>{y.current?.interact()}),n.events.on(Me.Events.forceSkip,()=>{n.isEnded()||y.current?.forceSkip()})]).cancel,[n,A]),kn(()=>n.onFlush(()=>{v()}).cancel,[n]),kn(()=>g.preference.events.depends([g.preference.onPreferenceChange(te.Preferences.gameSpeed,()=>{y.current?.update()}),g.preference.onPreferenceChange(te.Preferences.autoForward,()=>{y.current?.update()}),g.preference.onPreferenceChange(te.Preferences.cps,()=>{y.current?.update()})]).cancel,[]);let w=(d??!0)&&!g.config.disableTextScaling,k=Wu(()=>T.reduce((B,Ee)=>B+(Ee===`
|
|
55
55
|
`?1:Ee.text.length),0),[T]),{containerRef:b,scale:x}=uc({enabled:w,minFontSize:p??ac,vertical:yi(c),revealed:k});function I(){let B=new S,Ee=new we(B).setGuard(m.guard),ft=new Set,rt=n.config.firedTextEvents??new Set,Ue=new Set,N=new Set,H=Kr(n.config.evaluatedWords),D=null,K=[],ce=[],G=()=>{K.forEach(We=>We()),K.length=0},ge=()=>{if(ce.length!==0)return{done:!1,value:ce.shift()};let{done:We,value:Je}=H.next();return{done:We,value:Je}},De=We=>{let Je=on=>{We(on),Ue.delete(Je)};return Ue.add(Je),{cancel:()=>{Ue.delete(Je)}}},st=We=>{gc(f,We)},Ge=(We=!1)=>{let Je=!1;for(;!Je;){let{done:on,value:Ze}=ge();if(on){Je=!0;break}if(ze.isPause(Ze)){if(We)continue;Je=!0,ce.push(Ze);break}else ut.isTextEvent(Ze)?ko(Ze,rt,m):Ze===`
|
|
56
|
-
`?f(at=>[...at,Ze]):typeof Ze=="object"&&"text"in Ze&&!ft.has(Ze)&&(ft.add(Ze),st(Ze))}D&&!D.isSettled()?D.abort():(N.forEach(on=>on()),B.resolve())};return m.schedule(async We=>{let Je=!1,on=!1;for(;!Je;){let{done:Ze,value:at}=ge();if(Ze){Je=on=!0;break}if(ut.isTextEvent(at)){ko(at,rt,m);continue}let Ii=new S;if(m.timelines.attachTimeline(Ii),Ii.registerSkipController(new U(()=>{G(),Je=!0,We.retry()})),Ii.onSettled(()=>{G()}),D=Ii,ze.isPause(at)){let Mi=ze.from(at),Ni=g.preference.getPreference(te.Preferences.gameSpeed);if(Mi.config.duration){let Gi=Mi.config.duration/Ni;await Ki(Gi)}else{let Gi=g.preference.getPreference(te.Preferences.autoForward),Fi=S.race([S.create(
|
|
56
|
+
`?f(at=>[...at,Ze]):typeof Ze=="object"&&"text"in Ze&&!ft.has(Ze)&&(ft.add(Ze),st(Ze))}D&&!D.isSettled()?D.abort():(N.forEach(on=>on()),B.resolve())};return m.schedule(async We=>{let Je=!1,on=!1;for(;!Je;){let{done:Ze,value:at}=ge();if(Ze){Je=on=!0;break}if(ut.isTextEvent(at)){ko(at,rt,m);continue}let Ii=new S;if(m.timelines.attachTimeline(Ii),Ii.registerSkipController(new U(()=>{G(),Je=!0,We.retry()})),Ii.onSettled(()=>{G()}),D=Ii,ze.isPause(at)){let Mi=ze.from(at),Ni=g.preference.getPreference(te.Preferences.gameSpeed);if(Mi.config.duration){let Gi=Mi.config.duration/Ni;await Ki(Gi)}else{let Gi=g.preference.getPreference(te.Preferences.autoForward),Fi=S.race([S.create(Ml=>{let Nl=De(Gl=>{Gl(),Ml.resolve()});K.push(()=>Nl.cancel())}),...Gi?[S.delay(g.config.autoForwardDefaultPause/Ni)]:[]]);m.timelines.attachTimeline(Fi),await S.wait(Fi)}}else{if(at!==`
|
|
57
57
|
`&&ft.has(at))continue;ft.add(at),st(at);let{gameSpeed:Mi,cps:Ni}=g.preference.getPreferences(),Fi=1e3/((typeof at=="object"&&"cps"in at&&at.cps!==void 0?at.cps:Ni)*Mi);await Ki(Fi)}}on&&(N.forEach(Ze=>Ze()),B.resolve())},0),{getToken:()=>B,interact:()=>{let We=!1;Ue.forEach(Je=>Je(()=>We=!0)),!We&&Ge()},update:()=>{D&&D.abort()},forceSkip:()=>{Ge(!0)},timeline:Ee,onComplete:We=>(N.add(We),{cancel:()=>{N.delete(We)}})}}let V=n.config.action.sentence;if(!V)return null;let oe=s??"bold",Ne=V.config.fontSize??i,_e={fontWeight:V.config.bold?oe:r,fontSize:gi(Ne)??lc(),color:Do(V.config.color??o),fontFamily:V.config.fontFamily??a,fontStyle:V.config.italic?"italic":void 0},bt=B=>({fontWeight:B.config.bold||V.config.bold?oe:r,fontSize:pc(B.config,Ne),color:Do(B.config.color??V.config.color??o),fontFamily:B.config.fontFamily??V.config.fontFamily??a,fontStyle:B.config.italic??V.config.italic?"italic":void 0,...Fr(B.config.emphasis)}),At=yi(c),gn=n.isEnded(),mt=(B,Ee)=>{if(B===`
|
|
58
|
-
`)return Ve.createElement("br",{key:Ee});let ft=bt(B),rt=Nr(B.config.render),Ue=
|
|
58
|
+
`)return Ve.createElement("br",{key:Ee});let ft=bt(B),rt=Nr(B.config.render),Ue=Ku(B,rt);return Ve.createElement(zt.Span,{tag:`say.word.${Ee}`,key:Ee,"data-element-type":Ue?"interactive-word":void 0,onClick:Ue?N=>N.stopPropagation():void 0,style:{...ft,...Ur(),...$i(g.config.app.debug,{outline:"1px dashed red"})},className:Eo("inline-block",B.config.className)},Ve.createElement(vc,{word:B,vertical:At,tateChuYoko:u,done:gn,style:ft,renderer:rt}))};return Ve.createElement("div",{...h,ref:b,className:Eo("whitespace-pre-wrap",e),style:{[Po]:x,..._e,...Vr(c,l),...t}},T.map(mt))}function $u({text:o,sentence:e,words:t,useTypeEffect:n=!0,loop:i=!0,restartDelay:r,cps:s,gameSpeed:a,pauseDuration:c,defaultColor:l,className:u,style:d,fontSize:p,fontWeight:h,fontWeightBold:g,fontFamily:m,writingMode:y,textOrientation:T,tateChuYoko:f,onCompleted:v,...A}){let w=Wa(),[,k]=Br(0),b=w?.config??te.DefaultConfig,x=w?.preference.getPreferences()??te.DefaultPreference,I=s??x.cps,V=a??x.gameSpeed,oe=c??b.autoForwardDefaultPause,Ne=r??b.autoForwardDefaultPause,_e=Ve.useMemo(()=>Bu(o,e,t),[o,e,t]),bt=Ve.useMemo(()=>zu(i,r,Ne),[i,r,Ne]),At=hc(v),[gn,mt]=Br(()=>n?[]:zr(_e));kn(()=>{if(w)return w.preference.onPreferenceChange(()=>{k(H=>H+1)}).cancel},[w]),kn(()=>{At.current=v},[v]),kn(()=>{let H=!1,D=[],K=Math.max(.01,V),ce=De=>new Promise(st=>{let Ge=setTimeout(st,Math.max(0,De));D.push(Ge)}),G=()=>{H||At.current?.()};return n?_e.length===0?(mt([]),()=>{H=!0}):((async()=>{do{let De=Kr(_e);for(mt([]);!H;){let{done:st,value:Ge}=De.next();if(st)break;if(ze.isPause(Ge)){let Ri=ze.from(Ge);await ce((Ri.config.duration??oe)/K)}else{if(ut.isTextEvent(Ge))continue;gc(mt,Ge),Ge===`
|
|
59
59
|
`?await ce(fc(I,V)):await ce(fc(Ge.cps??I,V))}}if(H)return;G(),bt.enabled&&await ce(bt.delay)}while(!H&&bt.enabled)})(),()=>{H=!0,D.forEach(De=>clearTimeout(De))}):(mt(zr(_e)),G(),()=>{H=!0})},[_e,n,bt,I,V,oe]);let B=e?.config,Ee=g??"bold",ft={fontWeight:B?.bold?Ee:h,fontSize:B?.fontSize??p,color:Do(B?.color??l),fontFamily:B?.fontFamily??m,fontStyle:B?.italic?"italic":void 0},rt=H=>({fontWeight:H.config.bold||B?.bold?Ee:h,fontSize:dc(H.config,B?.fontSize??p),color:Do(H.config.color??B?.color??l),fontFamily:H.config.fontFamily??B?.fontFamily??m,fontStyle:H.config.italic??B?.italic?"italic":void 0,...Fr(H.config.emphasis)}),Ue=yi(y),N=(H,D)=>{if(H===`
|
|
60
|
-
`)return Ve.createElement("br",{key:D});let K=rt(H);return Ve.createElement("span",{key:D,style:{...K,...Ur()},className:Eo("inline-block",H.config.className)},Ve.createElement(vc,{word:H,vertical:Ue,tateChuYoko:f,done:!1,style:K,renderer:Nr(H.config.render)}))};return Ve.createElement("div",{...A,className:Eo("whitespace-pre-wrap",u),style:{...ft,...Vr(y,T),...d}},gn.map(N))}function Sc(o){return Ve.createElement($r,{...o,key:o.dialog?.config.action.id})}function $u({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=wo({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Ve.createElement($r,{...r,dialog:s,key:s.config.action.id})}function ju(o){let e=It();return Ve.createElement($r,{...o,dialog:e,key:e.config.action.id})}function fn(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Ve.createElement($u,{...o}):Ve.createElement(ju,{...o})}var qu=fn;import Ro,{useEffect as Yu,useLayoutEffect as Xu,useMemo as bc,useRef as Qu,useState as _u}from"react";import Lo from"react";var jr=Lo.createContext(null);function qr(){let o=Lo.useContext(jr);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var Yr=Lo.createContext(null);function Tc(){let o=Lo.useContext(Yr);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function Io({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let c=Qu(null),{register:l,unregister:u,getIndex:d}=Tc(),[p,h]=_u(-1),{choose:g,evaluated:m,gameState:y}=qr(),T=p===-1?null:m[p],f=bc(()=>xe.getCtx({gameState:y}),[y]),{hidden:v,disabled:A}=bc(()=>{if(!T)return{hidden:!1,disabled:!1};let b=T.config.hidden?.evaluate(f)?.value??!1,x=!b&&(T.config.disabled?.evaluate(f)?.value??!1);return{hidden:b,disabled:x}},[T,f]);Xu(()=>{if(!c.current)return;let b=c;l(b);let x=d(b);return h(x),c.current.dataset.index=x.toString(),()=>u(b)},[l,u,d]),Yu(()=>{if(!t)return;let b=x=>{x.key.toLowerCase()===t.toLowerCase()&&!x.ctrlKey&&!x.metaKey&&(x.preventDefault(),x.stopPropagation(),w())};return window.addEventListener("keydown",b,!0),()=>{window.removeEventListener("keydown",b,!0)}},[t]);function w(){if(p===-1||!m[p]||v||A)return;let b=m[p];g({...b,evaluated:ie.getText(b.words||[])})}let k=T&&!v;return Ro.createElement(Ro.Fragment,null,Ro.createElement("button",{className:o,style:{...e,display:k?e?.display??void 0:"none"},onClick:w,ref:c,disabled:A},k&&Ro.createElement(Sc,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Me({useTypeEffect:!1,action:{sentence:T.prompt,words:T.words,character:null},gameState:y,evaluatedWords:T.words})})))}import Mo from"react";import{AnimatePresence as Ju}from"motion/react";function No({children:o,...e}){let t=Ju;return Mo.createElement(Mo.Fragment,null,Mo.createElement("div",{...e},Mo.createElement(t,null,o)))}import Ac from"react";function en({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=Ac.useContext(xn),c=e??o?.character??a?.config.action.character??null,l=n??c?.config.color,u=i??t??c?.state.name;return Ac.createElement("div",{...s,style:{color:l?Rn(l):void 0,...r}},u)}import tp from"clsx";import np from"react";import Xr,{createContext as Zu,useContext as ep,useState as Cc}from"react";var Pn=class Pn{constructor(){this.preloaded=[];this.events=new _}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(Pn.EventTypes["event:preloaded.add"],e),this.events.emit(Pn.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(i=>this.getSrc(i));return this.preloaded=this.preloaded.filter(i=>!n.includes(this.getSrc(i))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(Pn.EventTypes["event:preloaded.remove"],e),this.events.emit(Pn.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Re.getSrc(e)}};Pn.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.complete":"event:preloaded.complete","event:preloaded.unmount":"event:preloaded.unmount"};var $e=Pn;var Go=class o{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.decoded=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.releaseAll(),this.src.clear(),this.decoded.clear()})}static getImage(e,t,n){return ea(e,{...n,signal:t})}static async decodeImage(e){if(typeof window>"u"||typeof window.Image>"u")return null;let t=new window.Image;if(t.src=e,typeof t.decode!="function")return null;try{await t.decode()}catch{return null}return t}release(e){let t=this.src.get(e);t&&t.startsWith("blob:")&&URL.revokeObjectURL(t)}releaseAll(){for(let e of this.src.keys())this.release(e)}has(e){return this.src.has(e)}add(e,t){return this.src.get(e)!==t&&this.release(e),this.src.set(e,t),this}remove(e){return this.release(e),this.src.delete(e),this.decoded.delete(e),this}get(e){return this.src.get(e)}isDecoded(e){return this.decoded.has(e)}clear(){return this.releaseAll(),this.src.clear(),this.decoded.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t,n){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let i=t,r={};this.game.hooks.rawTrigger("preloadImage",()=>[i,(p,h)=>{i=p,r={...r,...h}}]);let s=new AbortController,a=s.signal,c=[],u={promise:o.getImage(i,a,r).then(async p=>{if(this.preloadTasks.delete(t),!p)return;this.add(t,p);let h=await o.decodeImage(p);if(this.src.get(t)!==p){URL.revokeObjectURL(p);return}h&&n?.retainDecoded&&this.decoded.set(t,h)}).catch(p=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),c.forEach(h=>h(p))}),controller:s};this.preloadTasks.set(t,u);let d={abort:()=>{s.abort(),this.preloadTasks.delete(t)},onFinished:p=>(u.promise.then(p),d),onErrored:p=>(c.push(p),d)};return d}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){let t=new Set(e);for(let n of[...this.src.keys()])t.has(n)||(this.release(n),this.src.delete(n),this.decoded.delete(n));for(let n of this.decoded.keys())t.has(n)||this.decoded.delete(n);return this}};var Qr=Zu(null);function xc({children:o}){let e=M(),[t]=Cc(()=>new $e),[n]=Cc(()=>new Go(e));return Xr.createElement(Xr.Fragment,null,Xr.createElement(Qr,{value:{preloaded:t,cacheManager:n}},o))}function Kt(){if(!Qr)throw new Error("usePreloaded must be used within a PreloadedProvider");return ep(Qr)}function wc(){let o=It(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return rp(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?F.getSrcURL(s):null,c=s&&F.isTagSrc(s)?[...s.state.currentSrc]:null,l=Ia({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=op(l.source);return{visible:!!u,src:u,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function ip({className:o,style:e,alt:t,...n}){let i=wc(),{cacheManager:r}=Kt();if(!i.visible||!i.src)return null;let s=r.get(i.src)||i.src;return np.createElement("img",{...n,"data-element-type":"dialog-avatar",className:tp("dialog-avatar",o),src:s,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function op(o){return o?P.srcToURL(o):null}function rp(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var _r=ip;import{useEffect as sp}from"react";function ap(){let o=It(),[e]=ae(o.deps),t=ie.getText(o.config.evaluatedWords);return sp(()=>o.events.on(Me.Events.onFlush,()=>{e()}).cancel,[o]),{done:o.isEnded(),text:t,isNarrator:o.config.action.character===null||o.config.action.character.state.name==="",metadata:o.config.action.sentence?.getMetadata()}}import{useCallback as Fo,useEffect as Jr,useMemo as cp,useRef as lp,useState as kc}from"react";function up(){let o=It(),[e]=ae(o.deps),[t,n]=kc(!0),[i,r]=kc(!0),s=lp(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;Jr(()=>o.events.on(Me.Events.onFlush,()=>{e()}).cancel,[o]);let u=cp(()=>{if(!c)return null;try{return it.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);Jr(()=>{s.current=null,r(!0)},[c]),Jr(()=>{let m=!1,y=null,T=null,f=null;if(!u){n(!0);return}n(!1);let v=()=>{m||n(!0)};y=a.audioManager.getToken(u),y&&(y.isPlaying()||n(!0),T=()=>v(),f=()=>v(),y.once("ended",T),y.once("stop",f));let A=a.events.on(L.EventTypes["event:state.player.lineEnd"],()=>{v()});return()=>{m=!0,A.cancel(),y&&T&&y.off("ended",T),y&&f&&y.off("stop",f)}},[a,u]);let d=Fo(async m=>{let y=m??u;if(!y)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let T=y instanceof URL?fe.voice(y.toString()):typeof y=="string"?fe.voice(y):y,f=await a.getLiveGame().playSound(T);s.current=f;let v=()=>{r(!0)};return f.once("ended",v),f.once("stop",v),f},[a,u]),p=Fo(()=>u,[u]),h=Fo(()=>l,[l]),g=Fo(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:d,getVoice:p,getVoiceId:h,getVoiceSrc:g}}import Zr,{createContext as Ap,useContext as Cp,useEffect as Dc,useRef as xp}from"react";import{useState as pp}from"react";function Oo(o){let[e]=pp(o);return e}import{AnimatePresence as dp}from"motion/react";var Ho=dp;import bi,{createContext as yp,useContext as vp,useEffect as Sp,useRef as Tp}from"react";import{useEffect as vi,useLayoutEffect as mp}from"react";function fp(){let o=Wt(),[e]=ae();return vi(()=>o.onChange(e).cancel,[]),o.getPathname()}function hp(){let{router:o,path:e}=Ti(),[t]=ae();return vi(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function gp(){let o=Wt(),[e]=ae();return vi(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Vo(o,e){let t=Wt();mp(()=>t.onUpdate(()=>o(t)).cancel,e),vi(()=>{o(t)},[])}function Si(){let o=Wt(),[e]=ae();return vi(()=>o.onChange(e).cancel,[]),e}var Pc=yp(null);function Ai({children:o,path:e,consumedBy:t}){let i={router:Wt(),path:e,consumedBy:t};return bi.createElement(Pc,{value:i},o)}function Ti(){let o=vp(Pc);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new E(`Invalid useLayout call: Trying to access layout without a parent.
|
|
61
|
-
This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function bp({children:o,name:e,propagate:t}){let n=M(),[i]=ae(),{path:r,router:s,consumedBy:a}=Ti(),c=s.joinPath(r,e),l=Oo(()=>s.createToken(c+"@layout")),u=s.getCurrentPath(),d=Tp(!1),p=g=>{d.current=g,i()},h=s.matchPath(u,c);if(Si(),Vo(g=>{let m=g.matchPath(g.getCurrentPath(),c);if(d.current&&!m){if(!o){p(!1);return}g.registerUnmountingPath(l)}m&&g.isPathsUnmounting()&&g.unregisterUnmountingPath(l),m&&!d.current&&!g.isTransitioning()&&p(!0)},[h,o]),Sp(()=>{if(!h)return;let g=s.mount(c);return()=>{g.cancel()}},[c,s,h]),a)throw new E("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return bi.createElement(Ai,{path:c},bi.createElement(Ho,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),p(!1)}},h&&d.current&&o))}function Ec({children:o}){return Si(),bi.createElement(Ai,{path:dn.rootPath},bi.createElement(To,{"data-layout-path":dn.rootPath,key:dn.rootPath},o))}var es=Ap(null);function wp(){return Cp(es)}function kp({children:o,name:e}){let[t]=ae(),{path:n,router:i,consumedBy:r}=Ti(),s=wp(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,u=Oo(()=>i.createToken(l+"@page")),d=i.getCurrentPath(),p=!a,h=xp(!1),g=f=>{h.current=f,t()},m=p&&i.exactMatch(d,n)||i.exactMatch(d,l);if(r&&r!==c)throw new E("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");Si(),Vo(f=>{let v=p&&f.exactMatch(f.getCurrentPath(),n)||f.exactMatch(f.getCurrentPath(),l);if(h.current&&!v){if(!o){g(!1);return}f.registerUnmountingPath(u)}v&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(u),v&&!h.current&&!f.isTransitioning()&&g(!0)},[m,o]),Dc(()=>{if(!m)return;let f=p?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{f.cancel()}},[l,m]),Dc(()=>()=>{i.unregisterUnmountingPath(u),g(!1)},[]);let y=Zr.createElement(Ai,{path:n,consumedBy:c},Zr.createElement(Ho,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),g(!1)}},m&&h.current&&o));return(f=>s?Zr.createElement(es,{value:{name:null}},f):f)(y)}import ts,{useCallback as Pp,useEffect as ns,useImperativeHandle as Ep,useMemo as Lc,useRef as is,useState as Dp}from"react";var Lp=50,Rp={position:"relative",width:"100%",height:"100%",overflow:"hidden"},Rc={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function Ip(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function Ic(o,e){return e==null?o:Math.max(o,e)}function Mp(o,e,t){return o<=0||e<=0||t<=0?{width:o,height:e}:o/e>t?{width:e*t,height:e}:{width:o,height:o/t}}var Mc=ts.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:u,children:d},p){let h=is(null),[g,m]=Dp({...Rc,width:"0px",height:"0px"}),y=is(u),T=is(null);ns(()=>{y.current=u},[u]);let f=Pp(()=>{let w=h.current;if(!w)return;let k=w.clientWidth,b=w.clientHeight;if(k<=0||b<=0||e<=0)return;let x=Mp(k,b,e),I=Ic(x.width,n),V=Ic(x.height,i),oe=T.current;(!oe||oe.width!==I||oe.height!==V)&&(T.current={width:I,height:V},m({...Rc,width:`${I}px`,height:`${V}px`}));let Ne=t>0?I/t:1;y.current?.({width:I,height:V,scale:Ne,containerWidth:k,containerHeight:b})},[e,t,n,i]),v=Lc(()=>Js(f,typeof r=="number"?r:Lp),[f,r]);ns(()=>{f()},[f]),ns(()=>{let w=new ResizeObserver(()=>{v()});h.current&&w.observe(h.current);let k=()=>{v()};return window.addEventListener("resize",k),()=>{w.disconnect(),window.removeEventListener("resize",k)}},[v]),Ep(p,()=>({requestUpdate:f}),[f]);let A=Lc(()=>Ip(l),[l]);return ts.createElement("div",{id:c,ref:h,style:Rp,...A},ts.createElement("div",{className:s,style:{...g,...a}},d))}),Nc=Mc;function Np(){return M().getLiveGame()}import ss from"react";import Gp,{createContext as Fp,useContext as Op,useEffect as Hp,useState as Gc}from"react";var Vp={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},Fc=Fp({state:Vp,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function $t(){return Op(Fc)}function os(){let{dialogs:o}=$t();return o}function Up(){let{isActive:o}=$t();return o}function Wp(){let{isVisible:o}=$t();return o}function rs({children:o}){let t=M().getLiveGame().getGameState(),[n,i]=Gc(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=Gc(null);Hp(()=>{let c=g=>({...g,dialogs:[...g.dialogs]}),l=t.events.on(L.EventTypes["event:state.nvl.enter"],(g,m)=>{i(c(t.getNvlState())),s(m?.showTransition||null)}),u=t.events.on(L.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState()))}),d=t.events.on(L.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),p=t.events.on(L.EventTypes["event:state.nvl.visibilityChange"],(g,m)=>{i(c(t.getNvlState())),s(m||null)}),h=t.events.on(L.EventTypes["event:state.nvl.change"],g=>{i(c(g))});return()=>{l.cancel(),u.cancel(),d.cancel(),p.cancel(),h.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return Gp.createElement(Fc.Provider,{value:a},o)}import{AnimatePresence as Bp,motion as zp}from"motion/react";import Kp from"clsx";function as({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=$t(),{ratio:r}=he(),s=M(),a=i?.duration?i.duration/1e3:.3;return ss.createElement(Bp,null,n&&ss.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},ss.createElement(zp.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:Kp("w-full h-full overflow-auto",e),style:{transform:s.config.useAspectScale?`scale(${r.state.scale})`:void 0,transformOrigin:"top left",width:s.config.useAspectScale?s.config.width:"100%",height:s.config.useAspectScale?s.config.height:"100%",...t}},o)))}import En from"react";function cs({renderDialogItem:o,dialogs:e}){return En.createElement(as,{className:"bg-black/80 text-white p-16 inset-8"},En.createElement("div",{"data-element-type":"nvl-dialog-list",className:"flex flex-col space-y-4 p-4"},(e??[]).map((n,i)=>{let r=n.entry.character?En.createElement(en,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=En.createElement(fn,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return En.createElement("div",{key:`${n.entry.id}:${n.isActive?"active":"idle"}`,"data-element-type":"nvl-dialog-item","data-dialog-index":i,className:"nvl-dialog-item"},o?o({entry:n.entry,index:i,isActive:n.isActive,nametag:r,texts:s}):En.createElement(En.Fragment,null,r,s))})))}import Tt,{useMemo as $p}from"react";import Oc from"clsx";function jp({children:o,className:e,style:t,renderDialogItem:n}){let i=os(),{state:r}=$t();return Tt.createElement("div",{"data-element-type":"nvl-dialog-list",className:Oc("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>Tt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},Tt.createElement(qp,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?Tt.createElement(en,{className:"nvl-character-name font-bold mr-2"}):null,texts:Tt.createElement(fn,{className:"nvl-dialog-text"})}):o?Tt.Children.map(o,c=>Tt.isValidElement(c)?Tt.cloneElement(c,{entry:s,index:a}):c):Tt.createElement(Hc,{entry:s,index:a})))))}function Hc({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??Tt.createElement(fn,{className:"nvl-dialog-text"});return Tt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:Oc("nvl-dialog-item",t),style:n},r&&Tt.createElement(en,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function qp({entry:o,children:e}){let n=M().getLiveGame().getGameState(),i=$p(()=>o.sentence.evaluate(xe.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=wo({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return Tt.createElement(xn,{value:c},e)}import Uo from"react";import{createPortal as Yp}from"react-dom";var ls=Uo.createContext(null),Xp={Portal:()=>null,measure:()=>null,container:null};function Qp(){let o=Uo.useContext(ls);return Uo.useMemo(()=>{if(!o)return Xp;let e=t=>{let n=o.offsetWidth;return!n||!t.width?1:t.width/n};return{container:o,Portal:({children:t})=>Yp(Uo.createElement("div",{style:{position:"absolute",left:0,top:0,pointerEvents:"auto"}},t),o),measure:t=>{if(!t)return null;let n=o.getBoundingClientRect(),i=e(n),r=t.getBoundingClientRect(),s=(r.left-n.left)/i,a=(r.top-n.top)/i,c=r.width/i,l=r.height/i;return{left:s,top:a,width:c,height:l,right:s+c,bottom:a+l}}}},[o])}import{useEffect as _p}from"react";function Jp(o){let e=M();_p(()=>{if(!o)return;let t=e.getLiveGame().getGameState();if(t)return t.suspendAdvance()},[o,e])}var Wo=class{constructor(e,t){this.emit=e;this.options=t;this.held=!1;this.delayTimer=null;this.repeatTimer=null}isHeld(){return this.held}press(){this.held||(this.clearTimers(),this.held=!0,this.emit(!1),this.options.delay===0?this.startRepeating():this.delayTimer=setTimeout(()=>{this.delayTimer=null,this.startRepeating()},this.options.delay))}release(){this.clearTimers(),this.held=!1}dispose(){this.release()}startRepeating(){this.repeatTimer=setInterval(()=>{this.emit(!0)},this.options.interval)}clearTimers(){this.delayTimer!==null&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.repeatTimer!==null&&(clearInterval(this.repeatTimer),this.repeatTimer=null)}};function Uc({state:o}){let e=M(),t=Wt(),[n]=mn(te.Preferences.skipDelay),[i]=mn(te.Preferences.skipInterval),[r]=wn("skipAction");return ed(()=>{if(!e.getLiveGame().gameState.playerCurrent){o.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){o.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let a=new Wo(u=>{o.events.emit(L.EventTypes["event:state.player.skip"],u)},{delay:n,interval:i}),c=u=>{o.isAdvanceSuspended()||e.keyMap.match("skipAction",u.key)&&e.preference.getPreference(te.Preferences.skip)&&(a.isHeld()||o.logger.verbose("KeyEventAnnouncer","Skipping"),a.press())},l=u=>{e.keyMap.match("skipAction",u.key)&&a.release()};if(e.config.useWindowListener){let u=e.getLiveGame().onWindowEvent("keydown",c).cancel,d=e.getLiveGame().onWindowEvent("keyup",l).cancel;return()=>{a.dispose(),u(),d()}}else{let u=e.getLiveGame().onPlayerEvent("keydown",c).cancel,d=e.getLiveGame().onPlayerEvent("keyup",l).cancel;return()=>{a.dispose(),u(),d()}}},[t,n,i,r]),Vc.createElement(Vc.Fragment,null)}import Bc,{useEffect as td}from"react";function Wc({onStage:o,dialogShown:e,advanceSuspended:t}){return o?e?t?"ignore":"advance":"restoreDialog":"ignore"}function nd(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var zc=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],id=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]','[data-element-type="interactive-word"]','[data-element-type="dialog-overlay"]'];function od(o,e){return!o||e&&zc.some(t=>!!o.closest(t))?!1:[...id,...zc].some(t=>!!o.closest(t))}function Kc(o,e){if(!e)return!1;let t=e.getBoundingClientRect();return o.clientX>=t.left&&o.clientX<=t.right&&o.clientY>=t.top&&o.clientY<=t.bottom}function $c({state:o}){let e=M();return td(()=>{let t=e.getLiveGame().gameState?.playerCurrent;if(!t){o.logger.warn("StageClickAnnouncer","Failed to listen to playerElement events");return}let n=i=>{let r=i.target;if(!r||!t.contains(r)||!Kc(i,t))return;let s=o.mainContentNode;if(s&&(!s.contains(r)||!Kc(i,s))||nd(r)||od(r,o.isNvlMode()))return;let a=Wc({onStage:!0,dialogShown:e.preference.getPreference(te.Preferences.showDialog),advanceSuspended:o.isAdvanceSuspended()});if(a!=="ignore"){if(a==="restoreDialog"){e.preference.setPreference(te.Preferences.showDialog,!0);return}o.events.emit(L.EventTypes["event:state.player.stageClick"]),o.recordStageClick()}};if(e.config.useWindowListener){let i=e.getLiveGame().onWindowEvent("click",n);return()=>{i.cancel()}}else{let i=e.getLiveGame().onPlayerEvent("click",n);return()=>{i.cancel()}}},[e,o]),Bc.createElement(Bc.Fragment,null)}import{useEffect as jc}from"react";function us({gameState:o}){let e=o.audioManager,[t,n]=mn("globalVolume");return jc(()=>{n(e.getGlobalVolume())},[]),jc(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as Bo,useRef as rd}from"react";function qc(o){let e=Re.catSrc(o.srcManager?.src||[]),t=Re.catSrc(o.srcManager?.getFutureSrc()||[]),n=[],i=[],r=[],s=new Set,a=o.state?.backgroundImage?.state?.currentSrc;if(P.isImageSrc(a)){let c=P.srcToURL(a);c&&(s.add(c),n.push(c))}for(let c of e.image){let l=Re.getSrc(c);!l||s.has(l)||(s.add(l),i.push(l))}for(let c of t.image){let l=Re.getSrc(c);!l||s.has(l)||(s.add(l),r.push(l))}return{firstFrame:n,critical:i,lookAhead:r,all:[...n,...i,...r],criticalAudio:e.audio}}function Yc({state:o}){let{preloaded:e,cacheManager:t}=Kt(),n=M(),i=rd(new Set),[r]=ae(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function u(){o.logger.debug(s,"Preload unmounted"),e.events.emit($e.EventTypes["event:preloaded.unmount"])}return Bo(()=>o.events.on(L.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),Bo(()=>{if(typeof fetch>"u")return e.events.emit($e.EventTypes["event:preloaded.complete"]),e.events.emit($e.EventTypes["event:preloaded.ready"]),o.logger.warn(s,"Fetch is not supported in this environment, skipping preload"),u;if(!n.config.preloadAllImages)return e.events.emit($e.EventTypes["event:preloaded.complete"]),e.events.emit($e.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),u;if(n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(s,"Cache cleared")),!l||!a)return l?o.logger.debug(s,"Scene not ready yet, waiting for scene before preload"):o.logger.weakWarn(s,"Story not found, skipping preload"),u;let d=performance.now(),p=qc(a),h=new vn(n.config.preloadConcurrency,0),g=new vn(n.config.preloadConcurrency,0),m=new vn(n.config.preloadConcurrency,n.config.preloadDelay),y=o.logger.group(s,!0),T=!1;o.logger.debug(s,"preloading:",p,a);let f=(w,k,b,x)=>{k.forEach((I,V)=>{if(t.has(I)||t.isPreloading(I)){o.logger.debug(s,`Image already loaded (${b} ${V+1}/${k.length})`,I);return}w.addTask(()=>new Promise(oe=>{t.preload(o,I,{retainDecoded:x}).onFinished(()=>{o.logger.debug(s,`Image loaded (${b} ${V+1}/${k.length})`,I),oe()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${b} ${V+1}/${k.length})`,I),oe()})}))})};f(h,p.firstFrame,"first frame",!0),f(g,p.critical,"first scene",!0),f(m,p.lookAhead,"look-ahead",!1);for(let w of p.criticalAudio)o.audioManager.preload(w);y.end();let v=()=>{e.events.emit($e.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit($e.EventTypes["event:preloaded.ready"])},A=n.config.preloadGate!=="scene";return h.start().then(async()=>{o.logger.info(s,"Image preload (first frame)",`loaded ${t.size()} images in ${performance.now()-d}ms`),A&&v(),!T&&(await g.start(),o.logger.info(s,"Image preload (first scene)",`loaded ${t.size()} images in ${performance.now()-d}ms`),A||v(),!T&&(await m.start(),!T&&(o.logger.info(s,"Image preload (look-ahead)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(p.all))))}),n.config.waitForPreload||e.events.emit($e.EventTypes["event:preloaded.ready"]),e.events.emit($e.EventTypes["event:preloaded.mount"]),()=>{T=!0,u()}},[a,l]),Bo(()=>{i.current.clear()},[a]),Bo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let d=performance.now(),p=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(f=>Re.getPreloadableSrc(l,f)).filter(function(f){return f!==null});p.filter(function(f){return f?.activeType==="scene"}).forEach(f=>{i.current.has(f)||i.current.add(f)});let g=Re.catSrc([...i.current,...p]),m=new vn(n.config.preloadConcurrency,n.config.preloadDelay),y=[],T=o.logger.group(s);o.logger.debug(s,"preloading:",g);for(let f of g.image){let v=Re.getSrc(f);if(v){if(y.push(v),t.has(v)||t.isPreloading(v)){o.logger.debug(s,`Image already loaded (${g.image.indexOf(f)+1}/${g.image.length})`,v);continue}m.addTask(()=>new Promise(A=>{t.preload(o,v).onFinished(()=>{o.logger.debug(s,`Image loaded (${g.image.indexOf(f)+1}/${g.image.length})`,v),A()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${g.image.indexOf(f)+1}/${g.image.length})`,v),A()})}))}}T.end(),m.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(y)})},[c,l]),null}import Ci from"react";import Ko from"react";import ps,{useEffect as ds,useLayoutEffect as ms,useRef as zo,useState as fs}from"react";function jt({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c,companionRefs:l}){let[u,d]=fs(null),[p,h]=fs(null),g=zo(null),m=ps.useRef(null),[y]=fs(()=>new Vi("displayable.refGroup")),T=zo(y.next()),f=zo(rt()),A=M().getLiveGame().getGameState(),w=typeof a=="function"?a(u):a,[k]=ae([p,u,f]);ds(()=>A.events.depends([A.events.on(L.EventTypes["event:state.player.skip"],ft)]).cancel,[p,u,f]),ms(()=>{if(V(),!u)return;if(f.current.some(([G])=>!G.current))throw new E("Displayable: Trying to access transition groups before they are mounted");let{controller:N,task:H}=u,D=G=>{f.current.forEach(([ge],De)=>{let st=H.resolve[De],Ge=typeof st=="function"?st:st.resolver;if(!Ge)throw new E(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${De}])`);let Ri=Ge(...G),or=Y(w[De]||w[w.length-1]||{},Ri);Ne(ge,c?c(or):or)})},K=N.onUpdate(D);D(H.animations.map(G=>G.start));let ce=!1;return Promise.all(f.current.map(([G])=>{let ge=G.current;return ge?.waitForLoad?ge.waitForLoad():Promise.resolve()})).then(()=>{ce||N.start()}),()=>{ce=!0,K.cancel()}},[u]),ds(()=>{if(!m.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),ms(()=>{let N=e.toStyle(A,i);return Object.assign(m.current.style,N),I(),A.logger.debug("Displayable","Initial style applied",m.current,N),bt(),()=>{_e()}},[]);let b=zo(()=>{});b.current=()=>{u||!m.current||(V(),!(p||g.current)&&(Object.assign(m.current.style,e.toStyle(A,i)),I()))},ms(()=>{g.current&&!o._getLoop()&&_e(),b.current()});let{ratio:x}=he();ds(()=>x.onUpdate(()=>{b.current(),requestAnimationFrame(()=>b.current())}),[x]);function I(){if(l)for(let{ref:N,project:H}of l)N.current&&Object.assign(N.current.style,H(e.get()))}function V(){let N=typeof a=="function"?a(u):a;if(!f.current||!f.current.length)throw new E("Displayable: Transition group refs are not initialized correctly");f.current.some(([H])=>!H.current)||f.current.forEach(([H],D)=>{Ne(H,N[D]||N[N.length-1]||{})})}function oe(N){A.logger.debug("Displayable","Transform applied",e.toStyle(A,i),m.current),k(),r?.(N)}function Ne(N,H){if(!N.current)throw new E("Displayable: Trying to assign properties to unmounted element");oo(N.current,H,c)}function _e(){g.current&&(g.current.stop(),g.current=null,A.logger.debug("Displayable","Loop stopped",o))}function bt(){let N=o._getLoop();if(!N){_e();return}g.current||At(N.transform,N.options)}function At(N,H){p&&(p.abort(),h(null)),_e(),m.current&&(g.current=N.startLoop(e,{gameState:A,ref:m,overwrites:i,companionRefs:l},H))}function gn(N,H){return mt(new Z({},{duration:N?.duration??0,ease:N?.ease??"linear"}),H)}function mt(N,H){p&&(p.abort(),h(null)),_e();let D=N.animate(e,{gameState:A,ref:m,overwrites:i,companionRefs:l}),K=new we(D);return A.timelines.attachTimeline(K),D.onSkipControllerRegister(ce=>{ce.onAbort(()=>{K.abort(),h(null)})}),h(D),D.then(()=>{h(null),oe(N),H(),bt()}),K}function B(N,H){u&&u.controller.complete();let D=N.createTask(A),K=N.requestAnimations(D.animations),ce=new S().registerSkipController(new U(K.cancel)),G=new we(ce);ce.skipController.onAbort(()=>{K.cancel()}),K.onCanceled(()=>{G.abort(),d(null),A.logger.debug("Displayable","Transition cancelled",N)}),K.onComplete(()=>{Ue(),d(null),s?.(N),H(),ce.resolve()}),A.timelines.attachTimeline(G),d({task:D,controller:K,transition:N,resolve:H});let ge;if(f.current=D.resolve.map(De=>{let st=ps.createRef(),Ge=typeof De=="function"?void 0:De.key;if(!Ge)return[st,y.next()];if(Ge==="target")return ge=y.next(),[st,ge];if(Ge==="current")return[st,T.current];throw new E("Displayable: Invalid key type")}),!ge)throw new E("Displayable: No target key found");return T.current=ge,G}function Ee(N){return A.logger.debug("initDisplayable",o),mt(Z.immediate(e.get()),N)}function ft(){t&&p&&(p.abort(),h(null),A.logger.debug("transform skipped")),n&&u&&(u.controller.complete(),A.logger.debug("transition skipped"))}function rt(){return[[ps.createRef(),T.current]]}function Ue(){f.current.forEach(([N])=>{N.current=null}),f.current=rt()}return{transformRef:m,transitionRefs:f.current,transitionTask:u,initDisplayable:Ee,applyTransform:mt,applyTransition:B,applyLoop:At,stopLoop:gn,updateStyleSync:V,flush:k,deps:[p,u,f]}}import{useEffect as sd}from"react";function xt(o,e,t=[]){let i=M().getLiveGame().getGameState();return sd(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function hs({state:o,text:e}){let{ratio:t}=he(),[n]=ae(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyLoop:c,stopLoop:l,applyTransition:u,updateStyleSync:d,deps:p}=jt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:h=>({width:"fit-content",transform:Z.propToCSSTransform(o,h,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return xt(e,{initDisplayable:s,applyTransform:a,applyLoop:c,stopLoop:l,applyTransition:u,flush:n,updateStyleSync:d},[...p]),Ko.createElement(zt.Div,{"data-element-type":"text"},Ko.createElement(zt.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([h,g])=>Ko.createElement("span",{key:g,ref:h,className:e.config.className},Ko.createElement("span",null,e.state.text)))))}import Nt,{forwardRef as cd,useCallback as Qc,useImperativeHandle as ld,useRef as qo,useState as _c}from"react";import $o,{useEffect as gs,useRef as Kn,forwardRef as ad}from"react";var Xc=ad(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=Kn(null),{ratio:a}=he(),[c,l]=$o.useState(0),[u,d]=$o.useState(0),p=Kn(null),h=Kn(null),g=M(),m=Kn(!1),y=Kn(null),T=Kn(null);$o.useImperativeHandle(r,()=>s.current,[]),gs(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>{let w=()=>{let k=s.current;return!k||typeof k.decode!="function"?Promise.resolve():k.decode().catch(()=>{})};return m.current?w():(y.current||(y.current=new Promise(k=>{T.current=k})),y.current.then(w))},configurable:!0}})},[]),gs(()=>(f(),a.onUpdate(f)),[o]),gs(()=>{let w=new MutationObserver(k=>{k.forEach(b=>{b.type==="attributes"&&b.attributeName==="src"&&s.current&&f()})});return s.current&&w.observe(s.current,{attributes:!0}),()=>{w.disconnect()}},[o]);function f(){if(s.current&&s.current.naturalWidth){let w,k,b;if(s.current.naturalWidth*s.current.naturalHeight===1)w=a.state.width,k=a.state.height,b=`${w} / ${k}`;else{let oe=t?g.config.width/s.current.naturalWidth:1;w=s.current.naturalWidth*a.state.scale*oe,k=s.current.naturalHeight*a.state.scale*oe,b="auto"}let x=p.current,I=!x||x.w!==w||x.h!==k||x.ar!==b,V=!!o&&h.current!==o;if(!I&&!V)return;I&&(p.current={w,h:k,ar:b},l(w),d(k),s.current.style.aspectRatio=b),o&&(h.current=o,o(w,k))}}function v(){f(),m.current=!0,T.current&&(T.current(),T.current=null,y.current=null),e&&e()}function A(){m.current=!0,T.current&&(T.current(),T.current=null,y.current=null)}return $o.createElement("img",{ref:s,onLoad:v,onError:A,width:c,height:u,alt:"",src:n,style:i})});Xc.displayName="AspectScaleImage";var jo=Xc;import Jc from"clsx";import{motion as ud}from"motion/react";var pd={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},Zc=cd(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=qo(null),a=qo([]),c=o.findIndex(l=>l!==null);return ld(r,()=>Object.assign(s.current,{isLoaded:()=>a.current.every(l=>!l?.isLoaded||l.isLoaded()),waitForLoad:()=>Promise.all(a.current.map(l=>l?.waitForLoad?l.waitForLoad():Promise.resolve())).then(()=>{})}),[]),Nt.createElement("div",{ref:s},o.map((l,u)=>l===null?null:Nt.createElement(jo,{key:"layer-"+u,ref:d=>{a.current[u]=d},src:t(l),style:pd,autoFit:e,onSizeChanged:u===c?n:void 0,onLoad:u===c?i:void 0})))});Zc.displayName="LayerStack";function dd(o){return{willChange:"filter, opacity",position:"absolute",top:0,left:0,right:0,bottom:0,transform:"none",translate:"none",opacity:1,clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat",filter:`brightness(${1-o})`}}function md(o){return F.isStaticSrc(o)?o.state.currentSrc:F.getSrcURL(o)??void 0}var fd={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function hd({image:o,state:e}){let[t]=_c(()=>new _),[n,i]=_c([]),{cacheManager:r}=Kt(),s=qo([]),a=qo(null),c=F.isLayeredSrc(o)?F.getSrcURLs(o):null;function l(b){return!P.isInlineSrc(b)&&!r.has(b)&&!r.isPreloading(b)&&!s.current.includes(b)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${b}".
|
|
60
|
+
`)return Ve.createElement("br",{key:D});let K=rt(H);return Ve.createElement("span",{key:D,style:{...K,...Ur()},className:Eo("inline-block",H.config.className)},Ve.createElement(vc,{word:H,vertical:Ue,tateChuYoko:f,done:!1,style:K,renderer:Nr(H.config.render)}))};return Ve.createElement("div",{...A,className:Eo("whitespace-pre-wrap",u),style:{...ft,...Vr(y,T),...d}},gn.map(N))}function Sc(o){return Ve.createElement($r,{...o,key:o.dialog?.config.action.id})}function ju({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=wo({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Ve.createElement($r,{...r,dialog:s,key:s.config.action.id})}function qu(o){let e=It();return Ve.createElement($r,{...o,dialog:e,key:e.config.action.id})}function fn(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Ve.createElement(ju,{...o}):Ve.createElement(qu,{...o})}var Yu=fn;import Ro,{useEffect as Xu,useLayoutEffect as Qu,useMemo as bc,useRef as _u,useState as Ju}from"react";import Lo from"react";var jr=Lo.createContext(null);function qr(){let o=Lo.useContext(jr);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var Yr=Lo.createContext(null);function Tc(){let o=Lo.useContext(Yr);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function Io({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let c=_u(null),{register:l,unregister:u,getIndex:d}=Tc(),[p,h]=Ju(-1),{choose:g,evaluated:m,gameState:y}=qr(),T=p===-1?null:m[p],f=bc(()=>xe.getCtx({gameState:y}),[y]),{hidden:v,disabled:A}=bc(()=>{if(!T)return{hidden:!1,disabled:!1};let b=T.config.hidden?.evaluate(f)?.value??!1,x=!b&&(T.config.disabled?.evaluate(f)?.value??!1);return{hidden:b,disabled:x}},[T,f]);Qu(()=>{if(!c.current)return;let b=c;l(b);let x=d(b);return h(x),c.current.dataset.index=x.toString(),()=>u(b)},[l,u,d]),Xu(()=>{if(!t)return;let b=x=>{x.key.toLowerCase()===t.toLowerCase()&&!x.ctrlKey&&!x.metaKey&&(x.preventDefault(),x.stopPropagation(),w())};return window.addEventListener("keydown",b,!0),()=>{window.removeEventListener("keydown",b,!0)}},[t]);function w(){if(p===-1||!m[p]||v||A)return;let b=m[p];g({...b,evaluated:ie.getText(b.words||[])})}let k=T&&!v;return Ro.createElement(Ro.Fragment,null,Ro.createElement("button",{className:o,style:{...e,display:k?e?.display??void 0:"none"},onClick:w,ref:c,disabled:A},k&&Ro.createElement(Sc,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Me({useTypeEffect:!1,action:{sentence:T.prompt,words:T.words,character:null},gameState:y,evaluatedWords:T.words})})))}import Mo from"react";import{AnimatePresence as Zu}from"motion/react";function No({children:o,...e}){let t=Zu;return Mo.createElement(Mo.Fragment,null,Mo.createElement("div",{...e},Mo.createElement(t,null,o)))}import Ac from"react";function en({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=Ac.useContext(xn),c=e??o?.character??a?.config.action.character??null,l=n??c?.config.color,u=i??t??c?.state.name;return Ac.createElement("div",{...s,style:{color:l?Rn(l):void 0,...r}},u)}import np from"clsx";import ip from"react";import Xr,{createContext as ep,useContext as tp,useState as Cc}from"react";var Pn=class Pn{constructor(){this.preloaded=[];this.events=new _}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(Pn.EventTypes["event:preloaded.add"],e),this.events.emit(Pn.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(i=>this.getSrc(i));return this.preloaded=this.preloaded.filter(i=>!n.includes(this.getSrc(i))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(Pn.EventTypes["event:preloaded.remove"],e),this.events.emit(Pn.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Re.getSrc(e)}};Pn.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.complete":"event:preloaded.complete","event:preloaded.unmount":"event:preloaded.unmount"};var $e=Pn;var Go=class o{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.decoded=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.releaseAll(),this.src.clear(),this.decoded.clear()})}static getImage(e,t,n){return ea(e,{...n,signal:t})}static async decodeImage(e){if(typeof window>"u"||typeof window.Image>"u")return null;let t=new window.Image;if(t.src=e,typeof t.decode!="function")return null;try{await t.decode()}catch{return null}return t}release(e){let t=this.src.get(e);t&&t.startsWith("blob:")&&URL.revokeObjectURL(t)}releaseAll(){for(let e of this.src.keys())this.release(e)}has(e){return this.src.has(e)}add(e,t){return this.src.get(e)!==t&&this.release(e),this.src.set(e,t),this}remove(e){return this.release(e),this.src.delete(e),this.decoded.delete(e),this}get(e){return this.src.get(e)}isDecoded(e){return this.decoded.has(e)}clear(){return this.releaseAll(),this.src.clear(),this.decoded.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t,n){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let i=t,r={};this.game.hooks.rawTrigger("preloadImage",()=>[i,(p,h)=>{i=p,r={...r,...h}}]);let s=new AbortController,a=s.signal,c=[],u={promise:o.getImage(i,a,r).then(async p=>{if(this.preloadTasks.delete(t),!p)return;this.add(t,p);let h=await o.decodeImage(p);if(this.src.get(t)!==p){URL.revokeObjectURL(p);return}h&&n?.retainDecoded&&this.decoded.set(t,h)}).catch(p=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),c.forEach(h=>h(p))}),controller:s};this.preloadTasks.set(t,u);let d={abort:()=>{s.abort(),this.preloadTasks.delete(t)},onFinished:p=>(u.promise.then(p),d),onErrored:p=>(c.push(p),d)};return d}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){let t=new Set(e);for(let n of[...this.src.keys()])t.has(n)||(this.release(n),this.src.delete(n),this.decoded.delete(n));for(let n of this.decoded.keys())t.has(n)||this.decoded.delete(n);return this}};var Qr=ep(null);function xc({children:o}){let e=M(),[t]=Cc(()=>new $e),[n]=Cc(()=>new Go(e));return Xr.createElement(Xr.Fragment,null,Xr.createElement(Qr,{value:{preloaded:t,cacheManager:n}},o))}function Kt(){if(!Qr)throw new Error("usePreloaded must be used within a PreloadedProvider");return tp(Qr)}function wc(){let o=It(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return sp(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?F.getSrcURL(s):null,c=s&&F.isTagSrc(s)?[...s.state.currentSrc]:null,l=Ia({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=rp(l.source);return{visible:!!u,src:u,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function op({className:o,style:e,alt:t,...n}){let i=wc(),{cacheManager:r}=Kt();if(!i.visible||!i.src)return null;let s=r.get(i.src)||i.src;return ip.createElement("img",{...n,"data-element-type":"dialog-avatar",className:np("dialog-avatar",o),src:s,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function rp(o){return o?P.srcToURL(o):null}function sp(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var _r=op;import{useEffect as ap}from"react";function cp(){let o=It(),[e]=ae(o.deps),t=ie.getText(o.config.evaluatedWords);return ap(()=>o.events.on(Me.Events.onFlush,()=>{e()}).cancel,[o]),{done:o.isEnded(),text:t,isNarrator:o.config.action.character===null||o.config.action.character.state.name==="",metadata:o.config.action.sentence?.getMetadata()}}import{useCallback as Fo,useEffect as Jr,useMemo as lp,useRef as up,useState as kc}from"react";function pp(){let o=It(),[e]=ae(o.deps),[t,n]=kc(!0),[i,r]=kc(!0),s=up(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;Jr(()=>o.events.on(Me.Events.onFlush,()=>{e()}).cancel,[o]);let u=lp(()=>{if(!c)return null;try{return it.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);Jr(()=>{s.current=null,r(!0)},[c]),Jr(()=>{let m=!1,y=null,T=null,f=null;if(!u){n(!0);return}n(!1);let v=()=>{m||n(!0)};y=a.audioManager.getToken(u),y&&(y.isPlaying()||n(!0),T=()=>v(),f=()=>v(),y.once("ended",T),y.once("stop",f));let A=a.events.on(L.EventTypes["event:state.player.lineEnd"],()=>{v()});return()=>{m=!0,A.cancel(),y&&T&&y.off("ended",T),y&&f&&y.off("stop",f)}},[a,u]);let d=Fo(async m=>{let y=m??u;if(!y)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let T=y instanceof URL?fe.voice(y.toString()):typeof y=="string"?fe.voice(y):y,f=await a.getLiveGame().playSound(T);s.current=f;let v=()=>{r(!0)};return f.once("ended",v),f.once("stop",v),f},[a,u]),p=Fo(()=>u,[u]),h=Fo(()=>l,[l]),g=Fo(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:d,getVoice:p,getVoiceId:h,getVoiceSrc:g}}import Zr,{createContext as Cp,useContext as xp,useEffect as Dc,useRef as wp}from"react";import{useState as dp}from"react";function Oo(o){let[e]=dp(o);return e}import{AnimatePresence as mp}from"motion/react";var Ho=mp;import bi,{createContext as vp,useContext as Sp,useEffect as Tp,useRef as bp}from"react";import{useEffect as vi,useLayoutEffect as fp}from"react";function hp(){let o=Wt(),[e]=ae();return vi(()=>o.onChange(e).cancel,[]),o.getPathname()}function gp(){let{router:o,path:e}=Ti(),[t]=ae();return vi(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function yp(){let o=Wt(),[e]=ae();return vi(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Vo(o,e){let t=Wt();fp(()=>t.onUpdate(()=>o(t)).cancel,e),vi(()=>{o(t)},[])}function Si(){let o=Wt(),[e]=ae();return vi(()=>o.onChange(e).cancel,[]),e}var Pc=vp(null);function Ai({children:o,path:e,consumedBy:t}){let i={router:Wt(),path:e,consumedBy:t};return bi.createElement(Pc,{value:i},o)}function Ti(){let o=Sp(Pc);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new E(`Invalid useLayout call: Trying to access layout without a parent.
|
|
61
|
+
This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function Ap({children:o,name:e,propagate:t}){let n=M(),[i]=ae(),{path:r,router:s,consumedBy:a}=Ti(),c=s.joinPath(r,e),l=Oo(()=>s.createToken(c+"@layout")),u=s.getCurrentPath(),d=bp(!1),p=g=>{d.current=g,i()},h=s.matchPath(u,c);if(Si(),Vo(g=>{let m=g.matchPath(g.getCurrentPath(),c);if(d.current&&!m){if(!o){p(!1);return}g.registerUnmountingPath(l)}m&&g.isPathsUnmounting()&&g.unregisterUnmountingPath(l),m&&!d.current&&!g.isTransitioning()&&p(!0)},[h,o]),Tp(()=>{if(!h)return;let g=s.mount(c);return()=>{g.cancel()}},[c,s,h]),a)throw new E("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return bi.createElement(Ai,{path:c},bi.createElement(Ho,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),p(!1)}},h&&d.current&&o))}function Ec({children:o}){return Si(),bi.createElement(Ai,{path:dn.rootPath},bi.createElement(To,{"data-layout-path":dn.rootPath,key:dn.rootPath},o))}var es=Cp(null);function kp(){return xp(es)}function Pp({children:o,name:e}){let[t]=ae(),{path:n,router:i,consumedBy:r}=Ti(),s=kp(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,u=Oo(()=>i.createToken(l+"@page")),d=i.getCurrentPath(),p=!a,h=wp(!1),g=f=>{h.current=f,t()},m=p&&i.exactMatch(d,n)||i.exactMatch(d,l);if(r&&r!==c)throw new E("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");Si(),Vo(f=>{let v=p&&f.exactMatch(f.getCurrentPath(),n)||f.exactMatch(f.getCurrentPath(),l);if(h.current&&!v){if(!o){g(!1);return}f.registerUnmountingPath(u)}v&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(u),v&&!h.current&&!f.isTransitioning()&&g(!0)},[m,o]),Dc(()=>{if(!m)return;let f=p?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{f.cancel()}},[l,m]),Dc(()=>()=>{i.unregisterUnmountingPath(u),g(!1)},[]);let y=Zr.createElement(Ai,{path:n,consumedBy:c},Zr.createElement(Ho,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),g(!1)}},m&&h.current&&o));return(f=>s?Zr.createElement(es,{value:{name:null}},f):f)(y)}import ts,{useCallback as Ep,useEffect as ns,useImperativeHandle as Dp,useMemo as Lc,useRef as is,useState as Lp}from"react";var Rp=50,Ip={position:"relative",width:"100%",height:"100%",overflow:"hidden"},Rc={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function Mp(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function Ic(o,e){return e==null?o:Math.max(o,e)}function Np(o,e,t){return o<=0||e<=0||t<=0?{width:o,height:e}:o/e>t?{width:e*t,height:e}:{width:o,height:o/t}}var Mc=ts.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:u,children:d},p){let h=is(null),[g,m]=Lp({...Rc,width:"0px",height:"0px"}),y=is(u),T=is(null);ns(()=>{y.current=u},[u]);let f=Ep(()=>{let w=h.current;if(!w)return;let k=w.clientWidth,b=w.clientHeight;if(k<=0||b<=0||e<=0)return;let x=Np(k,b,e),I=Ic(x.width,n),V=Ic(x.height,i),oe=T.current;(!oe||oe.width!==I||oe.height!==V)&&(T.current={width:I,height:V},m({...Rc,width:`${I}px`,height:`${V}px`}));let Ne=t>0?I/t:1;y.current?.({width:I,height:V,scale:Ne,containerWidth:k,containerHeight:b})},[e,t,n,i]),v=Lc(()=>Js(f,typeof r=="number"?r:Rp),[f,r]);ns(()=>{f()},[f]),ns(()=>{let w=new ResizeObserver(()=>{v()});h.current&&w.observe(h.current);let k=()=>{v()};return window.addEventListener("resize",k),()=>{w.disconnect(),window.removeEventListener("resize",k)}},[v]),Dp(p,()=>({requestUpdate:f}),[f]);let A=Lc(()=>Mp(l),[l]);return ts.createElement("div",{id:c,ref:h,style:Ip,...A},ts.createElement("div",{className:s,style:{...g,...a}},d))}),Nc=Mc;function Gp(){return M().getLiveGame()}import ss from"react";import Fp,{createContext as Op,useContext as Hp,useEffect as Vp,useState as Gc}from"react";var Up={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},Fc=Op({state:Up,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function $t(){return Hp(Fc)}function os(){let{dialogs:o}=$t();return o}function Wp(){let{isActive:o}=$t();return o}function Bp(){let{isVisible:o}=$t();return o}function rs({children:o}){let t=M().getLiveGame().getGameState(),[n,i]=Gc(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=Gc(null);Vp(()=>{let c=g=>({...g,dialogs:[...g.dialogs]}),l=t.events.on(L.EventTypes["event:state.nvl.enter"],(g,m)=>{i(c(t.getNvlState())),s(m?.showTransition||null)}),u=t.events.on(L.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState()))}),d=t.events.on(L.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),p=t.events.on(L.EventTypes["event:state.nvl.visibilityChange"],(g,m)=>{i(c(t.getNvlState())),s(m||null)}),h=t.events.on(L.EventTypes["event:state.nvl.change"],g=>{i(c(g))});return()=>{l.cancel(),u.cancel(),d.cancel(),p.cancel(),h.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return Fp.createElement(Fc.Provider,{value:a},o)}import{AnimatePresence as zp,motion as Kp}from"motion/react";import $p from"clsx";function as({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=$t(),{ratio:r}=he(),s=M(),a=i?.duration?i.duration/1e3:.3;return ss.createElement(zp,null,n&&ss.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},ss.createElement(Kp.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:$p("w-full h-full overflow-auto",e),style:{transform:s.config.useAspectScale?`scale(${r.state.scale})`:void 0,transformOrigin:"top left",width:s.config.useAspectScale?s.config.width:"100%",height:s.config.useAspectScale?s.config.height:"100%",...t}},o)))}import En from"react";function cs({renderDialogItem:o,dialogs:e}){return En.createElement(as,{className:"bg-black/80 text-white p-16 inset-8"},En.createElement("div",{"data-element-type":"nvl-dialog-list",className:"flex flex-col space-y-4 p-4"},(e??[]).map((n,i)=>{let r=n.entry.character?En.createElement(en,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=En.createElement(fn,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return En.createElement("div",{key:`${n.entry.id}:${n.isActive?"active":"idle"}`,"data-element-type":"nvl-dialog-item","data-dialog-index":i,className:"nvl-dialog-item"},o?o({entry:n.entry,index:i,isActive:n.isActive,nametag:r,texts:s}):En.createElement(En.Fragment,null,r,s))})))}import Tt,{useMemo as jp}from"react";import Oc from"clsx";function qp({children:o,className:e,style:t,renderDialogItem:n}){let i=os(),{state:r}=$t();return Tt.createElement("div",{"data-element-type":"nvl-dialog-list",className:Oc("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>Tt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},Tt.createElement(Yp,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?Tt.createElement(en,{className:"nvl-character-name font-bold mr-2"}):null,texts:Tt.createElement(fn,{className:"nvl-dialog-text"})}):o?Tt.Children.map(o,c=>Tt.isValidElement(c)?Tt.cloneElement(c,{entry:s,index:a}):c):Tt.createElement(Hc,{entry:s,index:a})))))}function Hc({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??Tt.createElement(fn,{className:"nvl-dialog-text"});return Tt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:Oc("nvl-dialog-item",t),style:n},r&&Tt.createElement(en,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function Yp({entry:o,children:e}){let n=M().getLiveGame().getGameState(),i=jp(()=>o.sentence.evaluate(xe.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=wo({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return Tt.createElement(xn,{value:c},e)}import Uo from"react";import{createPortal as Xp}from"react-dom";var ls=Uo.createContext(null),Qp={Portal:()=>null,measure:()=>null,container:null};function _p(){let o=Uo.useContext(ls);return Uo.useMemo(()=>{if(!o)return Qp;let e=t=>{let n=o.offsetWidth;return!n||!t.width?1:t.width/n};return{container:o,Portal:({children:t})=>Xp(Uo.createElement("div",{style:{position:"absolute",left:0,top:0,pointerEvents:"auto"}},t),o),measure:t=>{if(!t)return null;let n=o.getBoundingClientRect(),i=e(n),r=t.getBoundingClientRect(),s=(r.left-n.left)/i,a=(r.top-n.top)/i,c=r.width/i,l=r.height/i;return{left:s,top:a,width:c,height:l,right:s+c,bottom:a+l}}}},[o])}import{useEffect as Jp}from"react";function Zp(o){let e=M();Jp(()=>{if(!o)return;let t=e.getLiveGame().getGameState();if(t)return t.suspendAdvance()},[o,e])}var Wo=class{constructor(e,t){this.emit=e;this.options=t;this.held=!1;this.delayTimer=null;this.repeatTimer=null}isHeld(){return this.held}press(){this.held||(this.clearTimers(),this.held=!0,this.emit(!1),this.options.delay===0?this.startRepeating():this.delayTimer=setTimeout(()=>{this.delayTimer=null,this.startRepeating()},this.options.delay))}release(){this.clearTimers(),this.held=!1}dispose(){this.release()}startRepeating(){this.repeatTimer=setInterval(()=>{this.emit(!0)},this.options.interval)}clearTimers(){this.delayTimer!==null&&(clearTimeout(this.delayTimer),this.delayTimer=null),this.repeatTimer!==null&&(clearInterval(this.repeatTimer),this.repeatTimer=null)}};function Uc({state:o}){let e=M(),t=Wt(),[n]=mn(te.Preferences.skipDelay),[i]=mn(te.Preferences.skipInterval),[r]=wn("skipAction");return td(()=>{if(!e.getLiveGame().gameState.playerCurrent){o.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){o.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let a=new Wo(u=>{o.events.emit(L.EventTypes["event:state.player.skip"],u)},{delay:n,interval:i}),c=u=>{o.isAdvanceSuspended()||e.keyMap.match("skipAction",u.key)&&e.preference.getPreference(te.Preferences.skip)&&(a.isHeld()||o.logger.verbose("KeyEventAnnouncer","Skipping"),a.press())},l=u=>{e.keyMap.match("skipAction",u.key)&&a.release()};if(e.config.useWindowListener){let u=e.getLiveGame().onWindowEvent("keydown",c).cancel,d=e.getLiveGame().onWindowEvent("keyup",l).cancel;return()=>{a.dispose(),u(),d()}}else{let u=e.getLiveGame().onPlayerEvent("keydown",c).cancel,d=e.getLiveGame().onPlayerEvent("keyup",l).cancel;return()=>{a.dispose(),u(),d()}}},[t,n,i,r]),Vc.createElement(Vc.Fragment,null)}import Bc,{useEffect as nd}from"react";function Wc({onStage:o,dialogShown:e,advanceSuspended:t}){return o?e?t?"ignore":"advance":"restoreDialog":"ignore"}function id(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var zc=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],od=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]','[data-element-type="interactive-word"]','[data-element-type="dialog-overlay"]'];function rd(o,e){return!o||e&&zc.some(t=>!!o.closest(t))?!1:[...od,...zc].some(t=>!!o.closest(t))}function Kc(o,e){if(!e)return!1;let t=e.getBoundingClientRect();return o.clientX>=t.left&&o.clientX<=t.right&&o.clientY>=t.top&&o.clientY<=t.bottom}function $c({state:o}){let e=M();return nd(()=>{let t=e.getLiveGame().gameState?.playerCurrent;if(!t){o.logger.warn("StageClickAnnouncer","Failed to listen to playerElement events");return}let n=i=>{let r=i.target;if(!r||!t.contains(r)||!Kc(i,t))return;let s=o.mainContentNode;if(s&&(!s.contains(r)||!Kc(i,s))||id(r)||rd(r,o.isNvlMode()))return;let a=Wc({onStage:!0,dialogShown:e.preference.getPreference(te.Preferences.showDialog),advanceSuspended:o.isAdvanceSuspended()});if(a!=="ignore"){if(a==="restoreDialog"){e.preference.setPreference(te.Preferences.showDialog,!0);return}o.events.emit(L.EventTypes["event:state.player.stageClick"]),o.recordStageClick()}};if(e.config.useWindowListener){let i=e.getLiveGame().onWindowEvent("click",n);return()=>{i.cancel()}}else{let i=e.getLiveGame().onPlayerEvent("click",n);return()=>{i.cancel()}}},[e,o]),Bc.createElement(Bc.Fragment,null)}import{useEffect as jc}from"react";function us({gameState:o}){let e=o.audioManager,[t,n]=mn("globalVolume");return jc(()=>{n(e.getGlobalVolume())},[]),jc(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as Bo,useRef as sd}from"react";function qc(o){let e=Re.catSrc(o.srcManager?.src||[]),t=Re.catSrc(o.srcManager?.getFutureSrc()||[]),n=[],i=[],r=[],s=new Set,a=o.state?.backgroundImage?.state?.currentSrc;if(P.isImageSrc(a)){let c=P.srcToURL(a);c&&(s.add(c),n.push(c))}for(let c of e.image){let l=Re.getSrc(c);!l||s.has(l)||(s.add(l),i.push(l))}for(let c of t.image){let l=Re.getSrc(c);!l||s.has(l)||(s.add(l),r.push(l))}return{firstFrame:n,critical:i,lookAhead:r,all:[...n,...i,...r],criticalAudio:e.audio}}function Yc({state:o}){let{preloaded:e,cacheManager:t}=Kt(),n=M(),i=sd(new Set),[r]=ae(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function u(){o.logger.debug(s,"Preload unmounted"),e.events.emit($e.EventTypes["event:preloaded.unmount"])}return Bo(()=>o.events.on(L.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),Bo(()=>{if(typeof fetch>"u")return e.events.emit($e.EventTypes["event:preloaded.complete"]),e.events.emit($e.EventTypes["event:preloaded.ready"]),o.logger.warn(s,"Fetch is not supported in this environment, skipping preload"),u;if(!n.config.preloadAllImages)return e.events.emit($e.EventTypes["event:preloaded.complete"]),e.events.emit($e.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),u;if(n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(s,"Cache cleared")),!l||!a)return l?o.logger.debug(s,"Scene not ready yet, waiting for scene before preload"):o.logger.weakWarn(s,"Story not found, skipping preload"),u;let d=performance.now(),p=qc(a),h=new vn(n.config.preloadConcurrency,0),g=new vn(n.config.preloadConcurrency,0),m=new vn(n.config.preloadConcurrency,n.config.preloadDelay),y=o.logger.group(s,!0),T=!1;o.logger.debug(s,"preloading:",p,a);let f=(w,k,b,x)=>{k.forEach((I,V)=>{if(t.has(I)||t.isPreloading(I)){o.logger.debug(s,`Image already loaded (${b} ${V+1}/${k.length})`,I);return}w.addTask(()=>new Promise(oe=>{t.preload(o,I,{retainDecoded:x}).onFinished(()=>{o.logger.debug(s,`Image loaded (${b} ${V+1}/${k.length})`,I),oe()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${b} ${V+1}/${k.length})`,I),oe()})}))})};f(h,p.firstFrame,"first frame",!0),f(g,p.critical,"first scene",!0),f(m,p.lookAhead,"look-ahead",!1);for(let w of p.criticalAudio)o.audioManager.preload(w);y.end();let v=()=>{e.events.emit($e.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit($e.EventTypes["event:preloaded.ready"])},A=n.config.preloadGate!=="scene";return h.start().then(async()=>{o.logger.info(s,"Image preload (first frame)",`loaded ${t.size()} images in ${performance.now()-d}ms`),A&&v(),!T&&(await g.start(),o.logger.info(s,"Image preload (first scene)",`loaded ${t.size()} images in ${performance.now()-d}ms`),A||v(),!T&&(await m.start(),!T&&(o.logger.info(s,"Image preload (look-ahead)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(p.all))))}),n.config.waitForPreload||e.events.emit($e.EventTypes["event:preloaded.ready"]),e.events.emit($e.EventTypes["event:preloaded.mount"]),()=>{T=!0,u()}},[a,l]),Bo(()=>{i.current.clear()},[a]),Bo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let d=performance.now(),p=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(f=>Re.getPreloadableSrc(l,f)).filter(function(f){return f!==null});p.filter(function(f){return f?.activeType==="scene"}).forEach(f=>{i.current.has(f)||i.current.add(f)});let g=Re.catSrc([...i.current,...p]),m=new vn(n.config.preloadConcurrency,n.config.preloadDelay),y=[],T=o.logger.group(s);o.logger.debug(s,"preloading:",g);for(let f of g.image){let v=Re.getSrc(f);if(v){if(y.push(v),t.has(v)||t.isPreloading(v)){o.logger.debug(s,`Image already loaded (${g.image.indexOf(f)+1}/${g.image.length})`,v);continue}m.addTask(()=>new Promise(A=>{t.preload(o,v).onFinished(()=>{o.logger.debug(s,`Image loaded (${g.image.indexOf(f)+1}/${g.image.length})`,v),A()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${g.image.indexOf(f)+1}/${g.image.length})`,v),A()})}))}}T.end(),m.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(y)})},[c,l]),null}import Ci from"react";import Ko from"react";import ps,{useEffect as ds,useLayoutEffect as ms,useRef as zo,useState as fs}from"react";function jt({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c,companionRefs:l}){let[u,d]=fs(null),[p,h]=fs(null),g=zo(null),m=ps.useRef(null),[y]=fs(()=>new Vi("displayable.refGroup")),T=zo(y.next()),f=zo(rt()),A=M().getLiveGame().getGameState(),w=typeof a=="function"?a(u):a,[k]=ae([p,u,f]);ds(()=>A.events.depends([A.events.on(L.EventTypes["event:state.player.skip"],ft)]).cancel,[p,u,f]),ms(()=>{if(V(),!u)return;if(f.current.some(([G])=>!G.current))throw new E("Displayable: Trying to access transition groups before they are mounted");let{controller:N,task:H}=u,D=G=>{f.current.forEach(([ge],De)=>{let st=H.resolve[De],Ge=typeof st=="function"?st:st.resolver;if(!Ge)throw new E(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${De}])`);let Ri=Ge(...G),or=Y(w[De]||w[w.length-1]||{},Ri);Ne(ge,c?c(or):or)})},K=N.onUpdate(D);D(H.animations.map(G=>G.start));let ce=!1;return Promise.all(f.current.map(([G])=>{let ge=G.current;return ge?.waitForLoad?ge.waitForLoad():Promise.resolve()})).then(()=>{ce||N.start()}),()=>{ce=!0,K.cancel()}},[u]),ds(()=>{if(!m.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),ms(()=>{let N=e.toStyle(A,i);return Object.assign(m.current.style,N),I(),A.logger.debug("Displayable","Initial style applied",m.current,N),bt(),()=>{_e()}},[]);let b=zo(()=>{});b.current=()=>{u||!m.current||(V(),!(p||g.current)&&(Object.assign(m.current.style,e.toStyle(A,i)),I()))},ms(()=>{g.current&&!o._getLoop()&&_e(),b.current()});let{ratio:x}=he();ds(()=>x.onUpdate(()=>{b.current(),requestAnimationFrame(()=>b.current())}),[x]);function I(){if(l)for(let{ref:N,project:H}of l)N.current&&Object.assign(N.current.style,H(e.get()))}function V(){let N=typeof a=="function"?a(u):a;if(!f.current||!f.current.length)throw new E("Displayable: Transition group refs are not initialized correctly");f.current.some(([H])=>!H.current)||f.current.forEach(([H],D)=>{Ne(H,N[D]||N[N.length-1]||{})})}function oe(N){A.logger.debug("Displayable","Transform applied",e.toStyle(A,i),m.current),k(),r?.(N)}function Ne(N,H){if(!N.current)throw new E("Displayable: Trying to assign properties to unmounted element");oo(N.current,H,c)}function _e(){g.current&&(g.current.stop(),g.current=null,A.logger.debug("Displayable","Loop stopped",o))}function bt(){let N=o._getLoop();if(!N){_e();return}g.current||At(N.transform,N.options)}function At(N,H){p&&(p.abort(),h(null)),_e(),m.current&&(g.current=N.startLoop(e,{gameState:A,ref:m,overwrites:i,companionRefs:l},H))}function gn(N,H){return mt(new Z({},{duration:N?.duration??0,ease:N?.ease??"linear"}),H)}function mt(N,H){p&&(p.abort(),h(null)),_e();let D=N.animate(e,{gameState:A,ref:m,overwrites:i,companionRefs:l}),K=new we(D);return A.timelines.attachTimeline(K),D.onSkipControllerRegister(ce=>{ce.onAbort(()=>{K.abort(),h(null)})}),h(D),D.then(()=>{h(null),oe(N),H(),bt()}),K}function B(N,H){u&&u.controller.complete();let D=N.createTask(A),K=N.requestAnimations(D.animations),ce=new S().registerSkipController(new U(K.cancel)),G=new we(ce);ce.skipController.onAbort(()=>{K.cancel()}),K.onCanceled(()=>{G.abort(),d(null),A.logger.debug("Displayable","Transition cancelled",N)}),K.onComplete(()=>{Ue(),d(null),s?.(N),H(),ce.resolve()}),A.timelines.attachTimeline(G),d({task:D,controller:K,transition:N,resolve:H});let ge;if(f.current=D.resolve.map(De=>{let st=ps.createRef(),Ge=typeof De=="function"?void 0:De.key;if(!Ge)return[st,y.next()];if(Ge==="target")return ge=y.next(),[st,ge];if(Ge==="current")return[st,T.current];throw new E("Displayable: Invalid key type")}),!ge)throw new E("Displayable: No target key found");return T.current=ge,G}function Ee(N){return A.logger.debug("initDisplayable",o),mt(Z.immediate(e.get()),N)}function ft(){t&&p&&(p.abort(),h(null),A.logger.debug("transform skipped")),n&&u&&(u.controller.complete(),A.logger.debug("transition skipped"))}function rt(){return[[ps.createRef(),T.current]]}function Ue(){f.current.forEach(([N])=>{N.current=null}),f.current=rt()}return{transformRef:m,transitionRefs:f.current,transitionTask:u,initDisplayable:Ee,applyTransform:mt,applyTransition:B,applyLoop:At,stopLoop:gn,updateStyleSync:V,flush:k,deps:[p,u,f]}}import{useEffect as ad}from"react";function xt(o,e,t=[]){let i=M().getLiveGame().getGameState();return ad(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function hs({state:o,text:e}){let{ratio:t}=he(),[n]=ae(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyLoop:c,stopLoop:l,applyTransition:u,updateStyleSync:d,deps:p}=jt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:h=>({width:"fit-content",transform:Z.propToCSSTransform(o,h,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return xt(e,{initDisplayable:s,applyTransform:a,applyLoop:c,stopLoop:l,applyTransition:u,flush:n,updateStyleSync:d},[...p]),Ko.createElement(zt.Div,{"data-element-type":"text"},Ko.createElement(zt.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([h,g])=>Ko.createElement("span",{key:g,ref:h,className:e.config.className},Ko.createElement("span",null,e.state.text)))))}import Nt,{forwardRef as ld,useCallback as Qc,useImperativeHandle as ud,useRef as qo,useState as _c}from"react";import $o,{useEffect as gs,useRef as Kn,forwardRef as cd}from"react";var Xc=cd(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=Kn(null),{ratio:a}=he(),[c,l]=$o.useState(0),[u,d]=$o.useState(0),p=Kn(null),h=Kn(null),g=M(),m=Kn(!1),y=Kn(null),T=Kn(null);$o.useImperativeHandle(r,()=>s.current,[]),gs(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>{let w=()=>{let k=s.current;return!k||typeof k.decode!="function"?Promise.resolve():k.decode().catch(()=>{})};return m.current?w():(y.current||(y.current=new Promise(k=>{T.current=k})),y.current.then(w))},configurable:!0}})},[]),gs(()=>(f(),a.onUpdate(f)),[o]),gs(()=>{let w=new MutationObserver(k=>{k.forEach(b=>{b.type==="attributes"&&b.attributeName==="src"&&s.current&&f()})});return s.current&&w.observe(s.current,{attributes:!0}),()=>{w.disconnect()}},[o]);function f(){if(s.current&&s.current.naturalWidth){let w,k,b;if(s.current.naturalWidth*s.current.naturalHeight===1)w=a.state.width,k=a.state.height,b=`${w} / ${k}`;else{let oe=t?g.config.width/s.current.naturalWidth:1;w=s.current.naturalWidth*a.state.scale*oe,k=s.current.naturalHeight*a.state.scale*oe,b="auto"}let x=p.current,I=!x||x.w!==w||x.h!==k||x.ar!==b,V=!!o&&h.current!==o;if(!I&&!V)return;I&&(p.current={w,h:k,ar:b},l(w),d(k),s.current.style.aspectRatio=b),o&&(h.current=o,o(w,k))}}function v(){f(),m.current=!0,T.current&&(T.current(),T.current=null,y.current=null),e&&e()}function A(){m.current=!0,T.current&&(T.current(),T.current=null,y.current=null)}return $o.createElement("img",{ref:s,onLoad:v,onError:A,width:c,height:u,alt:"",src:n,style:i})});Xc.displayName="AspectScaleImage";var jo=Xc;import Jc from"clsx";import{motion as pd}from"motion/react";var dd={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},Zc=ld(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=qo(null),a=qo([]),c=o.findIndex(l=>l!==null);return ud(r,()=>Object.assign(s.current,{isLoaded:()=>a.current.every(l=>!l?.isLoaded||l.isLoaded()),waitForLoad:()=>Promise.all(a.current.map(l=>l?.waitForLoad?l.waitForLoad():Promise.resolve())).then(()=>{})}),[]),Nt.createElement("div",{ref:s},o.map((l,u)=>l===null?null:Nt.createElement(jo,{key:"layer-"+u,ref:d=>{a.current[u]=d},src:t(l),style:dd,autoFit:e,onSizeChanged:u===c?n:void 0,onLoad:u===c?i:void 0})))});Zc.displayName="LayerStack";function md(o){return{willChange:"filter, opacity",position:"absolute",top:0,left:0,right:0,bottom:0,transform:"none",translate:"none",opacity:1,clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat",filter:`brightness(${1-o})`}}function fd(o){return F.isStaticSrc(o)?o.state.currentSrc:F.getSrcURL(o)??void 0}var hd={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function gd({image:o,state:e}){let[t]=_c(()=>new _),[n,i]=_c([]),{cacheManager:r}=Kt(),s=qo([]),a=qo(null),c=F.isLayeredSrc(o)?F.getSrcURLs(o):null;function l(b){return!P.isInlineSrc(b)&&!r.has(b)&&!r.isPreloading(b)&&!s.current.includes(b)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${b}".
|
|
62
62
|
This may be caused by complicated image action behavior that cannot be predicted.
|
|
63
|
-
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(b)),r.get(b)||b}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:h,applyTransition:g,applyTransform:m,applyLoop:y,stopLoop:T,updateStyleSync:f,flush:v,deps:A}=jt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:b=>{if(c)return(b?b.task.resolve:[null]).map(V=>V&&typeof V=="function"?{style:fd}:{style:dd(o.state.darkness)});let x=b?b.transition._getCurrentSrc():md(o);return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:P.isColor(x)?P.colorToString(x):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:P.isImageSrc(x)?P.srcToURL(x):F.DefaultImagePlaceholder},{style:{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none",filter:"brightness(1)"}}]},propOverwrite:b=>b.src?{...b,src:l(b.src)}:b});xt(o,{createWearable:b=>{i(x=>[...x,b])},disposeWearable:b=>{i(x=>x.filter(I=>I.getId()!==b.getId()))},initDisplayable:h,applyTransform:m,applyLoop:y,stopLoop:T,applyTransition:g,events:t,updateStyleSync:f,flush:v},[...A]);let w=Qc((b,x)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${b}px`,height:`${x}px`}))},[t]),k=Qc(()=>{t.emit("event:image.onLoad")},[t]);return Nt.createElement(ud.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},Nt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?d.map(([b,x],I)=>{let V=p?p.task.resolve[I]:null;if(V&&typeof V=="function")return Nt.createElement(jo,{key:x,ref:b,autoFit:o.config.autoFit});let oe=V?V.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():c;return Nt.createElement(Zc,{key:x,ref:b,src:oe||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:I===0?w:void 0,onLoad:I===0?k:void 0})}):d.map(([b,x],I)=>Nt.createElement(jo,{key:x,ref:b,autoFit:o.config.autoFit,onSizeChanged:I===0?w:void 0,onLoad:I===0?k:void 0})),Nt.createElement("div",{className:Jc("w-full h-full top-0 left-0 absolute")},n.map(b=>Nt.createElement("div",{className:Jc("w-full h-full relative"),key:"wearable-"+b.getId()},Nt.createElement(el,{image:b,state:e}))))))}var el=Nt.memo(hd),tl=el;import Xo,{useEffect as il,useMemo as Td,useRef as ys}from"react";var gd=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,yd=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function nl(o,e){if(typeof e!="string"||!e.length)return o;if(gd.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=vd(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+Sd(r+e.replace(/\\/g,"/"))}function vd(o){let e=yd.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function Sd(o){let e=o.split("/"),t=[];for(let n=0;n<e.length;n++){let i=e[n];if(!(i==="."||i===""&&n!==e.length-1)){if(i===".."){t.pop();continue}t.push(i)}}return t.join("/")}var Yo=class{constructor(){this.backends=new Map;this.reportedMissing=new Set}register(e){if(!e||typeof e.name!="string"||!e.name.length)throw new Error("A puppet backend must have a non-empty name.");if(typeof e.mount!="function")throw new Error(`Puppet backend "${e.name}" must implement mount().`);return this.backends.set(e.name,e),this.reportedMissing.delete(e.name),this}get(e){return this.backends.get(e)||null}has(e){return this.backends.has(e)}list(){return Array.from(this.backends.keys())}unregister(e){return this.backends.delete(e)}reportMissing(e,t){return this.reportedMissing.has(e)?!1:(this.reportedMissing.add(e),t(`No puppet backend is registered under "${e}". The element keeps its place on the stage, its transform and its saved state, but draws nothing. Register one with game.registerPuppetBackend({name, mount}) before the game mounts.`),!0)}};function vs({state:o,puppet:e}){let[t]=ae(),{cacheManager:n}=Kt(),i=ys(null),r=Td(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=ys(r);s.current=r;let{transformRef:a,transitionRefs:c,initDisplayable:l,applyTransform:u,applyLoop:d,stopLoop:p,applyTransition:h,updateStyleSync:g,deps:m}=jt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipImageTransform,skipTransition:o.game.config.allowSkipImageTransition,transitionsProps:[{style:{position:"relative",width:`${r.width}px`,height:`${r.height}px`}}]});xt(e,{initDisplayable:l,applyTransform:u,applyLoop:d,stopLoop:p,applyTransition:h,updateStyleSync:g,flush:t},[...m]),il(()=>{let f=i.current;if(!f)return;let v=o.game,A=e.config.backend,w=v.getPuppetBackend(A);if(!w)return e._setStatus("missing-backend"),v.getPuppetBackendRegistry().reportMissing(A,x=>{o.logger.warn("Puppet",x)}),()=>{e._setStatus("unmounted")};let k;try{k=w.mount(f,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:T,resolveSibling:x=>T(nl(e.config.src,x)),warn:(x,I)=>{o.logger.warn("Puppet",x,I)}})}catch(x){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${A}" threw while mounting "${e.config.src}"`,x),()=>{e._setStatus("unmounted")}}let b=!1;return e._attachInstance(k),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!b&&typeof k.ready=="function"?k.ready():void 0).then(()=>{b||e._setStatus("ready")}).catch(x=>{b||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${A}" failed to load "${e.config.src}"`,x))}),()=>{b=!0,e._attachInstance(null),e._setStatus("unmounted");try{k.dispose()}catch(x){o.logger.error("Puppet",`Backend "${A}" threw while disposing`,x)}}},[]);let y=ys(r);il(()=>{let f=y.current;if(f.width===r.width&&f.height===r.height)return;y.current=r;let v=e._getInstance();if(!(!v||typeof v.resize!="function"))try{v.resize(r)}catch(A){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,A)}},[r]);function T(f){return P.isDataURI(f)?f:n.get(f)||f}return Xo.createElement(zt.Div,{"data-element-type":"puppet"},Xo.createElement(zt.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},c.map(([f,v])=>Xo.createElement("div",{key:v,ref:f,className:e.config.className},Xo.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function Ss({state:o,displayable:e}){return Ci.createElement(Ci.Fragment,null,e.map(t=>{if(t instanceof Cn)return Ci.createElement(hs,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof F)return Ci.createElement(tl,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof Lt)return Ci.createElement(vs,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Qo,{useEffect as bd}from"react";import{motion as Ad}from"motion/react";function ol({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:c,stopLoop:l,updateStyleSync:u,deps:d}=jt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return xt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:c,stopLoop:l,updateStyleSync:u},[...d]),bd(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Qo.createElement(Qo.Fragment,null,Qo.createElement(Ad.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([p,h])=>Qo.createElement("div",{className:"relative w-full h-full",ref:p,key:h},t))))}async function rl(o,e,t,n){let i=e.state.backgroundMusic,r=i&&o.audioManager.isManaged(i)?o.audioManager.stop(i,n):null;if(r&&t===i&&await r,t)try{await o.audioManager.playSoundToken(t,{end:t.state.volume,duration:n}),e.state.backgroundMusic=t}catch{e.state.backgroundMusic=null}else e.state.backgroundMusic=null;r&&await r}import Cd from"clsx";import{useEffect as Ts,useRef as xd}from"react";import bs from"react";function As({state:o,className:e,elements:t}){let{scene:n,layers:i}=t,r=xd(null);return Ts(()=>(o.stageTransition.registerScene(n,r.current),()=>{o.stageTransition.registerScene(n,null)}),[]),Ts(()=>n.events.depends([n.events.on(Ye.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),Ts(()=>(n.events.emit(Ye.EventTypes["event:scene.mount"]),o.events.emit(L.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(Ye.EventTypes["event:scene.unmount"]),o.events.emit(L.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),xt(n,{setBackgroundMusic(s,a){return rl(o,n,s,a)}}),bs.createElement("div",{className:Cd(e,"w-full h-full absolute"),ref:r,"data-element-type":"scene","data-scene-id":n.getId()},[...i.entries()].sort(([s],[a])=>s.state.zIndex-a.state.zIndex).map(([s,a])=>bs.createElement(ol,{state:o,layer:s,key:s.getId()},bs.createElement(Ss,{state:o,displayable:a}))))}import{AnimatePresence as Ed}from"motion/react";import{useEffect as Dd,useReducer as Ld,useRef as _o}from"react";import wd from"clsx";import qt,{useCallback as Cs,useMemo as kd,useRef as Pd}from"react";function xs({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=M(),a=Pd([]),c=Cs(g=>(a.current.push(g),a.current.indexOf(g)),[]),l=Cs(g=>{let m=a.current.indexOf(g);m!==-1&&a.current.splice(m,1)},[]),u=Cs(g=>a.current.indexOf(g),[]),d=s.config.menu,p=kd(()=>e.map(g=>({...g,words:g.prompt.evaluate(xe.getCtx({gameState:n}))})),[e,n]);function h(g){t(g)}return qt.createElement(qt.Fragment,null,qt.createElement(jr,{value:{evaluated:p,choose:h,gameState:n}},qt.createElement(Yr,{value:{register:c,unregister:l,getIndex:u}},qt.createElement(Bt,{className:"absolute"},r&&o&&qt.createElement(hi,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),qt.createElement(zt.Div,{color:"green",border:"dashed",className:wd("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},qt.createElement(d,{items:p.map((g,m)=>m)})))))}function sl({items:o}){return qt.createElement(bo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>qt.createElement(Io,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import Rd from"clsx";import xi from"react";var al=120;function cl({sources:o,menuCount:e,presence:t,retained:n,lastActive:i,sceneId:r}){if(o.length===0){let c=n??(i.length>0?i.map(l=>({...l,active:!1})):null);return{items:c??[],retained:c,lastActive:i,retaining:c!==null,interactive:e>0}}let s=new Set(o.map(({slot:c})=>c));for(let[c,l]of Array.from(t.slotKeys))s.has(c)||(t.exitingKeys.add(l),t.slotKeys.delete(c));let a=o.map(({slot:c,...l})=>{let u=t.slotKeys.get(c);return(!u||t.exitingKeys.has(u))&&(u=`say-${r}-${t.nextKey++}`,t.slotKeys.set(c,u)),{...l,presenceKey:u,slot:c,active:!0}});return{items:a,retained:null,lastActive:a,retaining:!1,interactive:!0}}function ws({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=_o({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),a=_o([]),c=_o(null),l=_o(null),[,u]=Ld(y=>y+1,0),d=()=>{l.current&&(clearTimeout(l.current),l.current=null)},p=()=>{let y=c.current;if(!y)return;let T=s.current;y.forEach(({slot:f,presenceKey:v})=>{T.slotKeys.get(f)===v&&T.slotKeys.delete(f),T.exitingKeys.add(v)}),c.current=null,l.current=null,a.current=[],u()};Dd(()=>()=>{d()},[]);let h=s.current,g=i.length>0?i.map(({action:y,onClick:T},f)=>({action:y,slot:f,useTypeEffect:!0,onFinished:()=>{T(),o.events.emit(L.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((y,T)=>{if(!y.action.prompt||!y.action.words)return[];let f=h.menuPromptIds.get(y);return f||(f=`menu-prompt-${n.getId()}-${h.nextKey++}`,h.menuPromptIds.set(y,f)),[{action:{sentence:y.action.prompt,words:y.action.words,character:null,id:f},slot:T,useTypeEffect:!1}]}),m=cl({sources:g,menuCount:r.length,presence:h,retained:c.current,lastActive:a.current,sceneId:n.getId()});return c.current=m.retained,a.current=m.lastActive,m.retaining?l.current||(l.current=setTimeout(p,al)):d(),xi.createElement("div",{className:Rd(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs",style:{pointerEvents:m.interactive?"auto":"none"}},xi.createElement(Ed,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{s.current.exitingKeys.clear()}},m.items.map(({action:y,onFinished:T,presenceKey:f,active:v,useTypeEffect:A})=>xi.createElement(hi,{gameState:o,key:f,action:y,active:v,onFinished:T,useTypeEffect:A}))),r.map(({action:y,onClick:T},f)=>xi.createElement("div",{key:"menu-"+f,"data-element-type":"menu"},xi.createElement(xs,{state:o,prompt:y.prompt,choices:y.choices,renderPrompt:!y.prompt,afterChoose:v=>{T(v),o.stage.next()},words:y.words}))))}import hn,{useEffect as Id,useRef as ks}from"react";import{motion as Md}from"motion/react";function ll({state:o,camera:e,children:t}){let n=ks(null),i=ks(null),r=ks(null),{transformRef:s,transitionRefs:a,initDisplayable:c,applyTransition:l,applyTransform:u,applyLoop:d,stopLoop:p,updateStyleSync:h,deps:g}=jt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,companionRefs:[{ref:n,project:La},{ref:i,project:Ea},{ref:r,project:Da}],transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return xt(e,{initDisplayable:c,applyTransition:l,applyTransform:u,applyLoop:d,stopLoop:p,updateStyleSync:h},[...g]),Id(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),hn.createElement(hn.Fragment,null,hn.createElement(Md.div,{className:"absolute w-full h-full",ref:s,"data-element-type":"camera"},a.map(([m,y])=>hn.createElement("div",{className:"relative w-full h-full",ref:m,key:y},t))),hn.createElement("div",{className:"absolute w-full h-full","data-element-type":"camera-lens",style:{pointerEvents:"none"}},hn.createElement("div",{className:"absolute w-full h-full",ref:n,"data-element-type":"camera-lens-vignette"}),hn.createElement("div",{className:"absolute w-full h-full",ref:i,"data-element-type":"camera-lens-shutter-top"}),hn.createElement("div",{className:"absolute w-full h-full",ref:r,"data-element-type":"camera-lens-shutter-bottom"})))}import Nd from"react";import{useEffect as Ps,useRef as Gd}from"react";import{useCallback as ul}from"react";function pl(o){let e=ul(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=ul(()=>{if(!o.current)return;let n=o.current;n.style.opacity="0",n.style.pointerEvents="none",n.style.visibility="hidden"},[o]);return{show:e,hide:t}}function Es({gameState:o,video:e}){let t=Gd(null),{show:n,hide:i}=pl(t);Ps(()=>o.events.depends([o.events.on(L.EventTypes["event:state.player.skip"],()=>{o.game.config.allowSkipVideo&&(r(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),Ps(()=>{i(),e.state.display&&n()},[]),Ps(()=>{if(!t.current)return;let s=t.current,a=!1,c=new Set,l=()=>new E(`Failed to add event listener, ref is not available
|
|
64
|
-
at Video.tsx: useEffect`),u=h=>{a||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw l();n()},hide:()=>{if(!t.current)throw l();i()},play:()=>{if(!t.current)throw l();let g=t.current;return h||g.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(g.currentTime=0,new Promise(m=>{let y=!1,T=null,f=[],v=()=>{y||(y=!0,c.delete(v),T&&T(),f.forEach(A=>A()),m())};c.add(v),T=o.schedule(({retry:A})=>{if(y)return;if(g.readyState<3){let x=()=>{g.removeEventListener("loadeddata",x),A()};g.addEventListener("loadeddata",x),f.push(()=>g.removeEventListener("loadeddata",x));return}let w=()=>v(),k=()=>v(),b=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),v()};g.addEventListener("ended",w),g.addEventListener("stopped",k),g.addEventListener("error",b),f.push(()=>{g.removeEventListener("ended",w),g.removeEventListener("stopped",k),g.removeEventListener("error",b)}),g.play().catch(x=>{o.logger.error("Failed to play video: "+x),v()})},10)}))},pause:()=>{if(!t.current)throw l();t.current.pause()},resume:()=>{if(!t.current)throw l();return t.current.play().catch(g=>{o.logger.error("Failed to resume video: "+g)})},stop:()=>{if(!t.current)throw l();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:g=>{if(!t.current)throw l();t.current.currentTime=g}}))},d=()=>u(!1),p=()=>{o.logger.error("NarraLeaf-React: Video",`Failed to load video source: ${e.config.src}`+(s.error?` (media error code ${s.error.code})`:"")),u(!0)};return s.addEventListener("canplay",d),s.addEventListener("error",p),s.readyState>=3?u(!1):s.error&&p(),()=>{s.removeEventListener("canplay",d),s.removeEventListener("error",p),c.forEach(h=>h()),s.currentTime>0&&s.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]);function r(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return Nd.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:s=>s.preventDefault()})}import Fd,{useEffect as Od,useRef as Hd}from"react";var dl={linear:"linear",easeIn:"cubic-bezier(0.42, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.58, 1)",easeInOut:"cubic-bezier(0.42, 0, 0.58, 1)"};function Vd(o,e){return e===void 0?"linear":Array.isArray(e)?`cubic-bezier(${e.join(", ")})`:typeof e=="string"&&dl[e]?dl[e]:(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease")}function Ds({gameState:o,vfx:e}){let t=Hd(null);return Od(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,c=new Set,l=new Set,u=[],d=A=>{n.style.transition="",n.style.opacity=String(A)},p=()=>{n.play().catch(A=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+A)})},h=()=>i||n.error?(o.logger.error("NarraLeaf-React: Vfx","Cannot wait for a vfx whose source failed to load: "+e.config.src),Promise.resolve()):n.readyState>=2?Promise.resolve():new Promise(A=>{let w=!1,k=()=>x(),b=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),x()},x=()=>{w||(w=!0,l.delete(x),n.removeEventListener("loadeddata",k),n.removeEventListener("error",b),A())};l.add(x),n.addEventListener("loadeddata",k),n.addEventListener("error",b),(n.readyState>=2||n.error)&&x()}),g=(A,w,k)=>{let b=w?.duration??0,x=++s;return k.instant||b<=0?(d(A),Promise.resolve()):new Promise(I=>{let V=!1,oe=null,Ne=()=>{V||(V=!0,l.delete(Ne),oe!==null&&clearTimeout(oe),s===x&&t.current&&d(A),I())};l.add(Ne),n.style.transition=`opacity ${b}ms ${Vd(o,w?.easing)}`,n.offsetWidth,n.style.opacity=String(A),oe=setTimeout(Ne,b)})},m=A=>{r||(r=!0,i=A,o.mountState(e,{show:async w=>{a=!0;let k={instant:!1};c.add(k);try{if(await h(),!t.current)return;n.playbackRate=w?.rate??e.config.playbackRate,e.state.paused||p(),await g(w?.opacity??e.config.opacity,w,k)}finally{c.delete(k)}},hide:async w=>{a=!0;let k={instant:!1};c.add(k);try{await g(0,w,k),t.current&&n.pause()}finally{c.delete(k)}},pause:()=>{n.pause()},resume:()=>{p()},setRate:w=>{n.playbackRate=w}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&d(e.config.opacity)},0)))},y=()=>m(!1),T=()=>{o.logger.error("NarraLeaf-React: Vfx",`Failed to load vfx source: ${e.config.src}`+(n.error?` (media error code ${n.error.code})`:"")),m(!0)},f=o.events.on(L.EventTypes["event:state.player.skip"],()=>{c.size===0&&l.size===0||(c.forEach(A=>{A.instant=!0}),[...l].forEach(A=>A()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),v=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&t.current&&p()};return document.addEventListener("visibilitychange",v),n.style.opacity="0",n.playbackRate=e.config.playbackRate,e.config.muted||o.logger.weakWarn("NarraLeaf-React: Vfx","Vfx is not muted; autoplay may be rejected by the browser. (src: "+e.config.src+")"),e.state.display&&!e.state.paused&&p(),n.addEventListener("canplay",y),n.addEventListener("error",T),n.readyState>=3?m(!1):n.error&&T(),()=>{n.removeEventListener("canplay",y),n.removeEventListener("error",T),document.removeEventListener("visibilitychange",v),f.cancel(),u.forEach(A=>A()),[...l].forEach(A=>A()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),Fd.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,loop:e.config.loop,playsInline:!0,onContextMenu:n=>n.preventDefault(),style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:e.config.fit,pointerEvents:"none"}})}import Ud from"clsx";import Wd,{useCallback as Bd,useEffect as Jo,useRef as zd}from"react";function Ls({children:o,className:e,gameState:t}){let{ratio:n}=he(),i=M(),[r]=ae(),s=zd(null),a=i.config.minWidth,c=i.config.minHeight,l=Bd(u=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(u.width,u.height,u.scale),n.updateMin(a,c),r()},[r,t.logger,c,a,n]);return Jo(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Jo(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Jo(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Jo(()=>t.events.on(L.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),Wd.createElement(Nc,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:Ud(e),onUpdate:l},o)}import ml,{useEffect as Kd,useRef as $d,useState as fl}from"react";function Rs({src:o,width:e,height:t}){let[n,i]=fl({x:0,y:0}),[r,s]=fl(!1),a=$d(null),{ratio:c}=he();return Kd(()=>{let l=u=>{if(a.current){let d=a.current.getBoundingClientRect(),p=u.clientX-d.left,h=u.clientY-d.top;i({x:p,y:h}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),ml.createElement(Bt,{ref:a,className:"overflow-hidden absolute"},ml.createElement("img",{src:o,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:r?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import hl from"react";import tn from"react";function Is({error:o,errorInfo:e}){return M().config.app.debug?tn.createElement("div",{className:"text-left"},tn.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),tn.createElement("p",{className:"text-red-700"},"Message: ",o.message),tn.createElement("pre",null,"Error Stack: ",o?.stack),tn.createElement("pre",null,"Component Stack: ",e?.componentStack),tn.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):tn.createElement("div",{className:"bg-white w-full h-full"},tn.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),tn.createElement("p",null,"Please contact the game developer for further assistance."))}var Zo=class extends hl.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t,errorInfo:null}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n}),this.props.onError?.(t,n),console.error(t,n)}render(){return this.state.hasError?hl.createElement(Is,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import vl from"clsx";import W,{useEffect as Gt,useReducer as Sl,useState as $n}from"react";import{flushSync as Tl}from"react-dom";import{useRef as jd}from"react";import{useEffect as qd}from"react";function gl({gameState:o}){let e=jd(null);return qd(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(L.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import wi,{useEffect as Yd}from"react";function Ms({gameState:o}){let[e]=ae(),{ratio:t}=he(),n=o.notificationMgr;Yd(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return wi.createElement("div",{style:{transform:`scale(${t.state.scale})`,transformOrigin:"left top"},className:"absolute top-0 left-0 w-full h-full pointer-events-none","data-element-type":"notification"},wi.createElement(i,{notifications:n.toArray()}))}function yl({notifications:o}){return wi.createElement(No,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>wi.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},wi.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function bl({story:o=ai.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:u,active:d=!0}){let[p,h]=Sl(D=>D+1,0),[g,m]=Sl(D=>D+1,0),[y,T]=$n(0),f=M(),[v]=$n(()=>new L(f,{update:h,forceUpdate:()=>{v.logger.weakWarn("Player","force update"),Tl(()=>{h()})},forceRemount:()=>{v.logger.weakWarn("Player","force remount"),Tl(()=>{T(D=>D+1),h()})},next:Ue})),A=W.createRef(),w=W.createRef(),[k,b]=$n(!1),x=W.useRef(!1),I=W.useRef(null),V=W.useRef(null),{preloaded:oe}=Kt(),[Ne,_e]=$n(!1),bt=W.useRef(!1),[At,gn]=$n(!1),mt=W.useRef(!1),B=W.useRef(null),Ee=W.useRef(!1),[ft]=$n(new Map);function rt(D){return{game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable(),scene:D}}function Ue(){let D=()=>{ft.forEach(G=>G.cancel())};if(v.rollLock.isLocked())return;D();let K=!1,ce=0;for(;!K;){if(ce++>f.config.maxStackModelLoop)throw new E("Max stack model loop reached");let G=f.getLiveGame().next();if(!G){if(f.getLiveGame().stackModel&&!f.getLiveGame().stackModel.isEmpty())continue;break}if(S.isAwaitable(G)){if(I.current===G)break;I.current=G,G.onSettled(()=>{G.isFailed()||(I.current===G&&(I.current=null),Ue())}),G.onFailed(ge=>{I.current===G&&(I.current=null),v.logger.error("Player",ge)}),K=!0;break}if(G instanceof Ln){if(V.current===G)break;V.current=G,G.nextUnlock().then(()=>{V.current===G&&(V.current=null),Ue()}),K=!0;break}if(Xe.isCalledActionResult(G)&&G.wait&&Xe.isStackModelsAwaiting(G.wait.type,G.wait.stackModels)){if(I.current===G)break;if(I.current=G,G.wait){let ge=Xe.executeStackModelGroup(G.wait.type,G.wait.stackModels);ge.then(()=>{I.current===G&&(I.current=null),Ue()}),ge.onFailed(De=>{I.current===G&&(I.current=null),v.logger.error("Player",De)})}K=!0;break}v.handle(G)}v.stage.update()}Gt(()=>{v.audioManager.initialize()},[]),Gt(()=>(f.getLiveGame().setGameState(v),o&&!f.getLiveGame().isPlaying()&&f.getLiveGame().loadStory(o),o?.entryScene&&!v.getPreloadingScene()&&!v.getLastScene()&&v.preloadScene(o.entryScene),v.playerCurrent=A.current,v.mainContentNode=w.current,()=>{f.getLiveGame().setGameState(void 0),v.playerCurrent=null}),[f,o]),Gt(()=>ct(()=>{b(!0);let D=v.getLastScene(),K=[];D?K.push(D.events.once("event:scene.mount",()=>{v.stage.next()}).cancel):v.stage.next();let ce=v.events.on(L.EventTypes["event:state.end"],()=>{c&&c({game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable()})});return v.stage.update(),()=>{D&&K.forEach(G=>G()),ce.cancel()}}),[]),Gt(()=>ct(()=>{k&&i&&!x.current&&(x.current=!0,v.stage.forceUpdate(),f.hooks.trigger("init",[]),i({game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable()}))}),[k]),Gt(()=>ct(()=>{if(Ne&&s&&!bt.current){bt.current=!0;let D=B.current||v.getLastScene()||v.getPreloadingScene(),K=rt(D);s(K)}}),[Ne]),Gt(()=>ct(()=>{if(At&&!mt.current){mt.current=!0;let D=B.current||v.getLastScene()||v.getPreloadingScene(),K=rt(D);f.markPreloadComplete(K)&&r&&r(K)}}),[At]),Gt(()=>v.events.on(L.EventTypes["event:state.scene.mount"],D=>{B.current||(B.current=D,m())}).cancel,[]),Gt(()=>{if(!At||!d||Ee.current||f.isFirstSceneReady())return;let D=B.current||v.getLastScene();if(!D)return;let K=null,ce=null,G=!1;Ee.current=!0;let ge=()=>{G=!0,Ee.current=!1;let De=rt(D);f.markFirstSceneReady(De)&&a&&a(De)};return typeof requestAnimationFrame=="function"?K=requestAnimationFrame(()=>{ce=setTimeout(ge,0)}):ce=setTimeout(ge,0),()=>{G||(Ee.current=!1,K!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(K),ce!==null&&clearTimeout(ce))}},[d,g,p,At]),Gt(()=>oe.events.depends([oe.events.on($e.EventTypes["event:preloaded.ready"],()=>{_e(!0),v.stage.update(),o&&f.getLiveGame().isPlaying()&&Ue()}),oe.events.on($e.EventTypes["event:preloaded.complete"],()=>{gn(!0)})]).cancel,[]),Gt(()=>{v.flushDep=p},[p]);let N=e||f.config.width,H=t||f.config.height;return W.createElement(Zo,{onError:l},W.createElement("div",{style:{width:typeof N=="number"?`${N}px`:N,height:typeof H=="number"?`${H}px`:H},className:vl(n,"__narraleaf_content-player"),ref:A,tabIndex:0},W.createElement(Ls,{className:vl("flex-grow overflow-auto"),gameState:v},W.createElement(us,{gameState:v}),W.createElement(gl,{gameState:v}),W.createElement(Bt,{className:"absolute",ref:w,style:{cursor:v.game.config.cursor?"none":"auto",overflow:v.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},f.config.cursor&&W.createElement(Rs,{src:f.config.cursor,width:f.config.cursorWidth,height:f.config.cursorHeight}),W.createElement(Xd,{show:Ne&&d,key:y},W.createElement(rs,null,W.createElement(Uc,{state:v}),W.createElement($c,{state:v}),W.createElement(Qd,{state:v},W.createElement("div",{className:"w-full h-full absolute",style:{isolation:"isolate"},"data-element-type":"scene-group"},v.getSceneElements().map(D=>W.createElement(As,{key:"scene-"+D.scene.getId(),state:v,elements:D}))),W.createElement(_d,{state:v}),v.getVideos().map((D,K)=>W.createElement("div",{className:"w-full h-full absolute",key:"video-"+K,"data-element-type":"video"},W.createElement(Es,{gameState:v,video:D}))),v.getVfx().map(D=>W.createElement("div",{className:"w-full h-full absolute",key:"vfx-"+D.getId(),"data-element-type":"vfx",style:{zIndex:D.config.zIndex,mixBlendMode:D.config.blendMode}},W.createElement(Ds,{gameState:v,vfx:D})))),v.getSceneElements().map(D=>W.createElement(ws,{key:"scene-dialogs-"+D.scene.getId(),state:v,elements:D})),W.createElement(Jd,{NvlComponent:f.config.nvlDialog}))),W.createElement(Yc,{state:v}),W.createElement(Ec,null,u),W.createElement(Ms,{gameState:v})))))}function Xd({children:o,show:e}){return W.createElement(W.Fragment,null,e?o:null)}function Qd({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?W.createElement(ll,{state:o,camera:t},e):W.createElement(W.Fragment,null,e)}function _d({state:o}){let e=W.useRef(null);return Gt(()=>(o.stageTransition.registerOverlayHost(e.current),()=>{o.stageTransition.registerOverlayHost(null)}),[]),W.createElement("div",{className:"w-full h-full absolute pointer-events-none",ref:e,"data-element-type":"stage-transition-overlay-host"})}function Jd({NvlComponent:o}){let{dialogs:e,state:t}=$t(),i=M().getLiveGame().getGameState(),r=W.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(xe.getCtx({gameState:i})),l=t.activeDialogId===s.id,u=l&&t.phase==="typing";return{entry:s,index:a,isActive:l,gameState:i,words:c,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return W.createElement(o,{dialogs:r})}import"client-only";import jn from"react";function Al({children:o,game:e}){return jn.createElement(jn.Fragment,null,jn.createElement($a,null,jn.createElement(Ua,{game:e},jn.createElement(xc,null,jn.createElement(Ka,null,o)))))}var Zd=(c=>(c.image="narraleaf:image",c.text="narraleaf:text",c.layer="narraleaf:layer",c.scene="narraleaf:scene",c.video="narraleaf:video",c.vfx="narraleaf:vfx",c.camera="narraleaf:camera",c.puppet="narraleaf:puppet",c))(Zd||{});import em from"clsx";import wt,{useEffect as xl,useRef as tm,useState as nm}from"react";function Cl(o){return o?{className:"",ariaHidden:!1}:{className:"opacity-0",ariaHidden:!0}}import{motion as im,useIsPresent as om}from"motion/react";var rm={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function sm({children:o,initial:e,transition:t,...n}){let i=M(),r=It(),{ratio:s}=he(),[a]=mn(te.Preferences.showDialog),c=tm(null),[l]=wn("nextAction"),u=om(),[d,p]=nm(null),h=Cl(a);function g(){a&&(r.config.gameState.isAdvanceSuspended()||r.requestComplete())}return xl(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
65
|
-
at Say.tsx: onElementClick`);return}let m=T=>{T.repeat||r.config.gameState.isAdvanceSuspended()||i.keyMap.match("nextAction",T.key)&&r.requestComplete()};window.addEventListener("keydown",m);let y=r.events.on(Me.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",m),y.cancel()}},[r,l]),xl(()=>{let m=i.preference.onPreferenceChange(te.Preferences.autoForward,y=>{y&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{m.cancel()}},[r]),wt.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},wt.createElement("div",{className:em("absolute bottom-0 w-full h-full",h.className),"aria-hidden":h.ariaHidden,onClick:g,style:{...$i(i.config.useAspectScale,{maxWidth:i.config.dialogWidth,maxHeight:i.config.dialogHeight,transform:`scale(${s.state.scale})`,transformOrigin:"bottom left",width:i.config.width,height:i.config.height})},ref:c},wt.createElement(ls,{value:d},wt.createElement(im.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)),wt.createElement("div",{"data-element-type":"dialog-overlay",className:"absolute inset-0 pointer-events-none",ref:p})))}function wl({children:o,...e}){let t=It();return!t.config.action.sentence||!t.config.action.words?null:wt.createElement(sm,{...e},o)}var Zp=wl;function kl(){return wt.createElement(wl,null,wt.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},wt.createElement(_r,null),wt.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},wt.createElement(en,null),wt.createElement(fn,{...rm}))))}var ki={say:kl,menu:sl,notification:yl,nvlDialog:cs};var er=class{constructor(e){this.game=e;this.plugins=[];this.registerAll()}use(e){return this.plugins.push(e),this}register(e){e.register(this.game)}registerAll(){this.plugins.forEach(e=>e.register(this.game))}unregisterAll(){this.plugins.forEach(e=>e.unregister(this.game))}has(e){return this.plugins.some(t=>t.name===e.name)}};var Pi=class{constructor(e={}){this.keyMap=e;this.events=new _}setKeyBinding(e,t){this.keyMap[e]=t,this.events.emit("event:keyMap.change",e,t)}getKeyBinding(e){return this.keyMap[e]??null}addKeyBinding(e,t){if(t===null)return;let n=this.getKeyBinding(e)??[],i=r=>Array.isArray(r)?r:[r];Array.isArray(n)?this.setKeyBinding(e,[...n,...i(t)]):this.setKeyBinding(e,[n,...i(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,i)=>{n===e&&t(i)})}importKeyBindings(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setKeyBinding(t,e[t])}exportKeyBindings(){return this.keyMap}match(e,t){let n=this.getKeyBinding(e);return n===null?!1:Array.isArray(n)?n.includes(t)||n.some(i=>i.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var Pl=(e=>(e.game="game",e))(Pl||{}),Qe=class Qe{constructor(e){this.hooks=new Wi;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new mi(Qe.DefaultPreference);this.audioBuses=new ni(()=>this.config.audioBuses??[],ya(this.preference));this.keyMap=new Pi({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new _;this.puppetBackends=new Yo;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=Y(Qe.DefaultConfig,e),this.plugins=new er(this),this.router=new dn(this)}configure(e){let[t,n]=ra(e,this.freezeFields);return n.length>0&&console.warn(`NarraLeaf-React [Game] The following fields are not allowed to be configured: ${n.join(", ")}`),this.config=Y(this.config,t),Object.prototype.hasOwnProperty.call(t,"audioBuses")&&this.audioBuses.invalidate(),this.getLiveGame().getGameState()?.events.emit(L.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}registerPuppetBackend(e){return this.puppetBackends.register(e),this}getPuppetBackend(e){return this.puppetBackends.get(e)}listPuppetBackends(){return this.puppetBackends.list()}getPuppetBackendRegistry(){return this.puppetBackends}onPreloadComplete(e){return this.lifecycleEvents.on(Qe.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(Qe.LifecycleEventTypes["event:game.preloadComplete"],e)}whenPreloadComplete(){return this.preloadCompleteContext?Promise.resolve(this.preloadCompleteContext):new Promise(e=>{this.oncePreloadComplete(e)})}isPreloadComplete(){return this.preloadCompleteContext!==null}onFirstSceneReady(e){return this.lifecycleEvents.on(Qe.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(Qe.LifecycleEventTypes["event:game.firstSceneReady"],e)}whenFirstSceneReady(){return this.firstSceneReadyContext?Promise.resolve(this.firstSceneReadyContext):new Promise(e=>{this.onceFirstSceneReady(e)})}isFirstSceneReady(){return this.firstSceneReadyContext!==null}markPreloadComplete(e){return this.preloadCompleteContext?!1:(this.preloadCompleteContext=e,this.lifecycleEvents.emit(Qe.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(Qe.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.audioBuses.dispose(),this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new Ut(this)}};Qe.defaultSettings={volume:1},Qe.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:0,skipInterval:100},Qe.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",voiceVolume:"voiceVolume",voiceFadeDuration:"voiceFadeDuration",voiceEndMode:"voiceEndMode",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},Qe.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadGate:"firstFrame",preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipSceneTransition:!0,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,notification:ki.notification,menu:ki.menu,dialog:ki.say,nvlDialog:ki.nvlDialog,onError:e=>{console.error(e)},disableTextScaling:!1,stage:null,maxStackModelLoop:1e3,maxActionHistory:100,maxSceneCallDepth:8,audioBuses:[]},Qe.GameSettingsNamespace=Pl,Qe.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var te=Qe;var tr=class tr extends X{constructor(){super(...arguments);this._jumpTarget=null}setJumpTarget(t){return this._jumpTarget=t,this}getJumpTarget(){return this._jumpTarget}static executeActionsAsync(t,n){let i=t.game.getLiveGame().requestAsyncStackModel([{type:n.type,node:n.contentNode}]);return t.game.getLiveGame().executeAsyncStackModel(i)}checkActionChain(t){if(t.some(n=>!!n.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return t}executeAction(t,n){let i=this.contentNode,[r]=i.getContent();if(this.type===re.do)return r.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:r[0].contentNode}];if(this.type===re.doAsync){if(r.length===0)return super.executeAction(t,n);let s=tr.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===re.any){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:s}}}else if(this.type===re.all){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:s}}}else if(this.type===re.allAsync){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().requestAsyncStackModel([{type:a.type,node:a.contentNode}]));return t.timelines.attachTimeline(S.all(...s.map(a=>t.game.getLiveGame().executeAsyncStackModel(a)))),super.executeAction(t,n)}else if(this.type===re.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let c=Xe.createCountLoop(t.game.getLiveGame(),a,this.checkActionChain(s));return t.logger.debug("ControlAction","repeat",s,a),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===re.while){let[s,a]=this.contentNode.getContent();if(s.length===0)return super.executeAction(t,n);if(!a.evaluate({gameState:t}).value)return super.executeAction(t,n);let c=Xe.createConditionLoop(t.game.getLiveGame(),a,this.getId(),this.checkActionChain(s));return t.logger.debug("ControlAction","while",s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===re.break){if(!n.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return n.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===re.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=S.delay(s):S.isAwaitable(s)?a=s:a=S.fromPromise(s);let c=new S,l=new we(a);return t.timelines.attachTimeline(l),a.then(()=>{c.resolve({type:this.type,node:this.contentNode.getChild()})}),c.onSkipControllerRegister(u=>{u.onAbort(()=>{l.abort()})}),c}else if(this.type===re.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new S,a=new S,c=new we(a);t.timelines.attachTimeline(c);let l=t.game.preference,u=l.getPreference(te.Preferences.autoForward),d=l.getPreference(te.Preferences.gameSpeed),p=u?t.game.config.autoForwardDelay/d:null,h=!1,g=null,m=null,y=null,T=()=>{m?.cancel(),y?.cancel(),g&&(clearTimeout(g),g=null)},f=()=>{h||(h=!0,T(),a.resolve())};return m=t.events.on(L.EventTypes["event:state.player.stageClick"],f),y=t.events.on(L.EventTypes["event:state.player.skip"],f),p!==null&&(g=setTimeout(f,p)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(v=>{v.onAbort(()=>{h||(h=!0,T(),c.abort())})}),s}else{if(this.type===re.label)return super.executeAction(t,n);if(this.type===re.jump){let s=this._jumpTarget;if(!s){let[l]=this.contentNode.getContent();throw new Ae(`Jump target label "${l}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),c=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(l,u)},[c]),a.getStackModelForce().clearAboveCallFrame().push({type:this.type,node:s.contentNode}),null}}throw new Error("Unknown control action type: "+this.type)}getFutureActions(t,n){if(this.callee.config.allowFutureScene===!1&&n.allowFutureScene===!1)return[...super.getFutureActions(t,n)];if(this.type===re.break||this.type===re.waitForClick||this.type===re.label||this.type===re.jump)return super.getFutureActions(t,n);let i=this.contentNode.getContent()[0],r=super.getFutureActions(t,n);return[...i??[],...r]}stringify(t,n,i){if(this.type===re.break)return super.stringifyWithContent("Control","break");if(this.type===re.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===re.label||this.type===re.jump){let[a]=this.contentNode.getContent(),c=this.type===re.label?"label":"jump";return super.stringifyWithContent("Control",`${c}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};tr.ActionTypes=re;var se=tr;var Fe=class o extends le{constructor(t={}){super();this.config=t}static do(t){return new o().do(t)}static doAsync(t){return new o().doAsync(t)}static any(t){return new o().any(t)}static all(t){return new o().all(t)}static allAsync(t){return new o().allAsync(t)}static repeat(t,n){return new o().repeat(t,n)}static whileLoop(t,n){return new o().whileLoop(t,n)}static breakLoop(){return new o().breakLoop()}static sleep(t){return new o().sleep(t)}static waitForClick(){return new o().waitForClick()}static label(t){return new o().label(t)}static jump(t){return new o().jump(t)}do(t){return this.push(se.ActionTypes.do,t)}doAsync(t){return this.push(se.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(se.ActionTypes.any,t)}all(t){return this.pushUnchained(se.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(se.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(se.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=Q.from(t);return this.pushWithLambda(se.ActionTypes.while,n,i)}breakLoop(){let t=new se(this.chain(),se.ActionTypes.break,new C().setContent([]));return this.chain(t)}sleep(t){return this.push(se.ActionTypes.sleep,[],t)}waitForClick(){let t=new se(this.chain(),se.ActionTypes.waitForClick,new C().setContent([]));return this.chain(t)}label(t){let n=new se(this.chain(),se.ActionTypes.label,new C().setContent([t]));return this.chain(n)}jump(t){let n=new se(this.chain(),se.ActionTypes.jump,new C().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new se(this.chain(),t,new C().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new se(this.chain(),t,new C().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new se(this.chain(),t,new C().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?_t.say(n).getActions():Be.toActions([n]))}};var q=class q extends Ke{static get DefaultUserConfig(){return q._defaultUserConfig??(q._defaultUserConfig=new j({name:"(anonymous)",autoInit:!0,src:q.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...ne.DefaultTransformState.getDefaultConfig()},{position:e=>O.tryParsePosition(e)}))}static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return P.isStaticImageData(t)?P.srcToURL(t):P.isColor(t)?t:P.isImageSrc(t)?P.srcToURL(t):q.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isLayeredSrc(e){return!!e.config.src?.slots}static isSrcDefinitionObject(e){return typeof e=="object"&&e!==null&&!P.isImageSrc(e)&&!P.isColor(e)}static isLayeredDefinition(e){return this.isSrcDefinitionObject(e)&&"layers"in e}static isTagDefinition(e){return this.isSrcDefinitionObject(e)&&"resolve"in e}static isLayerVariants(e){return typeof e=="object"&&e!==null}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(P.isImageSrc(t)||P.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:q.isLayeredSrc(e)?null:q.isTagSrc(e)&&e.config.src.resolve?q.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):q.isStaticSrc(e)?P.isStaticImageData(e.state.currentSrc)?P.srcToURL(e.state.currentSrc):P.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static getSrcURLs(e,t){let n=e.config.src?.slots;if(!n)return[];let i=new Set(t??e.state.currentSrc);return n.map(r=>q.resolveLayerSlot(r,i))}static resolveLayerSlot(e,t){if(e===null||typeof e=="string")return e;if(typeof e=="function")return e(t);for(let[n,i]of Object.entries(e))if(t.has(n))return i;return null}static getAllLayerSrc(e){let t=e.config.src?.slots;if(!t)return[];let n=[];for(let i of t)if(typeof i=="string")n.push(i);else if(q.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new q({src:e})}constructor(e={}){super();let t=q.DefaultUserConfig.create(e),n=this.createImageConfig(t);this.userConfig=t,this.config=n.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(t),this.checkConfig().registerSrc()}char(e,t){return this.combineActions(new Fe,n=>{if(P.isImageSrc(e)||P.isColor(e)){if(P.isColor(e)&&!this.config.isBackground)throw new Error("Color src is not allowed for non-background image");return n.chain(this._setSrc(n,e,t))}else{let i=new ve(n,ve.ActionTypes.setAppearance,new C().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Fe,i=>i.chain(this._setDarkness(i,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new J("Cannot add self as a wearable");this.config.wearables.push(n),Object.assign(n.config,{isWearable:!0})}return this}wear(e){return this.addWearable(e)}bindWearable(e){return e.addWearable([this])}asWearableOf(e){return this.bindWearable(e)}useLayer(e){return this.userConfig.get().layer=e||void 0,Object.assign(this.config,{layer:e||void 0}),this}toData(){return{state:q.StateSerializer.serialize(this.state),transformState:ne.TransformStateSerializer.serialize(this.transformState.get()),loop:this._serializeLoop()}}fromData(e){return this.state=q.StateSerializer.deserialize(e.state),this.transformState.resetTo(ne.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}_applyTransition(e,t){return new Te(this.chain(),pe.applyTransition,new C().setContent([e,t]))}_init(e,t){return new Te(this.chain(),pe.init,new C().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new ve(this.chain(),ve.ActionTypes.initWearable,new C().setContent([e]))}_flush(){return new ve(this.chain(),ve.ActionTypes.flush,new C)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get()),this}resolveTags(e,t){if(!q.isTagSrc(this))throw new Error(`Tag not defined
|
|
63
|
+
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(b)),r.get(b)||b}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:h,applyTransition:g,applyTransform:m,applyLoop:y,stopLoop:T,updateStyleSync:f,flush:v,deps:A}=jt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:b=>{if(c)return(b?b.task.resolve:[null]).map(V=>V&&typeof V=="function"?{style:hd}:{style:md(o.state.darkness)});let x=b?b.transition._getCurrentSrc():fd(o);return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:P.isColor(x)?P.colorToString(x):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:P.isImageSrc(x)?P.srcToURL(x):F.DefaultImagePlaceholder},{style:{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none",filter:"brightness(1)"}}]},propOverwrite:b=>b.src?{...b,src:l(b.src)}:b});xt(o,{createWearable:b=>{i(x=>[...x,b])},disposeWearable:b=>{i(x=>x.filter(I=>I.getId()!==b.getId()))},initDisplayable:h,applyTransform:m,applyLoop:y,stopLoop:T,applyTransition:g,events:t,updateStyleSync:f,flush:v},[...A]);let w=Qc((b,x)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${b}px`,height:`${x}px`}))},[t]),k=Qc(()=>{t.emit("event:image.onLoad")},[t]);return Nt.createElement(pd.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},Nt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?d.map(([b,x],I)=>{let V=p?p.task.resolve[I]:null;if(V&&typeof V=="function")return Nt.createElement(jo,{key:x,ref:b,autoFit:o.config.autoFit});let oe=V?V.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():c;return Nt.createElement(Zc,{key:x,ref:b,src:oe||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:I===0?w:void 0,onLoad:I===0?k:void 0})}):d.map(([b,x],I)=>Nt.createElement(jo,{key:x,ref:b,autoFit:o.config.autoFit,onSizeChanged:I===0?w:void 0,onLoad:I===0?k:void 0})),Nt.createElement("div",{className:Jc("w-full h-full top-0 left-0 absolute")},n.map(b=>Nt.createElement("div",{className:Jc("w-full h-full relative"),key:"wearable-"+b.getId()},Nt.createElement(el,{image:b,state:e}))))))}var el=Nt.memo(gd),tl=el;import Xo,{useEffect as il,useMemo as bd,useRef as ys}from"react";var yd=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,vd=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function nl(o,e){if(typeof e!="string"||!e.length)return o;if(yd.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=Sd(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+Td(r+e.replace(/\\/g,"/"))}function Sd(o){let e=vd.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function Td(o){let e=o.split("/"),t=[];for(let n=0;n<e.length;n++){let i=e[n];if(!(i==="."||i===""&&n!==e.length-1)){if(i===".."){t.pop();continue}t.push(i)}}return t.join("/")}var Yo=class{constructor(){this.backends=new Map;this.reportedMissing=new Set}register(e){if(!e||typeof e.name!="string"||!e.name.length)throw new Error("A puppet backend must have a non-empty name.");if(typeof e.mount!="function")throw new Error(`Puppet backend "${e.name}" must implement mount().`);return this.backends.set(e.name,e),this.reportedMissing.delete(e.name),this}get(e){return this.backends.get(e)||null}has(e){return this.backends.has(e)}list(){return Array.from(this.backends.keys())}unregister(e){return this.backends.delete(e)}reportMissing(e,t){return this.reportedMissing.has(e)?!1:(this.reportedMissing.add(e),t(`No puppet backend is registered under "${e}". The element keeps its place on the stage, its transform and its saved state, but draws nothing. Register one with game.registerPuppetBackend({name, mount}) before the game mounts.`),!0)}};function vs({state:o,puppet:e}){let[t]=ae(),{cacheManager:n}=Kt(),i=ys(null),r=bd(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=ys(r);s.current=r;let{transformRef:a,transitionRefs:c,initDisplayable:l,applyTransform:u,applyLoop:d,stopLoop:p,applyTransition:h,updateStyleSync:g,deps:m}=jt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipImageTransform,skipTransition:o.game.config.allowSkipImageTransition,transitionsProps:[{style:{position:"relative",width:`${r.width}px`,height:`${r.height}px`}}]});xt(e,{initDisplayable:l,applyTransform:u,applyLoop:d,stopLoop:p,applyTransition:h,updateStyleSync:g,flush:t},[...m]),il(()=>{let f=i.current;if(!f)return;let v=o.game,A=e.config.backend,w=v.getPuppetBackend(A);if(!w)return e._setStatus("missing-backend"),v.getPuppetBackendRegistry().reportMissing(A,x=>{o.logger.warn("Puppet",x)}),()=>{e._setStatus("unmounted")};let k;try{k=w.mount(f,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:T,resolveSibling:x=>T(nl(e.config.src,x)),warn:(x,I)=>{o.logger.warn("Puppet",x,I)}})}catch(x){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${A}" threw while mounting "${e.config.src}"`,x),()=>{e._setStatus("unmounted")}}let b=!1;return e._attachInstance(k),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!b&&typeof k.ready=="function"?k.ready():void 0).then(()=>{b||e._setStatus("ready")}).catch(x=>{b||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${A}" failed to load "${e.config.src}"`,x))}),()=>{b=!0,e._attachInstance(null),e._setStatus("unmounted");try{k.dispose()}catch(x){o.logger.error("Puppet",`Backend "${A}" threw while disposing`,x)}}},[]);let y=ys(r);il(()=>{let f=y.current;if(f.width===r.width&&f.height===r.height)return;y.current=r;let v=e._getInstance();if(!(!v||typeof v.resize!="function"))try{v.resize(r)}catch(A){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,A)}},[r]);function T(f){return P.isDataURI(f)?f:n.get(f)||f}return Xo.createElement(zt.Div,{"data-element-type":"puppet"},Xo.createElement(zt.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},c.map(([f,v])=>Xo.createElement("div",{key:v,ref:f,className:e.config.className},Xo.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function Ss({state:o,displayable:e}){return Ci.createElement(Ci.Fragment,null,e.map(t=>{if(t instanceof Cn)return Ci.createElement(hs,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof F)return Ci.createElement(tl,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof Lt)return Ci.createElement(vs,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Qo,{useEffect as Ad}from"react";import{motion as Cd}from"motion/react";function ol({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:c,stopLoop:l,updateStyleSync:u,deps:d}=jt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return xt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:c,stopLoop:l,updateStyleSync:u},[...d]),Ad(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Qo.createElement(Qo.Fragment,null,Qo.createElement(Cd.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([p,h])=>Qo.createElement("div",{className:"relative w-full h-full",ref:p,key:h},t))))}async function rl(o,e,t,n){let i=e.state.backgroundMusic,r=i&&o.audioManager.isManaged(i)?o.audioManager.stop(i,n):null;if(r&&t===i&&await r,t)try{await o.audioManager.playSoundToken(t,{end:t.state.volume,duration:n}),e.state.backgroundMusic=t}catch{e.state.backgroundMusic=null}else e.state.backgroundMusic=null;r&&await r}import xd from"clsx";import{useEffect as Ts,useRef as wd}from"react";import bs from"react";function As({state:o,className:e,elements:t}){let{scene:n,layers:i}=t,r=wd(null);return Ts(()=>(o.stageTransition.registerScene(n,r.current),()=>{o.stageTransition.registerScene(n,null)}),[]),Ts(()=>n.events.depends([n.events.on(Ye.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),Ts(()=>(n.events.emit(Ye.EventTypes["event:scene.mount"]),o.events.emit(L.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(Ye.EventTypes["event:scene.unmount"]),o.events.emit(L.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),xt(n,{setBackgroundMusic(s,a){return rl(o,n,s,a)}}),bs.createElement("div",{className:xd(e,"w-full h-full absolute"),ref:r,"data-element-type":"scene","data-scene-id":n.getId()},[...i.entries()].sort(([s],[a])=>s.state.zIndex-a.state.zIndex).map(([s,a])=>bs.createElement(ol,{state:o,layer:s,key:s.getId()},bs.createElement(Ss,{state:o,displayable:a}))))}import{AnimatePresence as Dd}from"motion/react";import{useEffect as Ld,useReducer as Rd,useRef as _o}from"react";import kd from"clsx";import qt,{useCallback as Cs,useMemo as Pd,useRef as Ed}from"react";function xs({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=M(),a=Ed([]),c=Cs(g=>(a.current.push(g),a.current.indexOf(g)),[]),l=Cs(g=>{let m=a.current.indexOf(g);m!==-1&&a.current.splice(m,1)},[]),u=Cs(g=>a.current.indexOf(g),[]),d=s.config.menu,p=Pd(()=>e.map(g=>({...g,words:g.prompt.evaluate(xe.getCtx({gameState:n}))})),[e,n]);function h(g){t(g)}return qt.createElement(qt.Fragment,null,qt.createElement(jr,{value:{evaluated:p,choose:h,gameState:n}},qt.createElement(Yr,{value:{register:c,unregister:l,getIndex:u}},qt.createElement(Bt,{className:"absolute"},r&&o&&qt.createElement(hi,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),qt.createElement(zt.Div,{color:"green",border:"dashed",className:kd("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},qt.createElement(d,{items:p.map((g,m)=>m)})))))}function sl({items:o}){return qt.createElement(bo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>qt.createElement(Io,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import Id from"clsx";import xi from"react";var al=120;function cl({sources:o,menuCount:e,presence:t,retained:n,lastActive:i,sceneId:r}){if(o.length===0){let c=n??(i.length>0?i.map(l=>({...l,active:!1})):null);return{items:c??[],retained:c,lastActive:i,retaining:c!==null,interactive:e>0}}let s=new Set(o.map(({slot:c})=>c));for(let[c,l]of Array.from(t.slotKeys))s.has(c)||(t.exitingKeys.add(l),t.slotKeys.delete(c));let a=o.map(({slot:c,...l})=>{let u=t.slotKeys.get(c);return(!u||t.exitingKeys.has(u))&&(u=`say-${r}-${t.nextKey++}`,t.slotKeys.set(c,u)),{...l,presenceKey:u,slot:c,active:!0}});return{items:a,retained:null,lastActive:a,retaining:!1,interactive:!0}}function ws({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=_o({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),a=_o([]),c=_o(null),l=_o(null),[,u]=Rd(y=>y+1,0),d=()=>{l.current&&(clearTimeout(l.current),l.current=null)},p=()=>{let y=c.current;if(!y)return;let T=s.current;y.forEach(({slot:f,presenceKey:v})=>{T.slotKeys.get(f)===v&&T.slotKeys.delete(f),T.exitingKeys.add(v)}),c.current=null,l.current=null,a.current=[],u()};Ld(()=>()=>{d()},[]);let h=s.current,g=i.length>0?i.map(({action:y,onClick:T},f)=>({action:y,slot:f,useTypeEffect:!0,onFinished:()=>{T(),o.events.emit(L.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((y,T)=>{if(!y.action.prompt||!y.action.words)return[];let f=h.menuPromptIds.get(y);return f||(f=`menu-prompt-${n.getId()}-${h.nextKey++}`,h.menuPromptIds.set(y,f)),[{action:{sentence:y.action.prompt,words:y.action.words,character:null,id:f},slot:T,useTypeEffect:!1}]}),m=cl({sources:g,menuCount:r.length,presence:h,retained:c.current,lastActive:a.current,sceneId:n.getId()});return c.current=m.retained,a.current=m.lastActive,m.retaining?l.current||(l.current=setTimeout(p,al)):d(),xi.createElement("div",{className:Id(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs",style:{pointerEvents:m.interactive?"auto":"none"}},xi.createElement(Dd,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{s.current.exitingKeys.clear()}},m.items.map(({action:y,onFinished:T,presenceKey:f,active:v,useTypeEffect:A})=>xi.createElement(hi,{gameState:o,key:f,action:y,active:v,onFinished:T,useTypeEffect:A}))),r.map(({action:y,onClick:T},f)=>xi.createElement("div",{key:"menu-"+f,"data-element-type":"menu"},xi.createElement(xs,{state:o,prompt:y.prompt,choices:y.choices,renderPrompt:!y.prompt,afterChoose:v=>{T(v),o.stage.next()},words:y.words}))))}import hn,{useEffect as Md,useRef as ks}from"react";import{motion as Nd}from"motion/react";function ll({state:o,camera:e,children:t}){let n=ks(null),i=ks(null),r=ks(null),{transformRef:s,transitionRefs:a,initDisplayable:c,applyTransition:l,applyTransform:u,applyLoop:d,stopLoop:p,updateStyleSync:h,deps:g}=jt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,companionRefs:[{ref:n,project:La},{ref:i,project:Ea},{ref:r,project:Da}],transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return xt(e,{initDisplayable:c,applyTransition:l,applyTransform:u,applyLoop:d,stopLoop:p,updateStyleSync:h},[...g]),Md(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),hn.createElement(hn.Fragment,null,hn.createElement(Nd.div,{className:"absolute w-full h-full",ref:s,"data-element-type":"camera"},a.map(([m,y])=>hn.createElement("div",{className:"relative w-full h-full",ref:m,key:y},t))),hn.createElement("div",{className:"absolute w-full h-full","data-element-type":"camera-lens",style:{pointerEvents:"none"}},hn.createElement("div",{className:"absolute w-full h-full",ref:n,"data-element-type":"camera-lens-vignette"}),hn.createElement("div",{className:"absolute w-full h-full",ref:i,"data-element-type":"camera-lens-shutter-top"}),hn.createElement("div",{className:"absolute w-full h-full",ref:r,"data-element-type":"camera-lens-shutter-bottom"})))}import Gd from"react";import{useEffect as Ps,useRef as Fd}from"react";import{useCallback as ul}from"react";function pl(o){let e=ul(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=ul(()=>{if(!o.current)return;let n=o.current;n.style.opacity="0",n.style.pointerEvents="none",n.style.visibility="hidden"},[o]);return{show:e,hide:t}}function Es({gameState:o,video:e}){let t=Fd(null),{show:n,hide:i}=pl(t);Ps(()=>o.events.depends([o.events.on(L.EventTypes["event:state.player.skip"],()=>{o.game.config.allowSkipVideo&&(r(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),Ps(()=>{i(),e.state.display&&n()},[]),Ps(()=>{if(!t.current)return;let s=t.current,a=!1,c=new Set,l=()=>new E(`Failed to add event listener, ref is not available
|
|
64
|
+
at Video.tsx: useEffect`),u=h=>{a||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw l();n()},hide:()=>{if(!t.current)throw l();i()},play:()=>{if(!t.current)throw l();let g=t.current;return h||g.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(g.currentTime=0,new Promise(m=>{let y=!1,T=null,f=[],v=()=>{y||(y=!0,c.delete(v),T&&T(),f.forEach(A=>A()),m())};c.add(v),T=o.schedule(({retry:A})=>{if(y)return;if(g.readyState<3){let x=()=>{g.removeEventListener("loadeddata",x),A()};g.addEventListener("loadeddata",x),f.push(()=>g.removeEventListener("loadeddata",x));return}let w=()=>v(),k=()=>v(),b=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),v()};g.addEventListener("ended",w),g.addEventListener("stopped",k),g.addEventListener("error",b),f.push(()=>{g.removeEventListener("ended",w),g.removeEventListener("stopped",k),g.removeEventListener("error",b)}),g.play().catch(x=>{o.logger.error("Failed to play video: "+x),v()})},10)}))},pause:()=>{if(!t.current)throw l();t.current.pause()},resume:()=>{if(!t.current)throw l();return t.current.play().catch(g=>{o.logger.error("Failed to resume video: "+g)})},stop:()=>{if(!t.current)throw l();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:g=>{if(!t.current)throw l();t.current.currentTime=g}}))},d=()=>u(!1),p=()=>{o.logger.error("NarraLeaf-React: Video",`Failed to load video source: ${e.config.src}`+(s.error?` (media error code ${s.error.code})`:"")),u(!0)};return s.addEventListener("canplay",d),s.addEventListener("error",p),s.readyState>=3?u(!1):s.error&&p(),()=>{s.removeEventListener("canplay",d),s.removeEventListener("error",p),c.forEach(h=>h()),s.currentTime>0&&s.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]);function r(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return Gd.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:s=>s.preventDefault()})}import Od,{useEffect as Hd,useRef as Vd}from"react";var dl={linear:"linear",easeIn:"cubic-bezier(0.42, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.58, 1)",easeInOut:"cubic-bezier(0.42, 0, 0.58, 1)"};function Ud(o,e){return e===void 0?"linear":Array.isArray(e)?`cubic-bezier(${e.join(", ")})`:typeof e=="string"&&dl[e]?dl[e]:(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease")}function Ds({gameState:o,vfx:e}){let t=Vd(null);return Hd(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,c=new Set,l=new Set,u=[],d=A=>{n.style.transition="",n.style.opacity=String(A)},p=()=>{n.play().catch(A=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+A)})},h=()=>i||n.error?(o.logger.error("NarraLeaf-React: Vfx","Cannot wait for a vfx whose source failed to load: "+e.config.src),Promise.resolve()):n.readyState>=2?Promise.resolve():new Promise(A=>{let w=!1,k=()=>x(),b=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),x()},x=()=>{w||(w=!0,l.delete(x),n.removeEventListener("loadeddata",k),n.removeEventListener("error",b),A())};l.add(x),n.addEventListener("loadeddata",k),n.addEventListener("error",b),(n.readyState>=2||n.error)&&x()}),g=(A,w,k)=>{let b=w?.duration??0,x=++s;return k.instant||b<=0?(d(A),Promise.resolve()):new Promise(I=>{let V=!1,oe=null,Ne=()=>{V||(V=!0,l.delete(Ne),oe!==null&&clearTimeout(oe),s===x&&t.current&&d(A),I())};l.add(Ne),n.style.transition=`opacity ${b}ms ${Ud(o,w?.easing)}`,n.offsetWidth,n.style.opacity=String(A),oe=setTimeout(Ne,b)})},m=A=>{r||(r=!0,i=A,o.mountState(e,{show:async w=>{a=!0;let k={instant:!1};c.add(k);try{if(await h(),!t.current)return;n.playbackRate=w?.rate??e.config.playbackRate,e.state.paused||p(),await g(w?.opacity??e.config.opacity,w,k)}finally{c.delete(k)}},hide:async w=>{a=!0;let k={instant:!1};c.add(k);try{await g(0,w,k),t.current&&n.pause()}finally{c.delete(k)}},pause:()=>{n.pause()},resume:()=>{p()},setRate:w=>{n.playbackRate=w}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&d(e.config.opacity)},0)))},y=()=>m(!1),T=()=>{o.logger.error("NarraLeaf-React: Vfx",`Failed to load vfx source: ${e.config.src}`+(n.error?` (media error code ${n.error.code})`:"")),m(!0)},f=o.events.on(L.EventTypes["event:state.player.skip"],()=>{c.size===0&&l.size===0||(c.forEach(A=>{A.instant=!0}),[...l].forEach(A=>A()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),v=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&t.current&&p()};return document.addEventListener("visibilitychange",v),n.style.opacity="0",n.playbackRate=e.config.playbackRate,e.config.muted||o.logger.weakWarn("NarraLeaf-React: Vfx","Vfx is not muted; autoplay may be rejected by the browser. (src: "+e.config.src+")"),e.state.display&&!e.state.paused&&p(),n.addEventListener("canplay",y),n.addEventListener("error",T),n.readyState>=3?m(!1):n.error&&T(),()=>{n.removeEventListener("canplay",y),n.removeEventListener("error",T),document.removeEventListener("visibilitychange",v),f.cancel(),u.forEach(A=>A()),[...l].forEach(A=>A()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),Od.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,loop:e.config.loop,playsInline:!0,onContextMenu:n=>n.preventDefault(),style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:e.config.fit,pointerEvents:"none"}})}import Wd from"clsx";import Bd,{useCallback as zd,useEffect as Jo,useRef as Kd}from"react";function Ls({children:o,className:e,gameState:t}){let{ratio:n}=he(),i=M(),[r]=ae(),s=Kd(null),a=i.config.minWidth,c=i.config.minHeight,l=zd(u=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(u.width,u.height,u.scale),n.updateMin(a,c),r()},[r,t.logger,c,a,n]);return Jo(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Jo(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Jo(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Jo(()=>t.events.on(L.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),Bd.createElement(Nc,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:Wd(e),onUpdate:l},o)}import ml,{useEffect as $d,useRef as jd,useState as fl}from"react";function Rs({src:o,width:e,height:t}){let[n,i]=fl({x:0,y:0}),[r,s]=fl(!1),a=jd(null),{ratio:c}=he();return $d(()=>{let l=u=>{if(a.current){let d=a.current.getBoundingClientRect(),p=u.clientX-d.left,h=u.clientY-d.top;i({x:p,y:h}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),ml.createElement(Bt,{ref:a,className:"overflow-hidden absolute"},ml.createElement("img",{src:o,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:r?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import hl from"react";import tn from"react";function Is({error:o,errorInfo:e}){return M().config.app.debug?tn.createElement("div",{className:"text-left"},tn.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),tn.createElement("p",{className:"text-red-700"},"Message: ",o.message),tn.createElement("pre",null,"Error Stack: ",o?.stack),tn.createElement("pre",null,"Component Stack: ",e?.componentStack),tn.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):tn.createElement("div",{className:"bg-white w-full h-full"},tn.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),tn.createElement("p",null,"Please contact the game developer for further assistance."))}var Zo=class extends hl.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t,errorInfo:null}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n}),this.props.onError?.(t,n),console.error(t,n)}render(){return this.state.hasError?hl.createElement(Is,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import vl from"clsx";import W,{useEffect as Gt,useReducer as Sl,useState as $n}from"react";import{flushSync as Tl}from"react-dom";import{useRef as qd}from"react";import{useEffect as Yd}from"react";function gl({gameState:o}){let e=qd(null);return Yd(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(L.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import wi,{useEffect as Xd}from"react";function Ms({gameState:o}){let[e]=ae(),{ratio:t}=he(),n=o.notificationMgr;Xd(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return wi.createElement("div",{style:{transform:`scale(${t.state.scale})`,transformOrigin:"left top"},className:"absolute top-0 left-0 w-full h-full pointer-events-none","data-element-type":"notification"},wi.createElement(i,{notifications:n.toArray()}))}function yl({notifications:o}){return wi.createElement(No,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>wi.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},wi.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function bl({story:o=ai.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:u,active:d=!0}){let[p,h]=Sl(D=>D+1,0),[g,m]=Sl(D=>D+1,0),[y,T]=$n(0),f=M(),[v]=$n(()=>new L(f,{update:h,forceUpdate:()=>{v.logger.weakWarn("Player","force update"),Tl(()=>{h()})},forceRemount:()=>{v.logger.weakWarn("Player","force remount"),Tl(()=>{T(D=>D+1),h()})},next:Ue})),A=W.createRef(),w=W.createRef(),[k,b]=$n(!1),x=W.useRef(!1),I=W.useRef(null),V=W.useRef(null),{preloaded:oe}=Kt(),[Ne,_e]=$n(!1),bt=W.useRef(!1),[At,gn]=$n(!1),mt=W.useRef(!1),B=W.useRef(null),Ee=W.useRef(!1),[ft]=$n(new Map);function rt(D){return{game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable(),scene:D}}function Ue(){let D=()=>{ft.forEach(G=>G.cancel())};if(v.rollLock.isLocked())return;D();let K=!1,ce=0;for(;!K;){if(ce++>f.config.maxStackModelLoop)throw new E("Max stack model loop reached");let G=f.getLiveGame().next();if(!G){if(f.getLiveGame().stackModel&&!f.getLiveGame().stackModel.isEmpty())continue;break}if(S.isAwaitable(G)){if(I.current===G)break;I.current=G,G.onSettled(()=>{G.isFailed()||(I.current===G&&(I.current=null),Ue())}),G.onFailed(ge=>{I.current===G&&(I.current=null),v.logger.error("Player",ge)}),K=!0;break}if(G instanceof Ln){if(V.current===G)break;V.current=G,G.nextUnlock().then(()=>{V.current===G&&(V.current=null),Ue()}),K=!0;break}if(Xe.isCalledActionResult(G)&&G.wait&&Xe.isStackModelsAwaiting(G.wait.type,G.wait.stackModels)){if(I.current===G)break;if(I.current=G,G.wait){let ge=Xe.executeStackModelGroup(G.wait.type,G.wait.stackModels);ge.then(()=>{I.current===G&&(I.current=null),Ue()}),ge.onFailed(De=>{I.current===G&&(I.current=null),v.logger.error("Player",De)})}K=!0;break}v.handle(G)}v.stage.update()}Gt(()=>{v.audioManager.initialize()},[]),Gt(()=>(f.getLiveGame().setGameState(v),o&&!f.getLiveGame().isPlaying()&&f.getLiveGame().loadStory(o),o?.entryScene&&!v.getPreloadingScene()&&!v.getLastScene()&&v.preloadScene(o.entryScene),v.playerCurrent=A.current,v.mainContentNode=w.current,()=>{f.getLiveGame().setGameState(void 0),v.playerCurrent=null}),[f,o]),Gt(()=>ct(()=>{b(!0);let D=v.getLastScene(),K=[];D?K.push(D.events.once("event:scene.mount",()=>{v.stage.next()}).cancel):v.stage.next();let ce=v.events.on(L.EventTypes["event:state.end"],()=>{c&&c({game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable()})});return v.stage.update(),()=>{D&&K.forEach(G=>G()),ce.cancel()}}),[]),Gt(()=>ct(()=>{k&&i&&!x.current&&(x.current=!0,v.stage.forceUpdate(),f.hooks.trigger("init",[]),i({game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable()}))}),[k]),Gt(()=>ct(()=>{if(Ne&&s&&!bt.current){bt.current=!0;let D=B.current||v.getLastScene()||v.getPreloadingScene(),K=rt(D);s(K)}}),[Ne]),Gt(()=>ct(()=>{if(At&&!mt.current){mt.current=!0;let D=B.current||v.getLastScene()||v.getPreloadingScene(),K=rt(D);f.markPreloadComplete(K)&&r&&r(K)}}),[At]),Gt(()=>v.events.on(L.EventTypes["event:state.scene.mount"],D=>{B.current||(B.current=D,m())}).cancel,[]),Gt(()=>{if(!At||!d||Ee.current||f.isFirstSceneReady())return;let D=B.current||v.getLastScene();if(!D)return;let K=null,ce=null,G=!1;Ee.current=!0;let ge=()=>{G=!0,Ee.current=!1;let De=rt(D);f.markFirstSceneReady(De)&&a&&a(De)};return typeof requestAnimationFrame=="function"?K=requestAnimationFrame(()=>{ce=setTimeout(ge,0)}):ce=setTimeout(ge,0),()=>{G||(Ee.current=!1,K!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(K),ce!==null&&clearTimeout(ce))}},[d,g,p,At]),Gt(()=>oe.events.depends([oe.events.on($e.EventTypes["event:preloaded.ready"],()=>{_e(!0),v.stage.update(),o&&f.getLiveGame().isPlaying()&&Ue()}),oe.events.on($e.EventTypes["event:preloaded.complete"],()=>{gn(!0)})]).cancel,[]),Gt(()=>{v.flushDep=p},[p]);let N=e||f.config.width,H=t||f.config.height;return W.createElement(Zo,{onError:l},W.createElement("div",{style:{width:typeof N=="number"?`${N}px`:N,height:typeof H=="number"?`${H}px`:H},className:vl(n,"__narraleaf_content-player"),ref:A,tabIndex:0},W.createElement(Ls,{className:vl("flex-grow overflow-auto"),gameState:v},W.createElement(us,{gameState:v}),W.createElement(gl,{gameState:v}),W.createElement(Bt,{className:"absolute",ref:w,style:{cursor:v.game.config.cursor?"none":"auto",overflow:v.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},f.config.cursor&&W.createElement(Rs,{src:f.config.cursor,width:f.config.cursorWidth,height:f.config.cursorHeight}),W.createElement(Qd,{show:Ne&&d,key:y},W.createElement(rs,null,W.createElement(Uc,{state:v}),W.createElement($c,{state:v}),W.createElement(_d,{state:v},W.createElement("div",{className:"w-full h-full absolute",style:{isolation:"isolate"},"data-element-type":"scene-group"},v.getSceneElements().map(D=>W.createElement(As,{key:"scene-"+D.scene.getId(),state:v,elements:D}))),W.createElement(Jd,{state:v}),v.getVideos().map((D,K)=>W.createElement("div",{className:"w-full h-full absolute",key:"video-"+K,"data-element-type":"video"},W.createElement(Es,{gameState:v,video:D}))),v.getVfx().map(D=>W.createElement("div",{className:"w-full h-full absolute",key:"vfx-"+D.getId(),"data-element-type":"vfx",style:{zIndex:D.config.zIndex,mixBlendMode:D.config.blendMode}},W.createElement(Ds,{gameState:v,vfx:D})))),v.getSceneElements().map(D=>W.createElement(ws,{key:"scene-dialogs-"+D.scene.getId(),state:v,elements:D})),W.createElement(Zd,{NvlComponent:f.config.nvlDialog}))),W.createElement(Yc,{state:v}),W.createElement(Ec,null,u),W.createElement(Ms,{gameState:v})))))}function Qd({children:o,show:e}){return W.createElement(W.Fragment,null,e?o:null)}function _d({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?W.createElement(ll,{state:o,camera:t},e):W.createElement(W.Fragment,null,e)}function Jd({state:o}){let e=W.useRef(null);return Gt(()=>(o.stageTransition.registerOverlayHost(e.current),()=>{o.stageTransition.registerOverlayHost(null)}),[]),W.createElement("div",{className:"w-full h-full absolute pointer-events-none",ref:e,"data-element-type":"stage-transition-overlay-host"})}function Zd({NvlComponent:o}){let{dialogs:e,state:t}=$t(),i=M().getLiveGame().getGameState(),r=W.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(xe.getCtx({gameState:i})),l=t.activeDialogId===s.id,u=l&&t.phase==="typing";return{entry:s,index:a,isActive:l,gameState:i,words:c,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return W.createElement(o,{dialogs:r})}import"client-only";import jn from"react";function Al({children:o,game:e}){return jn.createElement(jn.Fragment,null,jn.createElement($a,null,jn.createElement(Ua,{game:e},jn.createElement(xc,null,jn.createElement(Ka,null,o)))))}var em=(c=>(c.image="narraleaf:image",c.text="narraleaf:text",c.layer="narraleaf:layer",c.scene="narraleaf:scene",c.video="narraleaf:video",c.vfx="narraleaf:vfx",c.camera="narraleaf:camera",c.puppet="narraleaf:puppet",c))(em||{});import tm from"clsx";import wt,{useEffect as xl,useRef as nm,useState as im}from"react";function Cl(o){return o?{className:"",ariaHidden:!1}:{className:"opacity-0",ariaHidden:!0}}import{motion as om,useIsPresent as rm}from"motion/react";var sm={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function am({children:o,initial:e,transition:t,...n}){let i=M(),r=It(),{ratio:s}=he(),[a]=mn(te.Preferences.showDialog),c=nm(null),[l]=wn("nextAction"),u=rm(),[d,p]=im(null),h=Cl(a);function g(){a&&(r.config.gameState.isAdvanceSuspended()||r.requestComplete())}return xl(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
65
|
+
at Say.tsx: onElementClick`);return}let m=T=>{T.repeat||r.config.gameState.isAdvanceSuspended()||i.keyMap.match("nextAction",T.key)&&r.requestComplete()};window.addEventListener("keydown",m);let y=r.events.on(Me.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",m),y.cancel()}},[r,l]),xl(()=>{let m=i.preference.onPreferenceChange(te.Preferences.autoForward,y=>{y&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{m.cancel()}},[r]),wt.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},wt.createElement("div",{className:tm("absolute bottom-0 w-full h-full",h.className),"aria-hidden":h.ariaHidden,onClick:g,style:{...$i(i.config.useAspectScale,{maxWidth:i.config.dialogWidth,maxHeight:i.config.dialogHeight,transform:`scale(${s.state.scale})`,transformOrigin:"bottom left",width:i.config.width,height:i.config.height})},ref:c},wt.createElement(ls,{value:d},wt.createElement(om.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)),wt.createElement("div",{"data-element-type":"dialog-overlay",className:"absolute inset-0 pointer-events-none",ref:p})))}function wl({children:o,...e}){let t=It();return!t.config.action.sentence||!t.config.action.words?null:wt.createElement(am,{...e},o)}var ed=wl;function kl(){return wt.createElement(wl,null,wt.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},wt.createElement(_r,null),wt.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},wt.createElement(en,null),wt.createElement(fn,{...sm}))))}var ki={say:kl,menu:sl,notification:yl,nvlDialog:cs};var er=class{constructor(e){this.game=e;this.plugins=[];this.registerAll()}use(e){return this.plugins.push(e),this}register(e){e.register(this.game)}registerAll(){this.plugins.forEach(e=>e.register(this.game))}unregisterAll(){this.plugins.forEach(e=>e.unregister(this.game))}has(e){return this.plugins.some(t=>t.name===e.name)}};var Pi=class{constructor(e={}){this.keyMap=e;this.events=new _}setKeyBinding(e,t){this.keyMap[e]=t,this.events.emit("event:keyMap.change",e,t)}getKeyBinding(e){return this.keyMap[e]??null}addKeyBinding(e,t){if(t===null)return;let n=this.getKeyBinding(e)??[],i=r=>Array.isArray(r)?r:[r];Array.isArray(n)?this.setKeyBinding(e,[...n,...i(t)]):this.setKeyBinding(e,[n,...i(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,i)=>{n===e&&t(i)})}importKeyBindings(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setKeyBinding(t,e[t])}exportKeyBindings(){return this.keyMap}match(e,t){let n=this.getKeyBinding(e);return n===null?!1:Array.isArray(n)?n.includes(t)||n.some(i=>i.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var Pl=(e=>(e.game="game",e))(Pl||{}),Qe=class Qe{constructor(e){this.hooks=new Wi;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new mi(Qe.DefaultPreference);this.audioBuses=new ni(()=>this.config.audioBuses??[],ya(this.preference));this.keyMap=new Pi({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new _;this.puppetBackends=new Yo;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=Y(Qe.DefaultConfig,e),this.plugins=new er(this),this.router=new dn(this)}configure(e){let[t,n]=ra(e,this.freezeFields);return n.length>0&&console.warn(`NarraLeaf-React [Game] The following fields are not allowed to be configured: ${n.join(", ")}`),this.config=Y(this.config,t),Object.prototype.hasOwnProperty.call(t,"audioBuses")&&this.audioBuses.invalidate(),this.getLiveGame().getGameState()?.events.emit(L.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}registerPuppetBackend(e){return this.puppetBackends.register(e),this}getPuppetBackend(e){return this.puppetBackends.get(e)}listPuppetBackends(){return this.puppetBackends.list()}getPuppetBackendRegistry(){return this.puppetBackends}onPreloadComplete(e){return this.lifecycleEvents.on(Qe.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(Qe.LifecycleEventTypes["event:game.preloadComplete"],e)}whenPreloadComplete(){return this.preloadCompleteContext?Promise.resolve(this.preloadCompleteContext):new Promise(e=>{this.oncePreloadComplete(e)})}isPreloadComplete(){return this.preloadCompleteContext!==null}onFirstSceneReady(e){return this.lifecycleEvents.on(Qe.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(Qe.LifecycleEventTypes["event:game.firstSceneReady"],e)}whenFirstSceneReady(){return this.firstSceneReadyContext?Promise.resolve(this.firstSceneReadyContext):new Promise(e=>{this.onceFirstSceneReady(e)})}isFirstSceneReady(){return this.firstSceneReadyContext!==null}markPreloadComplete(e){return this.preloadCompleteContext?!1:(this.preloadCompleteContext=e,this.lifecycleEvents.emit(Qe.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(Qe.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.audioBuses.dispose(),this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new Ut(this)}};Qe.defaultSettings={volume:1},Qe.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:0,skipInterval:100},Qe.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",voiceVolume:"voiceVolume",voiceFadeDuration:"voiceFadeDuration",voiceEndMode:"voiceEndMode",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},Qe.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadGate:"firstFrame",preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipSceneTransition:!0,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,notification:ki.notification,menu:ki.menu,dialog:ki.say,nvlDialog:ki.nvlDialog,onError:e=>{console.error(e)},disableTextScaling:!1,stage:null,maxStackModelLoop:1e3,maxActionHistory:100,maxSceneCallDepth:8,audioBuses:[]},Qe.GameSettingsNamespace=Pl,Qe.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var te=Qe;var tr=class tr extends X{constructor(){super(...arguments);this._jumpTarget=null}setJumpTarget(t){return this._jumpTarget=t,this}getJumpTarget(){return this._jumpTarget}static executeActionsAsync(t,n){let i=t.game.getLiveGame().requestAsyncStackModel([{type:n.type,node:n.contentNode}]);return t.game.getLiveGame().executeAsyncStackModel(i)}checkActionChain(t){if(t.some(n=>!!n.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return t}executeAction(t,n){let i=this.contentNode,[r]=i.getContent();if(this.type===re.do)return r.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:r[0].contentNode}];if(this.type===re.doAsync){if(r.length===0)return super.executeAction(t,n);let s=tr.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===re.any){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:s}}}else if(this.type===re.all){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().createStackModel([{type:a.type,node:a.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:s}}}else if(this.type===re.allAsync){if(r.length===0)return{type:this.type,node:this.contentNode.getChild()};let s=this.checkActionChain(r).map(a=>t.game.getLiveGame().requestAsyncStackModel([{type:a.type,node:a.contentNode}]));return t.timelines.attachTimeline(S.all(...s.map(a=>t.game.getLiveGame().executeAsyncStackModel(a)))),super.executeAction(t,n)}else if(this.type===re.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let c=Xe.createCountLoop(t.game.getLiveGame(),a,this.checkActionChain(s));return t.logger.debug("ControlAction","repeat",s,a),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===re.while){let[s,a]=this.contentNode.getContent();if(s.length===0)return super.executeAction(t,n);if(!a.evaluate({gameState:t}).value)return super.executeAction(t,n);let c=Xe.createConditionLoop(t.game.getLiveGame(),a,this.getId(),this.checkActionChain(s));return t.logger.debug("ControlAction","while",s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===re.break){if(!n.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return n.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===re.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=S.delay(s):S.isAwaitable(s)?a=s:a=S.fromPromise(s);let c=new S,l=new we(a);return t.timelines.attachTimeline(l),a.then(()=>{c.resolve({type:this.type,node:this.contentNode.getChild()})}),c.onSkipControllerRegister(u=>{u.onAbort(()=>{l.abort()})}),c}else if(this.type===re.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new S,a=new S,c=new we(a);t.timelines.attachTimeline(c);let l=t.game.preference,u=l.getPreference(te.Preferences.autoForward),d=l.getPreference(te.Preferences.gameSpeed),p=u?t.game.config.autoForwardDelay/d:null,h=!1,g=null,m=null,y=null,T=()=>{m?.cancel(),y?.cancel(),g&&(clearTimeout(g),g=null)},f=()=>{h||(h=!0,T(),a.resolve())};return m=t.events.on(L.EventTypes["event:state.player.stageClick"],f),y=t.events.on(L.EventTypes["event:state.player.skip"],f),p!==null&&(g=setTimeout(f,p)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(v=>{v.onAbort(()=>{h||(h=!0,T(),c.abort())})}),s}else{if(this.type===re.label)return super.executeAction(t,n);if(this.type===re.jump){let s=this._jumpTarget;if(!s){let[l]=this.contentNode.getContent();throw new Ae(`Jump target label "${l}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),c=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(l,u)},[c]),a.getStackModelForce().clearAboveCallFrame().push({type:this.type,node:s.contentNode}),null}}throw new Error("Unknown control action type: "+this.type)}getFutureActions(t,n){if(this.callee.config.allowFutureScene===!1&&n.allowFutureScene===!1)return[...super.getFutureActions(t,n)];if(this.type===re.break||this.type===re.waitForClick||this.type===re.label||this.type===re.jump)return super.getFutureActions(t,n);let i=this.contentNode.getContent()[0],r=super.getFutureActions(t,n);return[...i??[],...r]}stringify(t,n,i){if(this.type===re.break)return super.stringifyWithContent("Control","break");if(this.type===re.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===re.label||this.type===re.jump){let[a]=this.contentNode.getContent(),c=this.type===re.label?"label":"jump";return super.stringifyWithContent("Control",`${c}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};tr.ActionTypes=re;var se=tr;var Fe=class o extends le{constructor(t={}){super();this.config=t}static do(t){return new o().do(t)}static doAsync(t){return new o().doAsync(t)}static any(t){return new o().any(t)}static all(t){return new o().all(t)}static allAsync(t){return new o().allAsync(t)}static repeat(t,n){return new o().repeat(t,n)}static whileLoop(t,n){return new o().whileLoop(t,n)}static breakLoop(){return new o().breakLoop()}static sleep(t){return new o().sleep(t)}static waitForClick(){return new o().waitForClick()}static label(t){return new o().label(t)}static jump(t){return new o().jump(t)}do(t){return this.push(se.ActionTypes.do,t)}doAsync(t){return this.push(se.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(se.ActionTypes.any,t)}all(t){return this.pushUnchained(se.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(se.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(se.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=Q.from(t);return this.pushWithLambda(se.ActionTypes.while,n,i)}breakLoop(){let t=new se(this.chain(),se.ActionTypes.break,new C().setContent([]));return this.chain(t)}sleep(t){return this.push(se.ActionTypes.sleep,[],t)}waitForClick(){let t=new se(this.chain(),se.ActionTypes.waitForClick,new C().setContent([]));return this.chain(t)}label(t){let n=new se(this.chain(),se.ActionTypes.label,new C().setContent([t]));return this.chain(n)}jump(t){let n=new se(this.chain(),se.ActionTypes.jump,new C().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new se(this.chain(),t,new C().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new se(this.chain(),t,new C().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new se(this.chain(),t,new C().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?_t.say(n).getActions():Be.toActions([n]))}};var q=class q extends Ke{static get DefaultUserConfig(){return q._defaultUserConfig??(q._defaultUserConfig=new j({name:"(anonymous)",autoInit:!0,src:q.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...ne.DefaultTransformState.getDefaultConfig()},{position:e=>O.tryParsePosition(e)}))}static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return P.isStaticImageData(t)?P.srcToURL(t):P.isColor(t)?t:P.isImageSrc(t)?P.srcToURL(t):q.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isLayeredSrc(e){return!!e.config.src?.slots}static isSrcDefinitionObject(e){return typeof e=="object"&&e!==null&&!P.isImageSrc(e)&&!P.isColor(e)}static isLayeredDefinition(e){return this.isSrcDefinitionObject(e)&&"layers"in e}static isTagDefinition(e){return this.isSrcDefinitionObject(e)&&"resolve"in e}static isLayerVariants(e){return typeof e=="object"&&e!==null}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(P.isImageSrc(t)||P.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:q.isLayeredSrc(e)?null:q.isTagSrc(e)&&e.config.src.resolve?q.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):q.isStaticSrc(e)?P.isStaticImageData(e.state.currentSrc)?P.srcToURL(e.state.currentSrc):P.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static getSrcURLs(e,t){let n=e.config.src?.slots;if(!n)return[];let i=new Set(t??e.state.currentSrc);return n.map(r=>q.resolveLayerSlot(r,i))}static resolveLayerSlot(e,t){if(e===null||typeof e=="string")return e;if(typeof e=="function")return e(t);for(let[n,i]of Object.entries(e))if(t.has(n))return i;return null}static getAllLayerSrc(e){let t=e.config.src?.slots;if(!t)return[];let n=[];for(let i of t)if(typeof i=="string")n.push(i);else if(q.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new q({src:e})}constructor(e={}){super();let t=q.DefaultUserConfig.create(e),n=this.createImageConfig(t);this.userConfig=t,this.config=n.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(t),this.checkConfig().registerSrc()}char(e,t){return this.combineActions(new Fe,n=>{if(P.isImageSrc(e)||P.isColor(e)){if(P.isColor(e)&&!this.config.isBackground)throw new Error("Color src is not allowed for non-background image");return n.chain(this._setSrc(n,e,t))}else{let i=new ve(n,ve.ActionTypes.setAppearance,new C().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Fe,i=>i.chain(this._setDarkness(i,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new J("Cannot add self as a wearable");this.config.wearables.push(n),Object.assign(n.config,{isWearable:!0})}return this}wear(e){return this.addWearable(e)}bindWearable(e){return e.addWearable([this])}asWearableOf(e){return this.bindWearable(e)}useLayer(e){return this.userConfig.get().layer=e||void 0,Object.assign(this.config,{layer:e||void 0}),this}toData(){return{state:q.StateSerializer.serialize(this.state),transformState:ne.TransformStateSerializer.serialize(this.transformState.get()),loop:this._serializeLoop()}}fromData(e){return this.state=q.StateSerializer.deserialize(e.state),this.transformState.resetTo(ne.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}_applyTransition(e,t){return new Te(this.chain(),pe.applyTransition,new C().setContent([e,t]))}_init(e,t){return new Te(this.chain(),pe.init,new C().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new ve(this.chain(),ve.ActionTypes.initWearable,new C().setContent([e]))}_flush(){return new ve(this.chain(),ve.ActionTypes.flush,new C)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get()),this}resolveTags(e,t){if(!q.isTagSrc(this))throw new Error(`Tag not defined
|
|
66
66
|
Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),i=new Map,r=[];this.config.src.groups.forEach(a=>{i.set(a,null)});let s=a=>{a.forEach(c=>{let l=n.get(c);l&&i.set(l,c)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let c=i.get(a);if(!c)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(c)}),r}_setAppearanceSync(e){if(P.isImageSrc(e)||P.isColor(e)){if(P.isColor(e)&&!this.config.isBackground)throw new J("Color src is not allowed for non-background image");this.state.currentSrc=e;return}if(!q.isTagSrc(this))throw this._mixedSrcError();let t=this.state.currentSrc,n=this.resolveTags(t,e);this.state.currentSrc=n}_mixedSrcError(){throw new J(`Trying to mix src and tags
|
|
67
67
|
To better understand the behavior of the image, you cannot mix static src and tags in the same image. `)}_invalidSrcHandlerError(){throw new Error("Invalid src handler, If you are using tags, config.src must be a function that resolves the src from the tags. If you are using src, config.src must be a string or StaticImageData")}_invalidWearableError(e){throw new Error(`Invalid wearable
|
|
68
68
|
Wearable must be an Image with isWearable set to true
|
|
@@ -75,12 +75,12 @@ Tag "${r}" is conflicting with another tag
|
|
|
75
75
|
Error found in config.tag.defaults`);if(!n.has(r))throw new Error(`Tag not found
|
|
76
76
|
Tag "${r}" is not defined in tagDefinitions
|
|
77
77
|
Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}if(e.slots){let r=new Set(e.defaults);for(let s of e.groups)if(!s.some(a=>r.has(a)))throw new J(`Layer has no default
|
|
78
|
-
The group with tags "${s.join(", ")}" needs exactly one of them listed in src.defaults`)}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let i of n)t.set(i,n);return t}_setDarkness(e,t,n,i){return new ve(e,ve.ActionTypes.setDarkness,new C().setContent([t,n,i]))}};q.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",q.StateSerializer=new qe,q._defaultUserConfig=null,q.DefaultImageConfig=new j({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),q.DefaultImageState=new j({currentSrc:q.DefaultImagePlaceholder,darkness:0});var F=q;var be=class extends Vt{constructor(){super(...arguments);this._detached=!1}_setDetached(t){return this._detached=t,this}_isDetached(){return this._detached}_setPrevLayers(t){return this._prevLayers=t,this}_setTargetLayers(t){return this._targetLayers=t,this}_getPrevLayers(){return this._prevLayers}_getTargetLayers(){return this._targetLayers}_isLayered(){return!!this._prevLayers||!!this._targetLayers}_setPrevSrc(t){return this._prevSrc=t,this}_setTargetSrc(t){return this._targetSrc=t,this}_setCurrentSrc(t){return this._currentSrc=t,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),n}asPrev(t){return super.asPrev((...n)=>Y(t(...n),this._srcToProps(this._prevSrc)))}asTarget(t){return super.asTarget((...n)=>Y(t(...n),this._srcToProps(this._targetSrc)))}_srcToProps(t){if(this._isLayered()||this._detached)return{};if(P.isColor(t))return{src:F.DefaultImagePlaceholder,style:{backgroundColor:P.isRGBAColor(t)?P.RGBAColorToHex(t):t}};if(P.isImageSrc(t))return{src:P.srcToURL(t)};throw new J("Image transition src cannot be identified, using: "+t)}};import{anticipate as am,backIn as cm,backInOut as lm,backOut as um,circIn as pm,circInOut as dm,circOut as mm,cubicBezier as fm,easeIn as hm,easeInOut as El,easeOut as gm}from"motion/react";function $(o){return o<0?0:o>1?1:o}function Dl(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function Ns(o){return{position:"absolute",top:"50%",left:"50%",width:"100%",height:"100%",transform:"translate(-50%, -50%)",backgroundColor:o}}function Ll(o){switch(o){case"left":return"to left";case"top":return"to top";case"bottom":return"to bottom";case"right":default:return"to right"}}function Rl(o){return o==="vertical"?"to right":"to bottom"}var ym={easeIn:hm,easeOut:gm,easeInOut:El,circIn:pm,circOut:mm,circInOut:dm,backIn:cm,backOut:um,backInOut:lm,anticipate:am};function Gs(o){return typeof o=="function"?o:Array.isArray(o)?fm(o[0],o[1],o[2],o[3]):o==="linear"?e=>e:ym[o??"easeInOut"]??El}function nr(o){let e=Gs(o.easing),t=(1-Ei(o))/2,n=1-t;return i=>i<=t?t<=0?1:e($(i/t)):i>=n?n>=1?1:e($((1-i)/(1-n))):1}function Ei(o){return o.holdMs!==void 0?o.duration<=0?o.holdMs>0?1:0:$(o.holdMs/o.duration):$(o.hold??0)}var Di=class o extends be{constructor(e){super(),this.from=e.from,this.to=e.to,this.duration=e.duration,this.holdMs=e.holdMs,this.easing=e.easing}createTask(){let e=Ei({duration:this.duration,holdMs:this.holdMs}),t=Gs(this.easing),n=i=>i<=e?this.from:e>=1?this.from:this.from+(this.to-this.from)*t((i-e)/(1-e));return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asTarget(i=>({style:{filter:`brightness(${1-n(i)})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o({from:this.from,to:this.to,duration:this.duration,holdMs:this.holdMs,easing:this.easing})}};var Li=class Li extends X{static resolveTagSrc(e,t){if(!F.isTagSrc(e)||!e.config.src.resolve)throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return F.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(F.isLayeredSrc(e))throw e._mixedSrcError();if(F.isStaticSrc(e))return P.isImageSrc(e.state.currentSrc)?P.srcToURL(e.state.currentSrc):e.state.currentSrc;if(F.isTagSrc(e)&&e.config.src.resolve)return F.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===ht.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new S(s=>s);return i.createWearable(n),e.getExposedStateAsync(n,s=>{s.initDisplayable(()=>{r.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.disposeWearable(s)},[n]),r}else if(this.type===ht.setSrc){let n=this.contentNode.getContent()[0];if(P.isColor(n)&&!this.callee.config.isBackground)throw new J("Color src is not allowed for non-background image");let i=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.currentSrc=r},[i]),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else{if(this.type===ht.flush)return super.executeAction(e,t);if(this.type===ht.setAppearance){let[n,i]=this.contentNode.getContent();if(!F.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],c=()=>{this.callee.state.currentSrc=a};if(F.isLayeredSrc(this.callee)){if(e.logger.debug("Image - Set Appearance (layered)",s),i){let d=new S(m=>m).registerSkipController(new U(()=>super.executeAction(e,t)));i._setPrevLayers(F.getSrcURLs(this.callee))._setTargetLayers(F.getSrcURLs(this.callee,s));let h=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,d.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(d).attachChild(h);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},c,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},c),e.stage.update(),e.getExposedState(this.callee)?.flush(),super.executeAction(e,t)}let l=this.callee.config.src.resolve;if(!l)throw this.callee._invalidSrcHandlerError();let u=F.getSrcFromTags(s,l);if(e.logger.debug("Image - Set Appearance",s,u),i){let d=new S(m=>m).registerSkipController(new U(()=>super.executeAction(e,t)));i._setPrevSrc(Li.resolveCurrentSrc(this.callee))._setTargetSrc(u);let h=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,d.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(d).attachChild(h);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},c,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},c),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else if(this.type===ht.setDarkness){let[n,i,r]=this.contentNode.getContent(),s=this.callee.state.darkness,a=()=>{this.callee.state.darkness=s},c=e.getExposedStateForce(this.callee);if(i){let l=new S(h=>h),u=new Di({from:s,to:n,duration:i,easing:r});if(F.isLayeredSrc(this.callee)){let h=F.getSrcURLs(this.callee);u._setPrevLayers(h)._setTargetLayers(h)}else{let h=Li.resolveCurrentSrc(this.callee);u._setPrevSrc(h)._setTargetSrc(h)}let d=c.applyTransition(u,()=>{this.callee.state.darkness=n,l.resolve(super.executeAction(e,t))}),p=e.timelines.attachTimeline(l).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:p},()=>{l.isSettled()||l.abort(),d.abort(),a()}),l}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};Li.ActionTypes=ht;var ve=Li;var Fs=class o{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),s=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new o(n,i,r,s)}constructor(e,t,n,i=1){this.r=e,this.g=t,this.b=n,this.a=i}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},kt=class kt{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||kt.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return kt.isHexString(e)||kt.isNamedColor(e)||kt.isRGBAColor(e)}static isNamedColor(e){return na(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),i=e.b.toString(16).padStart(2,"0"),r=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${i}${r}`}static colorToString(e){if(kt.isHexString(e))return e;if(kt.isNamedColor(e))return e;if(kt.isRGBAColor(e))return kt.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static isInlineSrc(e){return kt.isDataURI(e)||e.startsWith("blob:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[i,r]=e,[s,a]=t,c=this.calc(i,s),l=this.calc(r,a),u=n.invertX?{right:c}:{left:c},d=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...d}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let i=typeof t=="string"?"+":t<0?"-":"+",r=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${i} ${r})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};kt.RGBColor=Fs;var P=kt,Os=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},Oe=class o extends Os{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},mo=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,i=[],r=new Set,s=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!s.length)return null;for(i.push(s[0]);i.length;){let a=i.shift();this.checkAction(e,a,{imageStates:t,scenes:n},r);let c=a.contentNode.getChild();c&&c.action&&i.push(c.action)}return t}checkAction(e,t,{imageStates:n,scenes:i},r){if(t instanceof ve)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof ee){let s=t.callee;if(i.has(s.config.name)){if(i.get(s.config.name)!==s){let a=`Scene with name: ${s.config.name} is duplicated
|
|
78
|
+
The group with tags "${s.join(", ")}" needs exactly one of them listed in src.defaults`)}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let i of n)t.set(i,n);return t}_setDarkness(e,t,n,i){return new ve(e,ve.ActionTypes.setDarkness,new C().setContent([t,n,i]))}};q.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",q.StateSerializer=new qe,q._defaultUserConfig=null,q.DefaultImageConfig=new j({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),q.DefaultImageState=new j({currentSrc:q.DefaultImagePlaceholder,darkness:0});var F=q;var be=class extends Vt{constructor(){super(...arguments);this._detached=!1}_setDetached(t){return this._detached=t,this}_isDetached(){return this._detached}_setPrevLayers(t){return this._prevLayers=t,this}_setTargetLayers(t){return this._targetLayers=t,this}_getPrevLayers(){return this._prevLayers}_getTargetLayers(){return this._targetLayers}_isLayered(){return!!this._prevLayers||!!this._targetLayers}_setPrevSrc(t){return this._prevSrc=t,this}_setTargetSrc(t){return this._targetSrc=t,this}_setCurrentSrc(t){return this._currentSrc=t,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),n}asPrev(t){return super.asPrev((...n)=>Y(t(...n),this._srcToProps(this._prevSrc)))}asTarget(t){return super.asTarget((...n)=>Y(t(...n),this._srcToProps(this._targetSrc)))}_srcToProps(t){if(this._isLayered()||this._detached)return{};if(P.isColor(t))return{src:F.DefaultImagePlaceholder,style:{backgroundColor:P.isRGBAColor(t)?P.RGBAColorToHex(t):t}};if(P.isImageSrc(t))return{src:P.srcToURL(t)};throw new J("Image transition src cannot be identified, using: "+t)}};import{anticipate as cm,backIn as lm,backInOut as um,backOut as pm,circIn as dm,circInOut as mm,circOut as fm,cubicBezier as hm,easeIn as gm,easeInOut as Dl,easeOut as ym}from"motion/react";var El=1;function $(o){return o<0?0:o>1?1:o}function Ll(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function Ns(o){return{position:"absolute",top:"50%",left:"50%",width:`calc(100% + ${El*2}px)`,height:`calc(100% + ${El*2}px)`,transform:"translate(-50%, -50%)",backgroundColor:o}}function Rl(o){switch(o){case"left":return"to left";case"top":return"to top";case"bottom":return"to bottom";case"right":default:return"to right"}}function Il(o){return o==="vertical"?"to right":"to bottom"}var vm={easeIn:gm,easeOut:ym,easeInOut:Dl,circIn:dm,circOut:fm,circInOut:mm,backIn:lm,backOut:pm,backInOut:um,anticipate:cm};function Gs(o){return typeof o=="function"?o:Array.isArray(o)?hm(o[0],o[1],o[2],o[3]):o==="linear"?e=>e:vm[o??"easeInOut"]??Dl}function nr(o){let e=Gs(o.easing),t=(1-Ei(o))/2,n=1-t;return i=>i<=t?t<=0?1:e($(i/t)):i>=n?n>=1?1:e($((1-i)/(1-n))):1}function Ei(o){return o.holdMs!==void 0?o.duration<=0?o.holdMs>0?1:0:$(o.holdMs/o.duration):$(o.hold??0)}var Di=class o extends be{constructor(e){super(),this.from=e.from,this.to=e.to,this.duration=e.duration,this.holdMs=e.holdMs,this.easing=e.easing}createTask(){let e=Ei({duration:this.duration,holdMs:this.holdMs}),t=Gs(this.easing),n=i=>i<=e?this.from:e>=1?this.from:this.from+(this.to-this.from)*t((i-e)/(1-e));return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asTarget(i=>({style:{filter:`brightness(${1-n(i)})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o({from:this.from,to:this.to,duration:this.duration,holdMs:this.holdMs,easing:this.easing})}};var Li=class Li extends X{static resolveTagSrc(e,t){if(!F.isTagSrc(e)||!e.config.src.resolve)throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return F.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(F.isLayeredSrc(e))throw e._mixedSrcError();if(F.isStaticSrc(e))return P.isImageSrc(e.state.currentSrc)?P.srcToURL(e.state.currentSrc):e.state.currentSrc;if(F.isTagSrc(e)&&e.config.src.resolve)return F.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===ht.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new S(s=>s);return i.createWearable(n),e.getExposedStateAsync(n,s=>{s.initDisplayable(()=>{r.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.disposeWearable(s)},[n]),r}else if(this.type===ht.setSrc){let n=this.contentNode.getContent()[0];if(P.isColor(n)&&!this.callee.config.isBackground)throw new J("Color src is not allowed for non-background image");let i=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.currentSrc=r},[i]),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else{if(this.type===ht.flush)return super.executeAction(e,t);if(this.type===ht.setAppearance){let[n,i]=this.contentNode.getContent();if(!F.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],c=()=>{this.callee.state.currentSrc=a};if(F.isLayeredSrc(this.callee)){if(e.logger.debug("Image - Set Appearance (layered)",s),i){let d=new S(m=>m).registerSkipController(new U(()=>super.executeAction(e,t)));i._setPrevLayers(F.getSrcURLs(this.callee))._setTargetLayers(F.getSrcURLs(this.callee,s));let h=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,d.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(d).attachChild(h);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},c,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},c),e.stage.update(),e.getExposedState(this.callee)?.flush(),super.executeAction(e,t)}let l=this.callee.config.src.resolve;if(!l)throw this.callee._invalidSrcHandlerError();let u=F.getSrcFromTags(s,l);if(e.logger.debug("Image - Set Appearance",s,u),i){let d=new S(m=>m).registerSkipController(new U(()=>super.executeAction(e,t)));i._setPrevSrc(Li.resolveCurrentSrc(this.callee))._setTargetSrc(u);let h=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,d.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(d).attachChild(h);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},c,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},c),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else if(this.type===ht.setDarkness){let[n,i,r]=this.contentNode.getContent(),s=this.callee.state.darkness,a=()=>{this.callee.state.darkness=s},c=e.getExposedStateForce(this.callee);if(i){let l=new S(h=>h),u=new Di({from:s,to:n,duration:i,easing:r});if(F.isLayeredSrc(this.callee)){let h=F.getSrcURLs(this.callee);u._setPrevLayers(h)._setTargetLayers(h)}else{let h=Li.resolveCurrentSrc(this.callee);u._setPrevSrc(h)._setTargetSrc(h)}let d=c.applyTransition(u,()=>{this.callee.state.darkness=n,l.resolve(super.executeAction(e,t))}),p=e.timelines.attachTimeline(l).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:p},()=>{l.isSettled()||l.abort(),d.abort(),a()}),l}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};Li.ActionTypes=ht;var ve=Li;var Fs=class o{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),s=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new o(n,i,r,s)}constructor(e,t,n,i=1){this.r=e,this.g=t,this.b=n,this.a=i}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},kt=class kt{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||kt.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return kt.isHexString(e)||kt.isNamedColor(e)||kt.isRGBAColor(e)}static isNamedColor(e){return na(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),i=e.b.toString(16).padStart(2,"0"),r=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${i}${r}`}static colorToString(e){if(kt.isHexString(e))return e;if(kt.isNamedColor(e))return e;if(kt.isRGBAColor(e))return kt.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static isInlineSrc(e){return kt.isDataURI(e)||e.startsWith("blob:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[i,r]=e,[s,a]=t,c=this.calc(i,s),l=this.calc(r,a),u=n.invertX?{right:c}:{left:c},d=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...d}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let i=typeof t=="string"?"+":t<0?"-":"+",r=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${i} ${r})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};kt.RGBColor=Fs;var P=kt,Os=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},Oe=class o extends Os{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},mo=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,i=[],r=new Set,s=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!s.length)return null;for(i.push(s[0]);i.length;){let a=i.shift();this.checkAction(e,a,{imageStates:t,scenes:n},r);let c=a.contentNode.getChild();c&&c.action&&i.push(c.action)}return t}checkAction(e,t,{imageStates:n,scenes:i},r){if(t instanceof ve)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof ee){let s=t.callee;if(i.has(s.config.name)){if(i.get(s.config.name)!==s){let a=`Scene with name: ${s.config.name} is duplicated
|
|
79
79
|
Scene: ${s.config.name}
|
|
80
80
|
|
|
81
81
|
At: ${t.__stack}`;throw new Oe(a)}}else i.set(s.config.name,s);if(t.type===z.jumpTo){let a=t.contentNode.getContent()[0],c=e.getScene(a,!0);if(r.has(c))return;r.add(c)}}}checkImage(e,t){if(t.type===ht.setSrc){let i=t.contentNode.getContent()[0];P.isImageURL(i)&&P.isExternalSrc(i)&&(e.usedExternalSrc=!0)}}},J=class o extends Error{static describeAction(e,t){return`
|
|
82
82
|
Action: (id: ${e.id}) ${e.type}`+(t?`
|
|
83
83
|
At: ${t}`:"")}static getActionTrace(e){return o.describeAction({id:e.getId(),type:String(e.type)},e.__stack)}static toMessage(e,t){let n=[];return n.push(...Array.isArray(e)?e:[e]),t&&n.push(...Array.isArray(t)?t.map(o.getActionTrace):[o.getActionTrace(t)]),n.join("")}constructor(e,t){super(Array.isArray(e)?e.join(""):e),this.name="RuntimeScriptError";let n=t===void 0?[]:Array.isArray(t)?t:[t],i=n[0];if(i&&(this.action={id:i.getId(),type:String(i.type)},this.actionStack=i.__stack),this.traceTail=n.map(o.getActionTrace).join(""),this.traceTail&&typeof this.stack=="string"){let r=this.stack.indexOf(this.message);this.stack=r===-1?`${this.name}: ${this.composedMessage}
|
|
84
|
-
${this.stack}`:this.stack.slice(0,r)+this.composedMessage+this.stack.slice(r+this.message.length)}}get composedMessage(){return this.message+this.traceTail}},E=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Ae=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function vm(o,e){return ie.color(o,e)}function Sm(o){return ie.bold(o)}function Tm(o){return ie.italic(o)}var Hs=class o extends be{constructor(e){super(),this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(e=>({style:{opacity:1-e}})),this.asTarget(e=>({style:{opacity:e}}))]}}copy(){return new o({duration:this.duration,easing:this.easing})}};var Vs=class o extends be{constructor(e){super(),this.duration=e.duration,this.offset=e.offset??[0,0],this.easing=e.easing}createTask(e){let{invertX:t,invertY:n}=e.getStory().getInversionConfig();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.offset[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.offset[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((i,r,s)=>({style:{opacity:i,translate:`${t?-r:r}px ${n?-s:s}px`}}))]}}copy(){return new o({duration:this.duration,offset:this.offset,easing:this.easing})}};var Us=class o extends be{constructor(e){super(),this.duration=e.duration,this.blur=e.blur??16,this.easing=e.easing}createTask(){let e=Math.max(0,this.blur);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-$(t),filter:`blur(${e*$(t)}px)`}})),this.asTarget(t=>({style:{opacity:$(t),filter:`blur(${e*(1-$(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var Ws=class o extends be{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisSign(){switch(this.direction){case"right":return{axis:"x",sign:1};case"top":return{axis:"y",sign:-1};case"bottom":return{axis:"y",sign:1};case"left":default:return{axis:"x",sign:-1}}}translate(e){let{axis:t}=this.axisSign(),n=`${e}%`;return{translate:t==="x"?`${n} 0px`:`0px ${n}`}}createTask(){let{sign:e}=this.axisSign();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*$(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-$(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};var Bs=class o extends be{constructor(e){super(),this.duration=e.duration,this.ev=e.ev??4.6,this.lift=e.lift??.04,this.hold=e.hold,this.holdMs=e.holdMs,this.easing=e.easing}burnStyle(e){let t=$(e);if(t<=0)return{filter:"none"};let n=$(this.lift)*t,i=Math.pow(2,Math.max(0,this.ev)*t);return{filter:`invert(1) brightness(${1-n}) invert(1) brightness(${i})`}}createTask(){let t=nr({duration:this.duration,hold:this.hold,holdMs:this.holdMs,easing:this.easing});return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asPrev(n=>({style:{opacity:n<.5?1:0,...this.burnStyle(t(n))}})),this.asTarget(n=>({style:{opacity:n<.5?0:1,...this.burnStyle(t(n))}}))]}}copy(){return new o({duration:this.duration,ev:this.ev,lift:this.lift,hold:this.hold,holdMs:this.holdMs,easing:this.easing})}};function R(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function Dn(o,e,t){return o<e?e:o>t?t:o}var nn=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${R(t)}deg`:Ll(t);return{mask:(r,s)=>{let a=-n+(s?1-$(r):$(r))*(100+n);return s?`linear-gradient(${i}, transparent ${R(a)}%, #000 ${R(a+n)}%)`:`linear-gradient(${i}, #000 ${R(a)}%, transparent ${R(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${R(t)}deg`,`${R(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let c=-n+$(s)*(50+n);if(!a){let l=u=>`linear-gradient(${u}, #000 ${R(c)}%, transparent ${R(c+n)}%)`;return`${l(i)}, ${l(r)}`}if(c<0){let l=$((c+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${R(50-c-n)}%, rgba(0,0,0,${R(l)}) 50%, transparent ${R(50+c+n)}%)`}return`linear-gradient(${i}, transparent ${R(50-c-n)}%, #000 ${R(50-c)}%, #000 ${R(50+c)}%, transparent ${R(50+c+n)}%)`}}}static iris(e={}){let t=e.center??"50% 50%",n=Math.max(0,e.feather??12),i=e.shape??"circle";return{mask:(r,s)=>{if(s){let c=(1-$(r))*150;return`radial-gradient(${i} at ${t}, transparent ${R(c-n)}%, #000 ${R(c)}%)`}let a=$(r)*150;return`radial-gradient(${i} at ${t}, #000 ${R(a-n)}%, transparent ${R(a)}%)`}}}static clock(e={}){let t=e.center??"50% 50%",n=e.from??0,i=Math.max(0,e.feather??24),r=e.direction??"clockwise";return{mask:(s,a)=>{let c=r==="counterclockwise"!=!!a,l=-i+$(s)*(360+i);if(c){let d=Math.max(0,360-l-i),p=Math.max(d,360-l);return`conic-gradient(from ${R(n)}deg at ${t}, transparent ${R(d)}deg, #000 ${R(p)}deg)`}let u=Math.max(0,l);return`conic-gradient(from ${R(n)}deg at ${t}, #000 ${R(u)}deg, transparent ${R(Math.max(u,l+i))}deg)`}}}static fan(e={}){let t=Math.max(1,Math.round(e.blades??4)),n=e.center??"50% 50%",i=e.from??0,r=Math.max(0,e.feather??10),s=360/t;return{mask:(a,c)=>{let l=-r+(c?1-$(a):$(a))*(s+r),u=Dn(l,0,s),d=Dn(l+r,0,s),p=`repeating-conic-gradient(from ${R(i)}deg at ${n}`;return c?`${p}, transparent 0deg, transparent ${R(u)}deg, #000 ${R(d)}deg, #000 ${R(s)}deg)`:`${p}, #000 0deg, #000 ${R(u)}deg, transparent ${R(d)}deg, transparent ${R(s)}deg)`}}}static blinds(e={}){let t=e.orientation??"horizontal",n=Math.max(1,Math.round(e.slats??8)),i=Math.max(0,e.feather??0),r=Dn(e.stagger??0,-1,1),s=typeof t=="number"?`${R(t)}deg`:Rl(t),a=100/n,c=Math.abs(r)/n,l=1-c*(n-1),u=(p,h)=>c*(r>=0!==h?p:n-1-p),d=(p,h,g)=>{let m=-i+(g?1-h:h)*(a+i),y=Dn(m,0,a),T=Dn(m+i,0,a),f=p*a;return g?`linear-gradient(${s}, transparent ${R(f+y)}%, #000 ${R(f+T)}%, #000 ${R(f+a)}%, transparent ${R(f+a)}%)`:`linear-gradient(${s}, transparent ${R(f)}%, #000 ${R(f)}%, #000 ${R(f+y)}%, transparent ${R(f+T)}%)`};return{mask:(p,h)=>{if(r!==0){let T=[];for(let f=0;f<n;f++)T.push(d(f,$(($(p)-u(f,!!h))/l),!!h));return T.join(", ")}let g=-i+(h?1-$(p):$(p))*(a+i),m=Dn(g,0,a),y=Dn(g+i,0,a);return h?`repeating-linear-gradient(${s}, transparent 0, transparent ${R(m)}%, #000 ${R(y)}%, #000 ${R(a)}%)`:`repeating-linear-gradient(${s}, #000 0, #000 ${R(m)}%, transparent ${R(y)}%, transparent ${R(a)}%)`}}}static dots(e={}){let t=Math.max(1,e.rows??6),n=Math.max(1,e.cols??10),i=Math.max(0,e.feather??20),s=$(e.stagger??0)*.5,a=(c,l,u)=>{let d=-i+$(l)*(100+i);return u?`radial-gradient(circle farthest-corner at ${c}, transparent ${R(d)}%, #000 ${R(d+i)}%)`:`radial-gradient(circle farthest-corner at ${c}, #000 ${R(d)}%, transparent ${R(d+i)}%)`};return{size:`${R(100/n)}% ${R(100/t)}%`,repeat:"repeat",mask:(c,l)=>{let u=l?1-$(c):$(c);if(s<=0)return a("50% 50%",u,l);let d=$(u/(1-s)),p=$((u-s)/(1-s));return l?`${a("50% 50%",p,!0)}, ${a("0% 0%",d,!0)}`:`${a("50% 50%",d)}, ${a("0% 0%",p)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return Dl(e.mask(t,n),e.size,e.repeat)}};var bm=.3,zs=class o extends be{constructor(e){super(),this.duration=e.duration,this.color=e.color??"#000000",this.hold=e.hold,this.holdMs=e.holdMs,this.pattern=e.pattern??null,this.inverted=e.inverted??!1,this.uncover=e.uncover??"retreat",this.easing=e.easing}coverStyle(e,t){if(!this.pattern)return{...Ns(this.color),opacity:$(e)};let n={...Ns(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...nn.toStyle(this.pattern,e,!this.inverted)}:{...n,...nn.toStyle(this.uncover,e)}:{...n,...nn.toStyle(this.pattern,e,this.inverted)}}createTask(){let e={duration:this.duration,hold:this.hold??(this.holdMs===void 0?bm:void 0),holdMs:this.holdMs,easing:this.easing},t=1-(1-Ei(e))/2,n=.5,i=nr(e);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asPrev(r=>({style:{opacity:r<n?1:0}})),this.asTarget(r=>({style:{opacity:r<n?0:1}})),r=>({src:F.DefaultImagePlaceholder,style:this.coverStyle(i(r),r>=t)})]}}copy(){return new o({duration:this.duration,color:this.color,hold:this.hold,holdMs:this.holdMs,pattern:this.pattern??void 0,inverted:this.inverted,uncover:this.uncover,easing:this.easing})}};var Ks=class o extends be{constructor(e){super(),this.duration=e.duration,this.pattern=e.pattern,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(e=>({style:nn.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var qn="http://www.w3.org/2000/svg",Am="http://www.w3.org/1999/xlink",Cm=.002,xm=1,wm=.12,km=0,$s=class o extends be{constructor(t){super();this.filterId=null;this.host=null;this.cut=null;this.duration=t.duration,this.rule=P.srcToURL(t.rule),this.feather=Math.min(xm,Math.max(Cm,t.feather??wm)),this.inverted=t.inverted??!1,this.easing=t.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(t=>({style:this.styleAt(t)}))]}}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>this.dispose()),n.onCanceled(()=>this.dispose()),n}copy(){return new o({duration:this.duration,rule:this.rule,feather:this.feather,inverted:this.inverted,easing:this.easing})}styleAt(t){if(t>=1)return this.dispose(),{filter:""};let n=this.ensureScaffold();if(!n)return{filter:""};let i=t*(1+this.feather),r=(this.inverted?1:-1)/this.feather,s=(this.inverted?i-1:i)/this.feather;return this.cut?.setAttribute("k3",String(r)),this.cut?.setAttribute("k4",String(s)),{filter:`url(#${n})`}}ensureScaffold(){if(typeof document>"u")return null;if(this.filterId&&this.host)return this.filterId;let t=`nl-rule-${++km}`,n=document.createElementNS(qn,"svg");n.setAttribute("aria-hidden","true"),n.setAttribute("data-element-type","rule-transition"),n.setAttribute("width","0"),n.setAttribute("height","0"),Object.assign(n.style,{position:"absolute",width:"0",height:"0",overflow:"hidden"});let i=document.createElementNS(qn,"filter");i.setAttribute("id",t),i.setAttribute("color-interpolation-filters","sRGB"),i.setAttribute("primitiveUnits","objectBoundingBox"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("width","100%"),i.setAttribute("height","100%");let r=document.createElementNS(qn,"feImage");r.setAttribute("href",this.rule),r.setAttributeNS(Am,"xlink:href",this.rule),r.setAttribute("preserveAspectRatio","none"),r.setAttribute("x","0"),r.setAttribute("y","0"),r.setAttribute("width","1"),r.setAttribute("height","1"),r.setAttribute("result","rule");let s=document.createElementNS(qn,"feColorMatrix");s.setAttribute("in","rule"),s.setAttribute("type","luminanceToAlpha"),s.setAttribute("result","lum");let a=document.createElementNS(qn,"feComposite");a.setAttribute("in","lum"),a.setAttribute("in2","lum"),a.setAttribute("operator","arithmetic"),a.setAttribute("k1","0"),a.setAttribute("k2","0"),a.setAttribute("k3","0"),a.setAttribute("k4","0"),a.setAttribute("result","cut");let c=document.createElementNS(qn,"feComposite");return c.setAttribute("in","SourceGraphic"),c.setAttribute("in2","cut"),c.setAttribute("operator","in"),i.append(r,s,a,c),n.appendChild(i),document.body.appendChild(n),this.filterId=t,this.host=n,this.cut=a,t}dispose(){this.host?.remove(),this.host=null,this.cut=null,this.filterId=null}};var js=class extends li{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new Q(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var ir=class{static getActionId(e){return e.getId()}static setActionId(e,t){return e.setId(t),e}static getStaticId(e){return e.getStaticId()}static setStaticId(e,t){return e.setStaticId(t),e}static chainToActions(e){return e.getActions()}static wrapAction(e){let t=Be.isChained(e)?e.getActions():e;return Fe.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}static getLayerSrcs(e,t){return F.getSrcURLs(e,t)}static registerDisplayable(e,t,n=null,i=null){e.findElementByDisplayable(t)||(e.createDisplayable(t,n,i),e.flush())}static setElementId(e,t){e.setId(t)}static setElementStaticId(e,t){e.setStaticId(t)}static getDisplayableTransformProps(e){return{...e.transformState.get()}}static setDisplayableTransformProps(e,t,n,i={}){let r=t.transformState;i.merge===!1?r.forceOverwrite(n):r.assign(Symbol("DevTools.setDisplayableTransformProps"),n),t.markDirty(),e.getExposedState(t)?.updateStyleSync?.(),e.flush()}static getPuppetStatus(e){return e._getStatus()}static onPuppetStatusChange(e,t){return e._onStatusChange(t)}static async describePuppet(e,t){try{return await t._describe()}catch(n){return e.logger.error("DevTools","Puppet backend threw while describing itself",n),null}}static getPuppetState(e){return Lt.normalizeState(e.state)}static setPuppetState(e,t,n,i={}){t.state=i.merge===!1?Lt.normalizeState(n):Lt.mergeState(t.state,n),t._applyState().catch(r=>{e.logger.error("DevTools","Puppet backend threw while applying state",r)}),e.flush()}static async runPuppetCommand(e,t,n,i){try{await t._runCommand(n,i)||e.logger.weakWarn("DevTools",`Puppet command "${n}" was dropped: the puppet is not mounted.`)}catch(r){e.logger.error("DevTools",`Puppet backend threw while running "${n}"`,r)}}static listPuppetBackends(e){return e.listPuppetBackends()}static getCurrentDialog(e){if(e.isNvlMode()){let n=e.getNvlState();if(!n.activeDialogId||n.phase==="idle")return null;let i=e.getNvlDialog(n.activeDialogId);return i?{actionId:i.actionId||null,ended:n.phase==="awaitAdvance",mode:"nvl"}:null}let t=e.getAdvDialogState();return t?{actionId:t.actionId,ended:t.ended,mode:"adv"}:null}static onDialogStateChange(e,t){let n=[e.events.on(L.EventTypes["event:state.dialog.change"],t),e.events.on(L.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};ir.DynamicPersistent=On;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
|
|
84
|
+
${this.stack}`:this.stack.slice(0,r)+this.composedMessage+this.stack.slice(r+this.message.length)}}get composedMessage(){return this.message+this.traceTail}},E=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Ae=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function Sm(o,e){return ie.color(o,e)}function Tm(o){return ie.bold(o)}function bm(o){return ie.italic(o)}var Hs=class o extends be{constructor(e){super(),this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(e=>({style:{opacity:1-e}})),this.asTarget(e=>({style:{opacity:e}}))]}}copy(){return new o({duration:this.duration,easing:this.easing})}};var Vs=class o extends be{constructor(e){super(),this.duration=e.duration,this.offset=e.offset??[0,0],this.easing=e.easing}createTask(e){let{invertX:t,invertY:n}=e.getStory().getInversionConfig();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.offset[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.offset[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((i,r,s)=>({style:{opacity:i,translate:`${t?-r:r}px ${n?-s:s}px`}}))]}}copy(){return new o({duration:this.duration,offset:this.offset,easing:this.easing})}};var Us=class o extends be{constructor(e){super(),this.duration=e.duration,this.blur=e.blur??16,this.easing=e.easing}createTask(){let e=Math.max(0,this.blur);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-$(t),filter:`blur(${e*$(t)}px)`}})),this.asTarget(t=>({style:{opacity:$(t),filter:`blur(${e*(1-$(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var Ws=class o extends be{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisSign(){switch(this.direction){case"right":return{axis:"x",sign:1};case"top":return{axis:"y",sign:-1};case"bottom":return{axis:"y",sign:1};case"left":default:return{axis:"x",sign:-1}}}translate(e){let{axis:t}=this.axisSign(),n=`${e}%`;return{translate:t==="x"?`${n} 0px`:`0px ${n}`}}createTask(){let{sign:e}=this.axisSign();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*$(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-$(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};var Bs=class o extends be{constructor(e){super(),this.duration=e.duration,this.ev=e.ev??4.6,this.lift=e.lift??.04,this.hold=e.hold,this.holdMs=e.holdMs,this.easing=e.easing}burnStyle(e){let t=$(e);if(t<=0)return{filter:"none"};let n=$(this.lift)*t,i=Math.pow(2,Math.max(0,this.ev)*t);return{filter:`invert(1) brightness(${1-n}) invert(1) brightness(${i})`}}createTask(){let t=nr({duration:this.duration,hold:this.hold,holdMs:this.holdMs,easing:this.easing});return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asPrev(n=>({style:{opacity:n<.5?1:0,...this.burnStyle(t(n))}})),this.asTarget(n=>({style:{opacity:n<.5?0:1,...this.burnStyle(t(n))}}))]}}copy(){return new o({duration:this.duration,ev:this.ev,lift:this.lift,hold:this.hold,holdMs:this.holdMs,easing:this.easing})}};function R(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function Dn(o,e,t){return o<e?e:o>t?t:o}var nn=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${R(t)}deg`:Rl(t);return{mask:(r,s)=>{let a=-n+(s?1-$(r):$(r))*(100+n);return s?`linear-gradient(${i}, transparent ${R(a)}%, #000 ${R(a+n)}%)`:`linear-gradient(${i}, #000 ${R(a)}%, transparent ${R(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${R(t)}deg`,`${R(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let c=-n+$(s)*(50+n);if(!a){let l=u=>`linear-gradient(${u}, #000 ${R(c)}%, transparent ${R(c+n)}%)`;return`${l(i)}, ${l(r)}`}if(c<0){let l=$((c+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${R(50-c-n)}%, rgba(0,0,0,${R(l)}) 50%, transparent ${R(50+c+n)}%)`}return`linear-gradient(${i}, transparent ${R(50-c-n)}%, #000 ${R(50-c)}%, #000 ${R(50+c)}%, transparent ${R(50+c+n)}%)`}}}static iris(e={}){let t=e.center??"50% 50%",n=Math.max(0,e.feather??12),i=e.shape??"circle";return{mask:(r,s)=>{if(s){let c=(1-$(r))*150;return`radial-gradient(${i} at ${t}, transparent ${R(c-n)}%, #000 ${R(c)}%)`}let a=$(r)*150;return`radial-gradient(${i} at ${t}, #000 ${R(a-n)}%, transparent ${R(a)}%)`}}}static clock(e={}){let t=e.center??"50% 50%",n=e.from??0,i=Math.max(0,e.feather??24),r=e.direction??"clockwise";return{mask:(s,a)=>{let c=r==="counterclockwise"!=!!a,l=-i+$(s)*(360+i);if(c){let d=Math.max(0,360-l-i),p=Math.max(d,360-l);return`conic-gradient(from ${R(n)}deg at ${t}, transparent ${R(d)}deg, #000 ${R(p)}deg)`}let u=Math.max(0,l);return`conic-gradient(from ${R(n)}deg at ${t}, #000 ${R(u)}deg, transparent ${R(Math.max(u,l+i))}deg)`}}}static fan(e={}){let t=Math.max(1,Math.round(e.blades??4)),n=e.center??"50% 50%",i=e.from??0,r=Math.max(0,e.feather??10),s=360/t;return{mask:(a,c)=>{let l=-r+(c?1-$(a):$(a))*(s+r),u=Dn(l,0,s),d=Dn(l+r,0,s),p=`repeating-conic-gradient(from ${R(i)}deg at ${n}`;return c?`${p}, transparent 0deg, transparent ${R(u)}deg, #000 ${R(d)}deg, #000 ${R(s)}deg)`:`${p}, #000 0deg, #000 ${R(u)}deg, transparent ${R(d)}deg, transparent ${R(s)}deg)`}}}static blinds(e={}){let t=e.orientation??"horizontal",n=Math.max(1,Math.round(e.slats??8)),i=Math.max(0,e.feather??0),r=Dn(e.stagger??0,-1,1),s=typeof t=="number"?`${R(t)}deg`:Il(t),a=100/n,c=Math.abs(r)/n,l=1-c*(n-1),u=(p,h)=>c*(r>=0!==h?p:n-1-p),d=(p,h,g)=>{let m=-i+(g?1-h:h)*(a+i),y=Dn(m,0,a),T=Dn(m+i,0,a),f=p*a;return g?`linear-gradient(${s}, transparent ${R(f+y)}%, #000 ${R(f+T)}%, #000 ${R(f+a)}%, transparent ${R(f+a)}%)`:`linear-gradient(${s}, transparent ${R(f)}%, #000 ${R(f)}%, #000 ${R(f+y)}%, transparent ${R(f+T)}%)`};return{mask:(p,h)=>{if(r!==0){let T=[];for(let f=0;f<n;f++)T.push(d(f,$(($(p)-u(f,!!h))/l),!!h));return T.join(", ")}let g=-i+(h?1-$(p):$(p))*(a+i),m=Dn(g,0,a),y=Dn(g+i,0,a);return h?`repeating-linear-gradient(${s}, transparent 0, transparent ${R(m)}%, #000 ${R(y)}%, #000 ${R(a)}%)`:`repeating-linear-gradient(${s}, #000 0, #000 ${R(m)}%, transparent ${R(y)}%, transparent ${R(a)}%)`}}}static dots(e={}){let t=Math.max(1,e.rows??6),n=Math.max(1,e.cols??10),i=Math.max(0,e.feather??20),s=$(e.stagger??0)*.5,a=(c,l,u)=>{let d=-i+$(l)*(100+i);return u?`radial-gradient(circle farthest-corner at ${c}, transparent ${R(d)}%, #000 ${R(d+i)}%)`:`radial-gradient(circle farthest-corner at ${c}, #000 ${R(d)}%, transparent ${R(d+i)}%)`};return{size:`${R(100/n)}% ${R(100/t)}%`,repeat:"repeat",mask:(c,l)=>{let u=l?1-$(c):$(c);if(s<=0)return a("50% 50%",u,l);let d=$(u/(1-s)),p=$((u-s)/(1-s));return l?`${a("50% 50%",p,!0)}, ${a("0% 0%",d,!0)}`:`${a("50% 50%",d)}, ${a("0% 0%",p)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return Ll(e.mask(t,n),e.size,e.repeat)}};var Am=.3,zs=class o extends be{constructor(e){super(),this.duration=e.duration,this.color=e.color??"#000000",this.hold=e.hold,this.holdMs=e.holdMs,this.pattern=e.pattern??null,this.inverted=e.inverted??!1,this.uncover=e.uncover??"retreat",this.easing=e.easing}coverStyle(e,t){if(!this.pattern)return{...Ns(this.color),opacity:$(e)};let n={...Ns(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...nn.toStyle(this.pattern,e,!this.inverted)}:{...n,...nn.toStyle(this.uncover,e)}:{...n,...nn.toStyle(this.pattern,e,this.inverted)}}createTask(){let e={duration:this.duration,hold:this.hold??(this.holdMs===void 0?Am:void 0),holdMs:this.holdMs,easing:this.easing},t=1-(1-Ei(e))/2,n=.5,i=nr(e);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:"linear"}],resolve:[this.asPrev(r=>({style:{opacity:r<n?1:0}})),this.asTarget(r=>({style:{opacity:r<n?0:1}})),r=>({src:F.DefaultImagePlaceholder,style:this.coverStyle(i(r),r>=t)})]}}copy(){return new o({duration:this.duration,color:this.color,hold:this.hold,holdMs:this.holdMs,pattern:this.pattern??void 0,inverted:this.inverted,uncover:this.uncover,easing:this.easing})}};var Ks=class o extends be{constructor(e){super(),this.duration=e.duration,this.pattern=e.pattern,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(e=>({style:nn.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var qn="http://www.w3.org/2000/svg",Cm="http://www.w3.org/1999/xlink",xm=.002,wm=1,km=.12,Pm=0,$s=class o extends be{constructor(t){super();this.filterId=null;this.host=null;this.cut=null;this.duration=t.duration,this.rule=P.srcToURL(t.rule),this.feather=Math.min(wm,Math.max(xm,t.feather??km)),this.inverted=t.inverted??!1,this.easing=t.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(t=>({style:this.styleAt(t)}))]}}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>this.dispose()),n.onCanceled(()=>this.dispose()),n}copy(){return new o({duration:this.duration,rule:this.rule,feather:this.feather,inverted:this.inverted,easing:this.easing})}styleAt(t){if(t>=1)return this.dispose(),{filter:""};let n=this.ensureScaffold();if(!n)return{filter:""};let i=t*(1+this.feather),r=(this.inverted?1:-1)/this.feather,s=(this.inverted?i-1:i)/this.feather;return this.cut?.setAttribute("k3",String(r)),this.cut?.setAttribute("k4",String(s)),{filter:`url(#${n})`}}ensureScaffold(){if(typeof document>"u")return null;if(this.filterId&&this.host)return this.filterId;let t=`nl-rule-${++Pm}`,n=document.createElementNS(qn,"svg");n.setAttribute("aria-hidden","true"),n.setAttribute("data-element-type","rule-transition"),n.setAttribute("width","0"),n.setAttribute("height","0"),Object.assign(n.style,{position:"absolute",width:"0",height:"0",overflow:"hidden"});let i=document.createElementNS(qn,"filter");i.setAttribute("id",t),i.setAttribute("color-interpolation-filters","sRGB"),i.setAttribute("primitiveUnits","objectBoundingBox"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("width","100%"),i.setAttribute("height","100%");let r=document.createElementNS(qn,"feImage");r.setAttribute("href",this.rule),r.setAttributeNS(Cm,"xlink:href",this.rule),r.setAttribute("preserveAspectRatio","none"),r.setAttribute("x","0"),r.setAttribute("y","0"),r.setAttribute("width","1"),r.setAttribute("height","1"),r.setAttribute("result","rule");let s=document.createElementNS(qn,"feColorMatrix");s.setAttribute("in","rule"),s.setAttribute("type","luminanceToAlpha"),s.setAttribute("result","lum");let a=document.createElementNS(qn,"feComposite");a.setAttribute("in","lum"),a.setAttribute("in2","lum"),a.setAttribute("operator","arithmetic"),a.setAttribute("k1","0"),a.setAttribute("k2","0"),a.setAttribute("k3","0"),a.setAttribute("k4","0"),a.setAttribute("result","cut");let c=document.createElementNS(qn,"feComposite");return c.setAttribute("in","SourceGraphic"),c.setAttribute("in2","cut"),c.setAttribute("operator","in"),i.append(r,s,a,c),n.appendChild(i),document.body.appendChild(n),this.filterId=t,this.host=n,this.cut=a,t}dispose(){this.host?.remove(),this.host=null,this.cut=null,this.filterId=null}};var js=class extends li{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new Q(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var ir=class{static getActionId(e){return e.getId()}static setActionId(e,t){return e.setId(t),e}static getStaticId(e){return e.getStaticId()}static setStaticId(e,t){return e.setStaticId(t),e}static chainToActions(e){return e.getActions()}static wrapAction(e){let t=Be.isChained(e)?e.getActions():e;return Fe.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}static getLayerSrcs(e,t){return F.getSrcURLs(e,t)}static registerDisplayable(e,t,n=null,i=null){e.findElementByDisplayable(t)||(e.createDisplayable(t,n,i),e.flush())}static setElementId(e,t){e.setId(t)}static setElementStaticId(e,t){e.setStaticId(t)}static getDisplayableTransformProps(e){return{...e.transformState.get()}}static setDisplayableTransformProps(e,t,n,i={}){let r=t.transformState;i.merge===!1?r.forceOverwrite(n):r.assign(Symbol("DevTools.setDisplayableTransformProps"),n),t.markDirty(),e.getExposedState(t)?.updateStyleSync?.(),e.flush()}static getPuppetStatus(e){return e._getStatus()}static onPuppetStatusChange(e,t){return e._onStatusChange(t)}static async describePuppet(e,t){try{return await t._describe()}catch(n){return e.logger.error("DevTools","Puppet backend threw while describing itself",n),null}}static getPuppetState(e){return Lt.normalizeState(e.state)}static setPuppetState(e,t,n,i={}){t.state=i.merge===!1?Lt.normalizeState(n):Lt.mergeState(t.state,n),t._applyState().catch(r=>{e.logger.error("DevTools","Puppet backend threw while applying state",r)}),e.flush()}static async runPuppetCommand(e,t,n,i){try{await t._runCommand(n,i)||e.logger.weakWarn("DevTools",`Puppet command "${n}" was dropped: the puppet is not mounted.`)}catch(r){e.logger.error("DevTools",`Puppet backend threw while running "${n}"`,r)}}static listPuppetBackends(e){return e.listPuppetBackends()}static getCurrentDialog(e){if(e.isNvlMode()){let n=e.getNvlState();if(!n.activeDialogId||n.phase==="idle")return null;let i=e.getNvlDialog(n.activeDialogId);return i?{actionId:i.actionId||null,ended:n.phase==="awaitAdvance",mode:"nvl"}:null}let t=e.getAdvDialogState();return t?{actionId:t.actionId,ended:t.ended,mode:"adv"}:null}static onDialogStateChange(e,t){let n=[e.events.on(L.EventTypes["event:state.dialog.change"],t),e.events.on(L.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};ir.DynamicPersistent=On;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
|
|
85
85
|
@layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.isolate{isolation:isolate}.z-20{z-index:20}.container{width:100%}.\\!hidden{display:none!important}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.table{display:table}.h-\\[80px\\]{height:80px}.h-full{height:100%}.h-max{height:-moz-max-content;height:max-content}.w-1\\/2{width:50%}.w-\\[100px\\]{width:100px}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-full{min-width:100%}.flex-grow,.grow{flex-grow:1}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.resize{resize:both}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.mask-repeat{-webkit-mask-repeat:repeat;mask-repeat:repeat}.text-center{text-align:center}.text-left{text-align:left}.align-bottom{vertical-align:bottom}.break-all{word-break:break-all}.whitespace-pre-wrap{white-space:pre-wrap}.italic{font-style:italic}.ordinal{--tw-ordinal:ordinal;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.underline{text-decoration-line:underline}.decoration-dotted{text-decoration-style:dotted}.opacity-0{opacity:0}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.grayscale{--tw-grayscale:grayscale(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-filter{backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,ease);transition-duration:var(--tw-duration,0s)}.__narraleaf_content-player *{-webkit-user-select:none;-moz-user-select:none;user-select:none}.__narraleaf_content-player img{pointer-events:none;-webkit-user-drag:none;-webkit-user-select:none}.__narraleaf_content-player .pointer-disabled{pointer-events:none}.__narraleaf_content-player .pointer-disabled>:not(.pointer-disabled){pointer-events:auto}.__narraleaf_content-player img:before,.__narraleaf_content-player img:after{content:none!important;border:none!important}.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.bg-cover{background-size:cover}.bg-center{background-position:50%}.pointer-events-auto-rest *{pointer-events:auto}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}\r
|
|
86
|
-
`,document.head.appendChild(o)}export{Sn as Align,sn as AudioBusError,ni as AudioBusMixer,ti as AudioBusTree,_r as Avatar,Us as BlurDissolve,si as Camera,co as Character,lt as CommonPosition,In as CommonPositionType,vr as Condition,Fe as Control,yt as Coord2D,Di as Darkness,nt as DefaultAudioBusIds,cs as DefaultNvlContainer,Hc as DefaultNvlDialogItem,ir as DevTools,
|
|
86
|
+
`,document.head.appendChild(o)}export{Sn as Align,sn as AudioBusError,ni as AudioBusMixer,ti as AudioBusTree,_r as Avatar,Us as BlurDissolve,si as Camera,co as Character,lt as CommonPosition,In as CommonPositionType,vr as Condition,Fe as Control,yt as Coord2D,Di as Darkness,nt as DefaultAudioBusIds,cs as DefaultNvlContainer,Hc as DefaultNvlDialogItem,ir as DevTools,ed as Dialog,Hs as Dissolve,em as ExposedStateType,Bs as Exposure,Vs as FadeIn,Mc as FixedAspectRatioContainer,js as Gallery,te as Game,bo as GameMenu,Al as GameProviders,L as GameState,F as Image,be as ImageTransition,Bt as Isolated,Io as Item,Bn as KeyBindingType,Pi as KeyMap,Q as Lambda,Vn as Layer,Ap as Layout,Ai as LayoutRouterProvider,Ut as LiveGame,nn as Mask,_i as MaxAudioBusDepth,Sr as Menu,pi as NVLToken,Ht as Namespace,en as Nametag,_t as Narrator,No as Notifications,as as NvlContainer,qp as NvlDialogList,rs as NvlProvider,Pp as Page,es as PageInjectContext,ze as Pause,Fn as Persistent,bl as Player,mi as Preference,Lt as Puppet,Ws as Push,Ks as Reveal,za as RootPath,$s as RuleReveal,Ye as Scene,xe as Script,ga as SeededBusPreferenceKeys,me as Sentence,li as Service,fe as Sound,va as SoundType,mu as Stage,Zn as Storable,ai as Story,Cn as Text,ut as TextEvent,ci as TextTransition,Yu as Texts,$u as TextsPreview,zs as ThroughColor,Z as Transform,Vt as Transition,xr as Vfx,Cr as Video,ie as Word,Ji as acceptsAudioBus,Tm as b,Sm as c,gr as getActiveAudioBusTree,Mu as getWordRenderer,bm as i,Ru as registerWordRenderer,Iu as unregisterWordRenderer,wc as useAvatar,cp as useDialog,_p as useDialogOverlay,M as useGame,Wp as useIsNvlMode,Bp as useIsNvlVisible,wn as useKeyBinding,Gp as useLiveGame,$t as useNvl,os as useNvlDialogs,gp as useParams,hp as usePathname,mn as usePreference,yp as useQueryParams,Wt as useRouter,Zp as useSuspendAdvance,qr as useUIMenuContext,pp as useVoiceState};
|