narraleaf-react 0.40.0 → 0.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +2 -2
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -35,7 +35,7 @@ NarraLeaf cannot find the element with the id from the saved game`);return l.fro
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+`
36
36
  NarraLeaf cannot find the element with the id from the saved game
37
37
  This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};le.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.lineEnd":"event:state.player.lineEnd","event:state.dialog.change":"event:state.dialog.change","event:state.player.requestFlush":"event:state.player.requestFlush","event:state.player.stageClick":"event:state.player.stageClick","event:state.scene.mount":"event:state.scene.mount","event:state.scene.unmount":"event:state.scene.unmount","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes","event:state.nvl.enter":"event:state.nvl.enter","event:state.nvl.exit":"event:state.nvl.exit","event:state.nvl.dialogComplete":"event:state.nvl.dialogComplete","event:state.nvl.dialogAppend":"event:state.nvl.dialogAppend","event:state.nvl.visibilityChange":"event:state.nvl.visibilityChange","event:state.nvl.change":"event:state.nvl.change"};var L=le;var Lt=class Lt extends X{static getVoice(e,t){let n=e.getLastScene();if(!n)throw new Error("No scene found when trying to play voice");let{voiceId:i,voice:r}=t.config;return!i&&!r?null:fe.toSound(n.getVoice(i)||r)}static endVoiceWithPreference(e,t){let{voiceEndMode:n,voiceFadeDuration:i}=e.game.preference.getPreferences();if(n==="none")return null;let r=n==="fade"?Math.max(0,i):0;return e.audioManager.stop(t,r)}static cutTrailingVoice(e,t){let n=Lt.trailingVoice.get(e);n&&n!==t&&e.audioManager.isPlaying(n)&&e.timelines.attachTimeline(e.audioManager.stop(n,0)),t?Lt.trailingVoice.set(e,t):Lt.trailingVoice.delete(e)}executeAction(e,t){if(this.type===Yt.say){let n=null,i="",r=null,s=new S(v=>v).registerSkipController(new V(()=>{n?.()})),a=new we(s),c=this.contentNode.getContent(),l=e.isNvlMode(),u=e.getLiveGame(),d=e.createPresentationSnapshot(),p=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,h=Lt.getVoice(e,c);if(h){Lt.cutTrailingVoice(e,h);let v=e.audioManager.play(h);a.attachChild(v)}let f=h?e.events.on(L.EventTypes["event:state.player.lineEnd"],()=>{let v=Lt.endVoiceWithPreference(e,h);v&&e.timelines.attachTimeline(v),f?.cancel()}):null;if(l){let v=this.getId(),g=(e.getActiveNvlDialogForAction(v)||e.getLatestNvlDialogForAction(v))?.id||e.allocateNvlDialogId(v),y=c.evaluate(xe.getCtx({gameState:e}));i=ie.getText(y),u.events.emit(Ut.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let b=!1,k=()=>{b||(b=!0,e.events.emit(L.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:w}=e.ensureNvlDialog({id:g,actionId:v,character:this.callee,sentence:c,text:i});r=g;let A=e.consumeNvlTypingSuppression(),x=w&&!A?"typing":"awaitAdvance";e.activateNvlDialog(g,x,!w);let O=e.waitForNvlAdvance(g,()=>{e.settleNvlDialog(g),k()});n=()=>{O.cancel()}}else{let v=e.idManager.generateId(),T=e.createDialog(v,c,()=>{e.settleAdvDialog(v),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()})});e.beginAdvDialog(v,this.getId()),i=T.text,n=()=>{e.settleAdvDialog(v),T.cancel()}}u.setLastDialog(i,this.callee.state.name),e.timelines.attachTimeline(a);let{id:m}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:a},()=>{if(f?.cancel(),h&&e.audioManager.isPlaying(h)){let v=Lt.endVoiceWithPreference(e,h);v&&a.attachChild(v)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(d),p?u.setLastDialog(p.sentence,p.speaker):u.lastDialog=null});return e.gameHistory.push({token:m,action:this,element:{type:"say",text:i,voice:h?h.getSrc():null,voiceId:c.config.voiceId??null,character:this.callee.state.name},isPending:!0,snapshot:u.captureGameState()}),s}else if(this.type===Yt.setName){let n=this.callee.state.name;return this.callee.state.name=this.contentNode.getContent()[0],e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.name=i},[n]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("CharacterAction")}};Lt.ActionTypes=Yt,Lt.trailingVoice=new WeakMap;var it=Lt;var Pe=class Pe extends Mn{constructor(t,n){super();this.srcManager=new Re;this.events=new _;this.actions=[];this.voiceCache=new Map;this._futureActions_=[];this.labelMap=new Map;let i=Pe.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=Pe.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=Pe.DefaultUserConfig.create(n),a=Pe.DefaultSceneConfig.create({...s.get(),name:t,layers:[...s.get().layers,i,r],defaultBackgroundLayer:i,defaultDisplayableLayer:r});this.userConfig=s,this.config=a.get(),this.state=this.getInitialState(),this.localPersistent=new Fn(t)}static get DefaultSceneConfig(){return Pe._defaultSceneConfig??(Pe._defaultSceneConfig=new $({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Hn("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Hn("[[Displayable Layer]]",{zIndex:0})},{voices:t=>{let n=r=>typeof r=="object"&&r!==null,i=r=>typeof r=="function";if(!t)return null;if(n(t)&&Object.values(t).forEach(r=>{fe.isSound(r)&&Pe.validateVoice(r)}),i(t))return t;throw new Oe(`Invalid voices config: ${t}`)}}))}static validateVoice(t){if(!Ji(t.config.type,[nt.voice,nt.sound]))throw new Oe(`Voice must be a voice, but got ${t.config.type}.
38
- To prevent unintended behavior and unexpected results, the sound have to be on the voice bus (or any bus beneath it). Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof Pe}static getOwnedSounds(t){let n=[],i=t.callee;if(Pe.isScene(i)){let r=i.userConfig.get().backgroundMusic;r&&n.push(r)}if(t instanceof ee&&t.type===z.setBackgroundMusic){let[r]=t.contentNode.getContent();r&&n.push(r)}return n}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t,n){return new qe({backgroundImage:i=>i.toData(),backgroundMusic:i=>{let r=i?.toData();if(!r)return null;let s=i.getId();return s?{...r,id:s}:r}},{backgroundImage:i=>t.state.backgroundImage.fromData(i),backgroundMusic:i=>{if(!i)return null;let r=i.id?n?.get(i.id):void 0,s=r instanceof fe?r:t.state.backgroundMusic;return s?s.fromData(i):null}})}get __futureActions__(){return this._futureActions_}get local(){return this.localPersistent}get background(){return this.state.backgroundImage}get backgroundLayer(){return this.config.defaultBackgroundLayer}get displayableLayer(){return this.config.defaultDisplayableLayer}setBackground(t,n){return this.chain().chain(Fe.do([this.background.char(t,n)]))}jumpTo(t,n={}){let i=q({},n instanceof Vt?{transition:n}:n);return i.returnable?this._callScene(t,i.transition):this.combineActions(new Fe({allowFutureScene:!1}),r=>(r.chain(new ee(r,"scene:preUnmount",new C().setContent([]))).chain(this._initScene(t))._transitionToScene(i.transition,t).chain(this._exit()),r))._jumpTo(t)}_callScene(t,n){return this.combineActions(new Fe({allowFutureScene:!1}),i=>(i.chain(this._preSuspend(t)).chain(this._initScene(t))._transitionToScene(n,t),i))._callTo(t)._resume(t)}setBackgroundMusic(t,n){return this.chain(new ee(this.chain(),z.setBackgroundMusic,new C().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new ui(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},u=new ee(this.chain(),z.nvlEnd,new C().setContent([l])),d=[...c,u];super.constructNodes(d);let p=new ee(this.chain(),z.nvlBlock,new C().setContent([d,l]));return this.chain(p)}action(t){return this.actions=t,this}preloadImage(t){if(!P.isImageSrc(t))throw new Error("Invalid image source: "+t);return(Array.isArray(t)?t:[t]).forEach(i=>{this.srcManager.register({type:"image",src:i})}),this}toData(){return{state:Pe.getStateSerializer(this).serialize(this.state)}}fromData(t,n){return this.state=Pe.getStateSerializer(this,n).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new ee(this.chain(),"scene:action",new C);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(m=>Be.isChained(m)?m.fromChained(m):m).flat(2),s=[],a=[],c=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(m=>{Be.isChained(m)||(m instanceof N?s.push(m):m instanceof An?a.push(m):m instanceof Dt&&c.push(m))});let l=[],u=[],d=new Map;s.forEach(m=>{m.config.isWearable?u.push(m):m.config.autoInit&&l.push(m);for(let v of m.config.wearables){if(d.get(v)&&d.get(v)!==m)throw new Error(`Wearable image cannot be used multiple times
38
+ To prevent unintended behavior and unexpected results, the sound have to be on the voice bus (or any bus beneath it). Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof Pe}static getOwnedSounds(t){let n=[],i=t.callee;if(Pe.isScene(i)){let r=i.userConfig.get().backgroundMusic;r&&n.push(r)}if(t instanceof ee&&t.type===z.setBackgroundMusic){let[r]=t.contentNode.getContent();r&&n.push(r)}return n}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t,n){return new qe({backgroundImage:i=>i.toData(),backgroundMusic:i=>{let r=i?.toData();if(!r)return null;let s=i.getId();return s?{...r,id:s}:r}},{backgroundImage:i=>t.state.backgroundImage.fromData(i),backgroundMusic:i=>{if(!i)return null;let r=i.id?n?.get(i.id):void 0,s=r instanceof fe?r:t.state.backgroundMusic;return s?s.fromData(i):null}})}get __futureActions__(){return this._futureActions_}get local(){return this.localPersistent}get background(){return this.state.backgroundImage}get backgroundLayer(){return this.config.defaultBackgroundLayer}get displayableLayer(){return this.config.defaultDisplayableLayer}setBackground(t,n){return this.combineActions(new Fe,()=>this.background.char(t,n))}jumpTo(t,n={}){let i=q({},n instanceof Vt?{transition:n}:n);return i.returnable?this._callScene(t,i.transition):this.combineActions(new Fe({allowFutureScene:!1}),r=>(r.chain(new ee(r,"scene:preUnmount",new C().setContent([]))).chain(this._initScene(t))._transitionToScene(i.transition,t).chain(this._exit()),r))._jumpTo(t)}_callScene(t,n){return this.combineActions(new Fe({allowFutureScene:!1}),i=>(i.chain(this._preSuspend(t)).chain(this._initScene(t))._transitionToScene(n,t),i))._callTo(t)._resume(t)}setBackgroundMusic(t,n){return this.chain(new ee(this.chain(),z.setBackgroundMusic,new C().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new ui(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},u=new ee(this.chain(),z.nvlEnd,new C().setContent([l])),d=[...c,u];super.constructNodes(d);let p=new ee(this.chain(),z.nvlBlock,new C().setContent([d,l]));return this.chain(p)}action(t){return this.actions=t,this}preloadImage(t){if(!P.isImageSrc(t))throw new Error("Invalid image source: "+t);return(Array.isArray(t)?t:[t]).forEach(i=>{this.srcManager.register({type:"image",src:i})}),this}toData(){return{state:Pe.getStateSerializer(this).serialize(this.state)}}fromData(t,n){return this.state=Pe.getStateSerializer(this,n).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new ee(this.chain(),"scene:action",new C);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(m=>Be.isChained(m)?m.fromChained(m):m).flat(2),s=[],a=[],c=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(m=>{Be.isChained(m)||(m instanceof N?s.push(m):m instanceof An?a.push(m):m instanceof Dt&&c.push(m))});let l=[],u=[],d=new Map;s.forEach(m=>{m.config.isWearable?u.push(m):m.config.autoInit&&l.push(m);for(let v of m.config.wearables){if(d.get(v)&&d.get(v)!==m)throw new Error(`Wearable image cannot be used multiple times
39
39
  Maybe you bind the same wearable image to multiple parent images
40
40
  Parent Conflict (src: `+d.get(v)?.state.currentSrc+`)
41
41
  Current Parent (src: `+m.state.currentSrc+")");d.set(v,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),f=new C(this.sceneRoot,void 0,h||void 0).setContent(this);return h?.setParent(f),this.sceneRoot?.setContentNode(f),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 re&&r.type===oe.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 re&&r.type===oe.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 f=Re.getPreloadableSrc(t,c);if(f&&this.srcManager.register(f),!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 Ia(c.callee,l))this.srcManager.register({type:"image",src:P.srcToURL(u)})}else if(c instanceof re){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}.
@@ -60,7 +60,7 @@ actual: ${i}`)}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,
60
60
  `)return Ve.createElement("br",{key:D});let K=rt(F);return Ve.createElement("span",{key:D,style:{...K,...Hr()},className:Eo("inline-block",F.config.className)},Ve.createElement(hc,{word:F,vertical:Ue,tateChuYoko:g,done:!1,style:K,renderer:Ir(F.config.render)}))};return Ve.createElement("div",{...b,className:Eo("whitespace-pre-wrap",u),style:{...ft,...Or(v,T),...d}},gn.map(I))}function gc(o){return Ve.createElement(zr,{...o,key:o.dialog?.config.action.id})}function Wu({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(zr,{...r,dialog:s,key:s.config.action.id})}function Bu(o){let e=Rt();return Ve.createElement(zr,{...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(Wu,{...o}):Ve.createElement(Bu,{...o})}var zu=fn;import Ro,{useEffect as Ku,useLayoutEffect as $u,useMemo as vc,useRef as ju,useState as qu}from"react";import Lo from"react";var Kr=Lo.createContext(null);function $r(){let o=Lo.useContext(Kr);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var jr=Lo.createContext(null);function yc(){let o=Lo.useContext(jr);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=ju(null),{register:l,unregister:u,getIndex:d}=yc(),[p,h]=qu(-1),{choose:f,evaluated:m,gameState:v}=$r(),T=p===-1?null:m[p],g=vc(()=>xe.getCtx({gameState:v}),[v]),{hidden:y,disabled:b}=vc(()=>{if(!T)return{hidden:!1,disabled:!1};let A=T.config.hidden?.evaluate(g)?.value??!1,x=!A&&(T.config.disabled?.evaluate(g)?.value??!1);return{hidden:A,disabled:x}},[T,g]);$u(()=>{if(!c.current)return;let A=c;l(A);let x=d(A);return h(x),c.current.dataset.index=x.toString(),()=>u(A)},[l,u,d]),Ku(()=>{if(!t)return;let A=x=>{x.key.toLowerCase()===t.toLowerCase()&&!x.ctrlKey&&!x.metaKey&&(x.preventDefault(),x.stopPropagation(),k())};return window.addEventListener("keydown",A,!0),()=>{window.removeEventListener("keydown",A,!0)}},[t]);function k(){if(p===-1||!m[p]||y||b)return;let A=m[p];f({...A,evaluated:ie.getText(A.words||[])})}let w=T&&!y;return Ro.createElement(Ro.Fragment,null,Ro.createElement("button",{className:o,style:{...e,display:w?e?.display??void 0:"none"},onClick:k,ref:c,disabled:b},w&&Ro.createElement(gc,{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:v,evaluatedWords:T.words})})))}import Mo from"react";import{AnimatePresence as Yu}from"motion/react";function No({children:o,...e}){let t=Yu;return Mo.createElement(Mo.Fragment,null,Mo.createElement("div",{...e},Mo.createElement(t,null,o)))}import Sc from"react";function en({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=Sc.useContext(Cn),c=e??o?.character??a?.config.action.character??null,l=n??c?.config.color,u=i??t??c?.state.name;return Sc.createElement("div",{...s,style:{color:l?Ln(l):void 0,...r}},u)}import _u from"clsx";import Ju from"react";import qr,{createContext as Xu,useContext as Qu,useState as Tc}from"react";var kn=class kn{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(kn.EventTypes["event:preloaded.add"],e),this.events.emit(kn.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(kn.EventTypes["event:preloaded.remove"],e),this.events.emit(kn.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Re.getSrc(e)}};kn.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=kn;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.src.clear(),this.decoded.clear()})}static getImage(e,t,n){return Zs(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}has(e){return this.src.has(e)}add(e,t){return this.src.set(e,t),this}remove(e){return 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.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){this.add(t,p);let h=await o.decodeImage(p);h&&n?.retainDecoded&&this.src.get(t)===p&&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.src.delete(n),this.decoded.delete(n));for(let n of this.decoded.keys())t.has(n)||this.decoded.delete(n);return this}};var Yr=Xu(null);function bc({children:o}){let e=R(),[t]=Tc(()=>new $e),[n]=Tc(()=>new Go(e));return qr.createElement(qr.Fragment,null,qr.createElement(Yr,{value:{preloaded:t,cacheManager:n}},o))}function Kt(){if(!Yr)throw new Error("usePreloaded must be used within a PreloadedProvider");return Qu(Yr)}function Ac(){let o=Rt(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return tp(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?N.getSrcURL(s):null,c=s&&N.isTagSrc(s)?[...s.state.currentSrc]:null,l=Ra({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=ep(l.source);return{visible:!!u,src:u,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function Zu({className:o,style:e,alt:t,...n}){let i=Ac(),{cacheManager:r}=Kt();if(!i.visible||!i.src)return null;let s=r.get(i.src)||i.src;return Ju.createElement("img",{...n,"data-element-type":"dialog-avatar",className:_u("dialog-avatar",o),src:s,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function ep(o){return o?P.srcToURL(o):null}function tp(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var Xr=Zu;import{useEffect as np}from"react";function ip(){let o=Rt(),[e]=se(o.deps),t=ie.getText(o.config.evaluatedWords);return np(()=>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 Qr,useMemo as op,useRef as rp,useState as Cc}from"react";function sp(){let o=Rt(),[e]=se(o.deps),[t,n]=Cc(!0),[i,r]=Cc(!0),s=rp(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;Qr(()=>o.events.on(Me.Events.onFlush,()=>{e()}).cancel,[o]);let u=op(()=>{if(!c)return null;try{return it.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);Qr(()=>{s.current=null,r(!0)},[c]),Qr(()=>{let m=!1,v=null,T=null,g=null;if(!u){n(!0);return}n(!1);let y=()=>{m||n(!0)};v=a.audioManager.getToken(u),v&&(v.isPlaying()||n(!0),T=()=>y(),g=()=>y(),v.once("ended",T),v.once("stop",g));let b=a.events.on(L.EventTypes["event:state.player.lineEnd"],()=>{y()});return()=>{m=!0,b.cancel(),v&&T&&v.off("ended",T),v&&g&&v.off("stop",g)}},[a,u]);let d=Fo(async m=>{let v=m??u;if(!v)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let T=v instanceof URL?fe.voice(v.toString()):typeof v=="string"?fe.voice(v):v,g=await a.getLiveGame().playSound(T);s.current=g;let y=()=>{r(!0)};return g.once("ended",y),g.once("stop",y),g},[a,u]),p=Fo(()=>u,[u]),h=Fo(()=>l,[l]),f=Fo(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:d,getVoice:p,getVoiceId:h,getVoiceSrc:f}}import _r,{createContext as vp,useContext as Sp,useEffect as kc,useRef as Tp}from"react";import{useState as ap}from"react";function Oo(o){let[e]=ap(o);return e}import{AnimatePresence as cp}from"motion/react";var Ho=cp;import Ti,{createContext as mp,useContext as fp,useEffect as hp,useRef as gp}from"react";import{useEffect as yi,useLayoutEffect as lp}from"react";function up(){let o=Wt(),[e]=se();return yi(()=>o.onChange(e).cancel,[]),o.getPathname()}function pp(){let{router:o,path:e}=Si(),[t]=se();return yi(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function dp(){let o=Wt(),[e]=se();return yi(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Vo(o,e){let t=Wt();lp(()=>t.onUpdate(()=>o(t)).cancel,e),yi(()=>{o(t)},[])}function vi(){let o=Wt(),[e]=se();return yi(()=>o.onChange(e).cancel,[]),e}var xc=mp(null);function bi({children:o,path:e,consumedBy:t}){let i={router:Wt(),path:e,consumedBy:t};return Ti.createElement(xc,{value:i},o)}function Si(){let o=fp(xc);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
61
  This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function yp({children:o,name:e,propagate:t}){let n=R(),[i]=se(),{path:r,router:s,consumedBy:a}=Si(),c=s.joinPath(r,e),l=Oo(()=>s.createToken(c+"@layout")),u=s.getCurrentPath(),d=gp(!1),p=f=>{d.current=f,i()},h=s.matchPath(u,c);if(vi(),Vo(f=>{let m=f.matchPath(f.getCurrentPath(),c);if(d.current&&!m){if(!o){p(!1);return}f.registerUnmountingPath(l)}m&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(l),m&&!d.current&&!f.isTransitioning()&&p(!0)},[h,o]),hp(()=>{if(!h)return;let f=s.mount(c);return()=>{f.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 Ti.createElement(bi,{path:c},Ti.createElement(Ho,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),p(!1)}},h&&d.current&&o))}function wc({children:o}){return vi(),Ti.createElement(bi,{path:dn.rootPath},Ti.createElement(To,{"data-layout-path":dn.rootPath,key:dn.rootPath},o))}var Jr=vp(null);function bp(){return Sp(Jr)}function Ap({children:o,name:e}){let[t]=se(),{path:n,router:i,consumedBy:r}=Si(),s=bp(),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=Tp(!1),f=g=>{h.current=g,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.");vi(),Vo(g=>{let y=p&&g.exactMatch(g.getCurrentPath(),n)||g.exactMatch(g.getCurrentPath(),l);if(h.current&&!y){if(!o){f(!1);return}g.registerUnmountingPath(u)}y&&g.isPathsUnmounting()&&g.unregisterUnmountingPath(u),y&&!h.current&&!g.isTransitioning()&&f(!0)},[m,o]),kc(()=>{if(!m)return;let g=p?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{g.cancel()}},[l,m]),kc(()=>()=>{i.unregisterUnmountingPath(u),f(!1)},[]);let v=_r.createElement(bi,{path:n,consumedBy:c},_r.createElement(Ho,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),f(!1)}},m&&h.current&&o));return(g=>s?_r.createElement(Jr,{value:{name:null}},g):g)(v)}import Zr,{useCallback as Cp,useEffect as es,useImperativeHandle as xp,useMemo as Pc,useRef as ts,useState as wp}from"react";var kp=50,Pp={position:"relative",width:"100%",height:"100%",overflow:"hidden"},Ec={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function Ep(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function Dc(o,e){return e==null?o:Math.max(o,e)}function Dp(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 Lc=Zr.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=ts(null),[f,m]=wp({...Ec,width:"0px",height:"0px"}),v=ts(u),T=ts(null);es(()=>{v.current=u},[u]);let g=Cp(()=>{let k=h.current;if(!k)return;let w=k.clientWidth,A=k.clientHeight;if(w<=0||A<=0||e<=0)return;let x=Dp(w,A,e),O=Dc(x.width,n),U=Dc(x.height,i),ue=T.current;(!ue||ue.width!==O||ue.height!==U)&&(T.current={width:O,height:U},m({...Ec,width:`${O}px`,height:`${U}px`}));let Ne=t>0?O/t:1;v.current?.({width:O,height:U,scale:Ne,containerWidth:w,containerHeight:A})},[e,t,n,i]),y=Pc(()=>_s(g,typeof r=="number"?r:kp),[g,r]);es(()=>{g()},[g]),es(()=>{let k=new ResizeObserver(()=>{y()});h.current&&k.observe(h.current);let w=()=>{y()};return window.addEventListener("resize",w),()=>{k.disconnect(),window.removeEventListener("resize",w)}},[y]),xp(p,()=>({requestUpdate:g}),[g]);let b=Pc(()=>Ep(l),[l]);return Zr.createElement("div",{id:c,ref:h,style:Pp,...b},Zr.createElement("div",{className:s,style:{...f,...a}},d))}),Rc=Lc;function Lp(){return R().getLiveGame()}import os from"react";import Rp,{createContext as Ip,useContext as Mp,useEffect as Np,useState as Ic}from"react";var Gp={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},Mc=Ip({state:Gp,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function $t(){return Mp(Mc)}function ns(){let{dialogs:o}=$t();return o}function Fp(){let{isActive:o}=$t();return o}function Op(){let{isVisible:o}=$t();return o}function is({children:o}){let t=R().getLiveGame().getGameState(),[n,i]=Ic(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=Ic(null);Np(()=>{let c=f=>({...f,dialogs:[...f.dialogs]}),l=t.events.on(L.EventTypes["event:state.nvl.enter"],(f,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"],(f,m)=>{i(c(t.getNvlState())),s(m||null)}),h=t.events.on(L.EventTypes["event:state.nvl.change"],f=>{i(c(f))});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 Rp.createElement(Mc.Provider,{value:a},o)}import{AnimatePresence as Hp,motion as Vp}from"motion/react";import Up from"clsx";function rs({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=$t(),{ratio:r}=he(),s=R(),a=i?.duration?i.duration/1e3:.3;return os.createElement(Hp,null,n&&os.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},os.createElement(Vp.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:Up("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 Pn from"react";function ss({renderDialogItem:o,dialogs:e}){return Pn.createElement(rs,{className:"bg-black/80 text-white p-16 inset-8"},Pn.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?Pn.createElement(en,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=Pn.createElement(fn,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return Pn.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}):Pn.createElement(Pn.Fragment,null,r,s))})))}import Tt,{useMemo as Wp}from"react";import Nc from"clsx";function Bp({children:o,className:e,style:t,renderDialogItem:n}){let i=ns(),{state:r}=$t();return Tt.createElement("div",{"data-element-type":"nvl-dialog-list",className:Nc("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(zp,{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(Gc,{entry:s,index:a})))))}function Gc({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:Nc("nvl-dialog-item",t),style:n},r&&Tt.createElement(en,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function zp({entry:o,children:e}){let n=R().getLiveGame().getGameState(),i=Wp(()=>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(Cn,{value:c},e)}import Uo from"react";import{createPortal as Kp}from"react-dom";var as=Uo.createContext(null),$p={Portal:()=>null,measure:()=>null,container:null};function jp(){let o=Uo.useContext(as);return Uo.useMemo(()=>{if(!o)return $p;let e=t=>{let n=o.offsetWidth;return!n||!t.width?1:t.width/n};return{container:o,Portal:({children:t})=>Kp(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 qp}from"react";function Yp(o){let e=R();qp(()=>{if(!o)return;let t=e.getLiveGame().getGameState();if(t)return t.suspendAdvance()},[o,e])}function Oc({state:o}){let e=R(),t=Wt(),n=cs(null),i=cs(null),r=cs(!1),[s]=mn(te.Preferences.skipDelay),[a]=mn(te.Preferences.skipInterval),[c]=xn("skipAction");return Qp(()=>{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 u=()=>{i.current&&(clearTimeout(i.current),i.current=null),n.current&&(clearInterval(n.current),n.current=null),r.current=!1},d=h=>{if(!o.isAdvanceSuspended()&&e.keyMap.match("skipAction",h.key)&&e.preference.getPreference(te.Preferences.skip)&&!r.current){o.logger.verbose("KeyEventAnnouncer","Skipping");let f=()=>{n.current=setInterval(()=>{o.events.emit(L.EventTypes["event:state.player.skip"],!1)},a)};u(),o.events.emit(L.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?f():i.current=setTimeout(f,s)}},p=h=>{e.keyMap.match("skipAction",h.key)&&u()};if(e.config.useWindowListener){let h=e.getLiveGame().onWindowEvent("keydown",d).cancel,f=e.getLiveGame().onWindowEvent("keyup",p).cancel;return()=>{u(),h(),f()}}else{let h=e.getLiveGame().onPlayerEvent("keydown",d).cancel,f=e.getLiveGame().onPlayerEvent("keyup",p).cancel;return()=>{u(),h(),f()}}},[t,s,a,c]),Fc.createElement(Fc.Fragment,null)}import Vc,{useEffect as _p}from"react";function Hc({onStage:o,dialogShown:e,advanceSuspended:t}){return o?e?t?"ignore":"advance":"restoreDialog":"ignore"}function Jp(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var Uc=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],Zp=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]','[data-element-type="interactive-word"]','[data-element-type="dialog-overlay"]'];function ed(o,e){return!o||e&&Uc.some(t=>!!o.closest(t))?!1:[...Zp,...Uc].some(t=>!!o.closest(t))}function Wc(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 Bc({state:o}){let e=R();return _p(()=>{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)||!Wc(i,t))return;let s=o.mainContentNode;if(s&&(!s.contains(r)||!Wc(i,s))||Jp(r)||ed(r,o.isNvlMode()))return;let a=Hc({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]),Vc.createElement(Vc.Fragment,null)}import{useEffect as zc}from"react";function ls({gameState:o}){let e=o.audioManager,[t,n]=mn("globalVolume");return zc(()=>{n(e.getGlobalVolume())},[]),zc(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as Wo,useRef as td}from"react";function Kc(o){let e=Re.catSrc(o.srcManager?.src||[]),t=Re.catSrc(o.srcManager?.getFutureSrc()||[]),n=[],i=[],r=new Set;for(let s of e.image){let a=Re.getSrc(s);!a||r.has(a)||(r.add(a),n.push(a))}for(let s of t.image){let a=Re.getSrc(s);!a||r.has(a)||(r.add(a),i.push(a))}return{critical:n,lookAhead:i,all:[...n,...i],criticalAudio:e.audio}}function $c({state:o}){let{preloaded:e,cacheManager:t}=Kt(),n=R(),i=td(new Set),[r]=se(),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 Wo(()=>o.events.on(L.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),Wo(()=>{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=Kc(a),h=new Dn(n.config.preloadConcurrency,0),f=new Dn(n.config.preloadConcurrency,n.config.preloadDelay),m=o.logger.group(s,!0),v=!1;o.logger.debug(s,"preloading:",p,a);let T=(g,y,b,k)=>{y.forEach((w,A)=>{if(t.has(w)||t.isPreloading(w)){o.logger.debug(s,`Image already loaded (${b} ${A+1}/${y.length})`,w);return}g.addTask(()=>new Promise(x=>{t.preload(o,w,{retainDecoded:k}).onFinished(()=>{o.logger.debug(s,`Image loaded (${b} ${A+1}/${y.length})`,w),x()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${b} ${A+1}/${y.length})`,w),x()})}))})};T(h,p.critical,"first scene",!0),T(f,p.lookAhead,"look-ahead",!1);for(let g of p.criticalAudio)o.audioManager.preload(g);return m.end(),h.start().then(async()=>{o.logger.info(s,"Image preload (first scene)",`loaded ${t.size()} images in ${performance.now()-d}ms`),e.events.emit($e.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit($e.EventTypes["event:preloaded.ready"]),!v&&(await f.start(),!v&&(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"]),()=>{v=!0,u()}},[a,l]),Wo(()=>{i.current.clear()},[a]),Wo(()=>{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(g=>Re.getPreloadableSrc(l,g)).filter(function(g){return g!==null});p.filter(function(g){return g?.activeType==="scene"}).forEach(g=>{i.current.has(g)||i.current.add(g)});let f=Re.catSrc([...i.current,...p]),m=new Dn(n.config.preloadConcurrency,n.config.preloadDelay),v=[],T=o.logger.group(s);o.logger.debug(s,"preloading:",f);for(let g of f.image){let y=Re.getSrc(g);if(y){if(v.push(y),t.has(y)||t.isPreloading(y)){o.logger.debug(s,`Image already loaded (${f.image.indexOf(g)+1}/${f.image.length})`,y);continue}m.addTask(()=>new Promise(b=>{t.preload(o,y).onFinished(()=>{o.logger.debug(s,`Image loaded (${f.image.indexOf(g)+1}/${f.image.length})`,y),b()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${f.image.indexOf(g)+1}/${f.image.length})`,y),b()})}))}}T.end(),m.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(v)})},[c,l]),null}import Ai from"react";import zo from"react";import us,{useEffect as ps,useLayoutEffect as ds,useRef as Bo,useState as ms}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]=ms(null),[p,h]=ms(null),f=Bo(null),m=us.useRef(null),[v]=ms(()=>new Vi("displayable.refGroup")),T=Bo(v.next()),g=Bo(rt()),b=R().getLiveGame().getGameState(),k=typeof a=="function"?a(u):a,[w]=se([p,u,g]);ps(()=>b.events.depends([b.events.on(L.EventTypes["event:state.player.skip"],ft)]).cancel,[p,u,g]),ds(()=>{if(U(),!u)return;if(g.current.some(([M])=>!M.current))throw new E("Displayable: Trying to access transition groups before they are mounted");let{controller:I,task:F}=u,D=M=>{g.current.forEach(([ge],De)=>{let st=F.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(...M),ir=q(k[De]||k[k.length-1]||{},Ri);Ne(ge,c?c(ir):ir)})},K=I.onUpdate(D);D(F.animations.map(M=>M.start));let ae=!1;return Promise.all(g.current.map(([M])=>{let ge=M.current;return ge?.waitForLoad?ge.waitForLoad():Promise.resolve()})).then(()=>{ae||I.start()}),()=>{ae=!0,K.cancel()}},[u]),ps(()=>{if(!m.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),ds(()=>{let I=e.toStyle(b,i);return Object.assign(m.current.style,I),O(),b.logger.debug("Displayable","Initial style applied",m.current,I),bt(),()=>{_e()}},[]);let A=Bo(()=>{});A.current=()=>{u||!m.current||(U(),!(p||f.current)&&(Object.assign(m.current.style,e.toStyle(b,i)),O()))},ds(()=>{f.current&&!o._getLoop()&&_e(),A.current()});let{ratio:x}=he();ps(()=>x.onUpdate(()=>{A.current(),requestAnimationFrame(()=>A.current())}),[x]);function O(){if(l)for(let{ref:I,project:F}of l)I.current&&Object.assign(I.current.style,F(e.get()))}function U(){let I=typeof a=="function"?a(u):a;if(!g.current||!g.current.length)throw new E("Displayable: Transition group refs are not initialized correctly");g.current.some(([F])=>!F.current)||g.current.forEach(([F],D)=>{Ne(F,I[D]||I[I.length-1]||{})})}function ue(I){b.logger.debug("Displayable","Transform applied",e.toStyle(b,i),m.current),w(),r?.(I)}function Ne(I,F){if(!I.current)throw new E("Displayable: Trying to assign properties to unmounted element");oo(I.current,F,c)}function _e(){f.current&&(f.current.stop(),f.current=null,b.logger.debug("Displayable","Loop stopped",o))}function bt(){let I=o._getLoop();if(!I){_e();return}f.current||At(I.transform,I.options)}function At(I,F){p&&(p.abort(),h(null)),_e(),m.current&&(f.current=I.startLoop(e,{gameState:b,ref:m,overwrites:i,companionRefs:l},F))}function gn(I,F){return mt(new Z({},{duration:I?.duration??0,ease:I?.ease??"linear"}),F)}function mt(I,F){p&&(p.abort(),h(null)),_e();let D=I.animate(e,{gameState:b,ref:m,overwrites:i,companionRefs:l}),K=new we(D);return b.timelines.attachTimeline(K),D.onSkipControllerRegister(ae=>{ae.onAbort(()=>{K.abort(),h(null)})}),h(D),D.then(()=>{h(null),ue(I),F(),bt()}),K}function B(I,F){u&&u.controller.complete();let D=I.createTask(b),K=I.requestAnimations(D.animations),ae=new S().registerSkipController(new V(K.cancel)),M=new we(ae);ae.skipController.onAbort(()=>{K.cancel()}),K.onCanceled(()=>{M.abort(),d(null),b.logger.debug("Displayable","Transition cancelled",I)}),K.onComplete(()=>{Ue(),d(null),s?.(I),F(),ae.resolve()}),b.timelines.attachTimeline(M),d({task:D,controller:K,transition:I,resolve:F});let ge;if(g.current=D.resolve.map(De=>{let st=us.createRef(),Ge=typeof De=="function"?void 0:De.key;if(!Ge)return[st,v.next()];if(Ge==="target")return ge=v.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,M}function Ee(I){return b.logger.debug("initDisplayable",o),mt(Z.immediate(e.get()),I)}function ft(){t&&p&&(p.abort(),h(null),b.logger.debug("transform skipped")),n&&u&&(u.controller.complete(),b.logger.debug("transition skipped"))}function rt(){return[[us.createRef(),T.current]]}function Ue(){g.current.forEach(([I])=>{I.current=null}),g.current=rt()}return{transformRef:m,transitionRefs:g.current,transitionTask:u,initDisplayable:Ee,applyTransform:mt,applyTransition:B,applyLoop:At,stopLoop:gn,updateStyleSync:U,flush:w,deps:[p,u,g]}}import{useEffect as nd}from"react";function xt(o,e,t=[]){let i=R().getLiveGame().getGameState();return nd(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function fs({state:o,text:e}){let{ratio:t}=he(),[n]=se(),{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]),zo.createElement(zt.Div,{"data-element-type":"text"},zo.createElement(zt.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([h,f])=>zo.createElement("span",{key:f,ref:h,className:e.config.className},zo.createElement("span",null,e.state.text)))))}import Mt,{forwardRef as od,useCallback as qc,useImperativeHandle as rd,useRef as jo,useState as Yc}from"react";import Ko,{useEffect as hs,useRef as zn,forwardRef as id}from"react";var jc=id(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=zn(null),{ratio:a}=he(),[c,l]=Ko.useState(0),[u,d]=Ko.useState(0),p=zn(null),h=zn(null),f=R(),m=zn(!1),v=zn(null),T=zn(null);Ko.useImperativeHandle(r,()=>s.current,[]),hs(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>{let k=()=>{let w=s.current;return!w||typeof w.decode!="function"?Promise.resolve():w.decode().catch(()=>{})};return m.current?k():(v.current||(v.current=new Promise(w=>{T.current=w})),v.current.then(k))},configurable:!0}})},[]),hs(()=>(g(),a.onUpdate(g)),[o]),hs(()=>{let k=new MutationObserver(w=>{w.forEach(A=>{A.type==="attributes"&&A.attributeName==="src"&&s.current&&g()})});return s.current&&k.observe(s.current,{attributes:!0}),()=>{k.disconnect()}},[o]);function g(){if(s.current&&s.current.naturalWidth){let k,w,A;if(s.current.naturalWidth*s.current.naturalHeight===1)k=a.state.width,w=a.state.height,A=`${k} / ${w}`;else{let ue=t?f.config.width/s.current.naturalWidth:1;k=s.current.naturalWidth*a.state.scale*ue,w=s.current.naturalHeight*a.state.scale*ue,A="auto"}let x=p.current,O=!x||x.w!==k||x.h!==w||x.ar!==A,U=!!o&&h.current!==o;if(!O&&!U)return;O&&(p.current={w:k,h:w,ar:A},l(k),d(w),s.current.style.aspectRatio=A),o&&(h.current=o,o(k,w))}}function y(){g(),m.current=!0,T.current&&(T.current(),T.current=null,v.current=null),e&&e()}function b(){m.current=!0,T.current&&(T.current(),T.current=null,v.current=null)}return Ko.createElement("img",{ref:s,onLoad:y,onError:b,width:c,height:u,alt:"",src:n,style:i})});jc.displayName="AspectScaleImage";var $o=jc;import Xc from"clsx";import{motion as sd}from"motion/react";var ad={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},Qc=od(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=jo(null),a=jo([]),c=o.findIndex(l=>l!==null);return rd(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(()=>{})}),[]),Mt.createElement("div",{ref:s},o.map((l,u)=>l===null?null:Mt.createElement($o,{key:"layer-"+u,ref:d=>{a.current[u]=d},src:t(l),style:ad,autoFit:e,onSizeChanged:u===c?n:void 0,onLoad:u===c?i:void 0})))});Qc.displayName="LayerStack";function cd(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 ld(o){return N.isStaticSrc(o)?o.state.currentSrc:N.getSrcURL(o)??void 0}var ud={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function pd({image:o,state:e}){let[t]=Yc(()=>new _),[n,i]=Yc([]),{cacheManager:r}=Kt(),s=jo([]),a=jo(null),c=N.isLayeredSrc(o)?N.getSrcURLs(o):null;function l(A){return!P.isDataURI(A)&&!r.has(A)&&!r.isPreloading(A)&&!s.current.includes(A)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${A}".
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(A)),r.get(A)||A}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:h,applyTransition:f,applyTransform:m,applyLoop:v,stopLoop:T,updateStyleSync:g,flush:y,deps:b}=jt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:A=>{if(c)return(A?A.task.resolve:[null]).map(U=>U&&typeof U=="function"?{style:ud}:{style:cd(o.state.darkness)});let x=A?A.transition._getCurrentSrc():ld(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):N.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:A=>A.src?{...A,src:l(A.src)}:A});xt(o,{createWearable:A=>{i(x=>[...x,A])},disposeWearable:A=>{i(x=>x.filter(O=>O.getId()!==A.getId()))},initDisplayable:h,applyTransform:m,applyLoop:v,stopLoop:T,applyTransition:f,events:t,updateStyleSync:g,flush:y},[...b]);let k=qc((A,x)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${A}px`,height:`${x}px`}))},[t]),w=qc(()=>{t.emit("event:image.onLoad")},[t]);return Mt.createElement(sd.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},Mt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?d.map(([A,x],O)=>{let U=p?p.task.resolve[O]:null;if(U&&typeof U=="function")return Mt.createElement($o,{key:x,ref:A,autoFit:o.config.autoFit});let ue=U?U.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():c;return Mt.createElement(Qc,{key:x,ref:A,src:ue||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:O===0?k:void 0,onLoad:O===0?w:void 0})}):d.map(([A,x],O)=>Mt.createElement($o,{key:x,ref:A,autoFit:o.config.autoFit,onSizeChanged:O===0?k:void 0,onLoad:O===0?w:void 0})),Mt.createElement("div",{className:Xc("w-full h-full top-0 left-0 absolute")},n.map(A=>Mt.createElement("div",{className:Xc("w-full h-full relative"),key:"wearable-"+A.getId()},Mt.createElement(_c,{image:A,state:e}))))))}var _c=Mt.memo(pd),Jc=_c;import Yo,{useEffect as el,useMemo as gd,useRef as gs}from"react";var dd=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,md=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function Zc(o,e){if(typeof e!="string"||!e.length)return o;if(dd.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=fd(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+hd(r+e.replace(/\\/g,"/"))}function fd(o){let e=md.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function hd(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 qo=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 ys({state:o,puppet:e}){let[t]=se(),{cacheManager:n}=Kt(),i=gs(null),r=gd(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=gs(r);s.current=r;let{transformRef:a,transitionRefs:c,initDisplayable:l,applyTransform:u,applyLoop:d,stopLoop:p,applyTransition:h,updateStyleSync:f,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:f,flush:t},[...m]),el(()=>{let g=i.current;if(!g)return;let y=o.game,b=e.config.backend,k=y.getPuppetBackend(b);if(!k)return e._setStatus("missing-backend"),y.getPuppetBackendRegistry().reportMissing(b,x=>{o.logger.warn("Puppet",x)}),()=>{e._setStatus("unmounted")};let w;try{w=k.mount(g,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:T,resolveSibling:x=>T(Zc(e.config.src,x)),warn:(x,O)=>{o.logger.warn("Puppet",x,O)}})}catch(x){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${b}" threw while mounting "${e.config.src}"`,x),()=>{e._setStatus("unmounted")}}let A=!1;return e._attachInstance(w),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!A&&typeof w.ready=="function"?w.ready():void 0).then(()=>{A||e._setStatus("ready")}).catch(x=>{A||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${b}" failed to load "${e.config.src}"`,x))}),()=>{A=!0,e._attachInstance(null),e._setStatus("unmounted");try{w.dispose()}catch(x){o.logger.error("Puppet",`Backend "${b}" threw while disposing`,x)}}},[]);let v=gs(r);el(()=>{let g=v.current;if(g.width===r.width&&g.height===r.height)return;v.current=r;let y=e._getInstance();if(!(!y||typeof y.resize!="function"))try{y.resize(r)}catch(b){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,b)}},[r]);function T(g){return P.isDataURI(g)?g:n.get(g)||g}return Yo.createElement(zt.Div,{"data-element-type":"puppet"},Yo.createElement(zt.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},c.map(([g,y])=>Yo.createElement("div",{key:y,ref:g,className:e.config.className},Yo.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function vs({state:o,displayable:e}){return Ai.createElement(Ai.Fragment,null,e.map(t=>{if(t instanceof An)return Ai.createElement(fs,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof N)return Ai.createElement(Jc,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof Dt)return Ai.createElement(ys,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Xo,{useEffect as yd}from"react";import{motion as vd}from"motion/react";function tl({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]),yd(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Xo.createElement(Xo.Fragment,null,Xo.createElement(vd.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])=>Xo.createElement("div",{className:"relative w-full h-full",ref:p,key:h},t))))}async function nl(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 Sd from"clsx";import{useEffect as Ss,useRef as Td}from"react";import Ts from"react";function bs({state:o,className:e,elements:t}){let{scene:n,layers:i}=t,r=Td(null);return Ss(()=>(o.stageTransition.registerScene(n,r.current),()=>{o.stageTransition.registerScene(n,null)}),[]),Ss(()=>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,[]),Ss(()=>(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 nl(o,n,s,a)}}),Ts.createElement("div",{className:Sd(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])=>Ts.createElement(tl,{state:o,layer:s,key:s.getId()},Ts.createElement(vs,{state:o,displayable:a}))))}import{AnimatePresence as xd}from"motion/react";import{useEffect as wd,useReducer as kd,useRef as Ci}from"react";import bd from"clsx";import qt,{useCallback as As,useMemo as Ad,useRef as Cd}from"react";function Cs({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=R(),a=Cd([]),c=As(f=>(a.current.push(f),a.current.indexOf(f)),[]),l=As(f=>{let m=a.current.indexOf(f);m!==-1&&a.current.splice(m,1)},[]),u=As(f=>a.current.indexOf(f),[]),d=s.config.menu,p=Ad(()=>e.map(f=>({...f,words:f.prompt.evaluate(xe.getCtx({gameState:n}))})),[]);function h(f){t(f)}return qt.createElement(qt.Fragment,null,qt.createElement(Kr,{value:{evaluated:p,choose:h,gameState:n}},qt.createElement(jr,{value:{register:c,unregister:l,getIndex:u}},qt.createElement(Bt,{className:"absolute"},r&&o&&qt.createElement(fi,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),qt.createElement(zt.Div,{color:"green",border:"dashed",className:bd("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},qt.createElement(d,{items:p.map((f,m)=>m)})))))}function il({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 Pd from"clsx";import xi from"react";var ol=120;function rl({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 xs({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=Ci(!1),a=Ci({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),c=Ci([]),l=Ci(null),u=Ci(null),[,d]=kd(T=>T+1,0),p=()=>{u.current&&(clearTimeout(u.current),u.current=null)},h=()=>{let T=l.current;if(!T)return;let g=a.current;T.forEach(({slot:y,presenceKey:b})=>{g.slotKeys.get(y)===b&&g.slotKeys.delete(y),g.exitingKeys.add(b)}),l.current=null,u.current=null,c.current=[],d()};wd(()=>()=>{p()},[]);let f=a.current,m=i.length>0?i.map(({action:T,onClick:g},y)=>({action:T,slot:y,useTypeEffect:!s.current,onFinished:b=>{b!==void 0&&(s.current=b),g(),o.events.emit(L.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((T,g)=>{if(!T.action.prompt||!T.action.words)return[];let y=f.menuPromptIds.get(T);return y||(y=`menu-prompt-${n.getId()}-${f.nextKey++}`,f.menuPromptIds.set(T,y)),[{action:{sentence:T.action.prompt,words:T.action.words,character:null,id:y},slot:g,useTypeEffect:!1}]}),v=rl({sources:m,menuCount:r.length,presence:f,retained:l.current,lastActive:c.current,sceneId:n.getId()});return l.current=v.retained,c.current=v.lastActive,v.retaining?u.current||(u.current=setTimeout(h,ol)):p(),xi.createElement("div",{className:Pd(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs",style:{pointerEvents:v.interactive?"auto":"none"}},xi.createElement(xd,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{a.current.exitingKeys.clear()}},v.items.map(({action:T,onFinished:g,presenceKey:y,active:b,useTypeEffect:k})=>xi.createElement(fi,{gameState:o,key:y,action:T,active:b,onFinished:g,useTypeEffect:k}))),r.map(({action:T,onClick:g},y)=>xi.createElement("div",{key:"menu-"+y,"data-element-type":"menu"},xi.createElement(Cs,{state:o,prompt:T.prompt,choices:T.choices,renderPrompt:!T.prompt,afterChoose:b=>{s.current=!1,g(b),o.stage.next()},words:T.words}))))}import hn,{useEffect as Ed,useRef as ws}from"react";import{motion as Dd}from"motion/react";function sl({state:o,camera:e,children:t}){let n=ws(null),i=ws(null),r=ws(null),{transformRef:s,transitionRefs:a,initDisplayable:c,applyTransition:l,applyTransform:u,applyLoop:d,stopLoop:p,updateStyleSync:h,deps:f}=jt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,companionRefs:[{ref:n,project:Da},{ref:i,project:Pa},{ref:r,project:Ea}],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},[...f]),Ed(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),hn.createElement(hn.Fragment,null,hn.createElement(Dd.div,{className:"absolute w-full h-full",ref:s,"data-element-type":"camera"},a.map(([m,v])=>hn.createElement("div",{className:"relative w-full h-full",ref:m,key:v},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 Ld from"react";import{useEffect as ks,useRef as Rd}from"react";import{useCallback as al}from"react";function cl(o){let e=al(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=al(()=>{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 Ps({gameState:o,video:e}){let t=Rd(null),{show:n,hide:i}=cl(t);ks(()=>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,[]),ks(()=>{i(),e.state.display&&n()},[]),ks(()=>{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
63
+ To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(A)),r.get(A)||A}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:h,applyTransition:f,applyTransform:m,applyLoop:v,stopLoop:T,updateStyleSync:g,flush:y,deps:b}=jt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:A=>{if(c)return(A?A.task.resolve:[null]).map(U=>U&&typeof U=="function"?{style:ud}:{style:cd(o.state.darkness)});let x=A?A.transition._getCurrentSrc():ld(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):N.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:A=>A.src?{...A,src:l(A.src)}:A});xt(o,{createWearable:A=>{i(x=>[...x,A])},disposeWearable:A=>{i(x=>x.filter(O=>O.getId()!==A.getId()))},initDisplayable:h,applyTransform:m,applyLoop:v,stopLoop:T,applyTransition:f,events:t,updateStyleSync:g,flush:y},[...b]);let k=qc((A,x)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${A}px`,height:`${x}px`}))},[t]),w=qc(()=>{t.emit("event:image.onLoad")},[t]);return Mt.createElement(sd.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},Mt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?d.map(([A,x],O)=>{let U=p?p.task.resolve[O]:null;if(U&&typeof U=="function")return Mt.createElement($o,{key:x,ref:A,autoFit:o.config.autoFit});let ue=U?U.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():c;return Mt.createElement(Qc,{key:x,ref:A,src:ue||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:O===0?k:void 0,onLoad:O===0?w:void 0})}):d.map(([A,x],O)=>Mt.createElement($o,{key:x,ref:A,autoFit:o.config.autoFit,onSizeChanged:O===0?k:void 0,onLoad:O===0?w:void 0})),Mt.createElement("div",{className:Xc("w-full h-full top-0 left-0 absolute")},n.map(A=>Mt.createElement("div",{className:Xc("w-full h-full relative"),key:"wearable-"+A.getId()},Mt.createElement(_c,{image:A,state:e}))))))}var _c=Mt.memo(pd),Jc=_c;import Yo,{useEffect as el,useMemo as gd,useRef as gs}from"react";var dd=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,md=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function Zc(o,e){if(typeof e!="string"||!e.length)return o;if(dd.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=fd(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+hd(r+e.replace(/\\/g,"/"))}function fd(o){let e=md.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function hd(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 qo=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 ys({state:o,puppet:e}){let[t]=se(),{cacheManager:n}=Kt(),i=gs(null),r=gd(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=gs(r);s.current=r;let{transformRef:a,transitionRefs:c,initDisplayable:l,applyTransform:u,applyLoop:d,stopLoop:p,applyTransition:h,updateStyleSync:f,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:f,flush:t},[...m]),el(()=>{let g=i.current;if(!g)return;let y=o.game,b=e.config.backend,k=y.getPuppetBackend(b);if(!k)return e._setStatus("missing-backend"),y.getPuppetBackendRegistry().reportMissing(b,x=>{o.logger.warn("Puppet",x)}),()=>{e._setStatus("unmounted")};let w;try{w=k.mount(g,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:T,resolveSibling:x=>T(Zc(e.config.src,x)),warn:(x,O)=>{o.logger.warn("Puppet",x,O)}})}catch(x){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${b}" threw while mounting "${e.config.src}"`,x),()=>{e._setStatus("unmounted")}}let A=!1;return e._attachInstance(w),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!A&&typeof w.ready=="function"?w.ready():void 0).then(()=>{A||e._setStatus("ready")}).catch(x=>{A||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${b}" failed to load "${e.config.src}"`,x))}),()=>{A=!0,e._attachInstance(null),e._setStatus("unmounted");try{w.dispose()}catch(x){o.logger.error("Puppet",`Backend "${b}" threw while disposing`,x)}}},[]);let v=gs(r);el(()=>{let g=v.current;if(g.width===r.width&&g.height===r.height)return;v.current=r;let y=e._getInstance();if(!(!y||typeof y.resize!="function"))try{y.resize(r)}catch(b){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,b)}},[r]);function T(g){return P.isDataURI(g)?g:n.get(g)||g}return Yo.createElement(zt.Div,{"data-element-type":"puppet"},Yo.createElement(zt.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},c.map(([g,y])=>Yo.createElement("div",{key:y,ref:g,className:e.config.className},Yo.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function vs({state:o,displayable:e}){return Ai.createElement(Ai.Fragment,null,e.map(t=>{if(t instanceof An)return Ai.createElement(fs,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof N)return Ai.createElement(Jc,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof Dt)return Ai.createElement(ys,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Xo,{useEffect as yd}from"react";import{motion as vd}from"motion/react";function tl({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]),yd(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Xo.createElement(Xo.Fragment,null,Xo.createElement(vd.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])=>Xo.createElement("div",{className:"relative w-full h-full",ref:p,key:h},t))))}async function nl(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 Sd from"clsx";import{useEffect as Ss,useRef as Td}from"react";import Ts from"react";function bs({state:o,className:e,elements:t}){let{scene:n,layers:i}=t,r=Td(null);return Ss(()=>(o.stageTransition.registerScene(n,r.current),()=>{o.stageTransition.registerScene(n,null)}),[]),Ss(()=>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,[]),Ss(()=>(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 nl(o,n,s,a)}}),Ts.createElement("div",{className:Sd(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])=>Ts.createElement(tl,{state:o,layer:s,key:s.getId()},Ts.createElement(vs,{state:o,displayable:a}))))}import{AnimatePresence as xd}from"motion/react";import{useEffect as wd,useReducer as kd,useRef as Ci}from"react";import bd from"clsx";import qt,{useCallback as As,useMemo as Ad,useRef as Cd}from"react";function Cs({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=R(),a=Cd([]),c=As(f=>(a.current.push(f),a.current.indexOf(f)),[]),l=As(f=>{let m=a.current.indexOf(f);m!==-1&&a.current.splice(m,1)},[]),u=As(f=>a.current.indexOf(f),[]),d=s.config.menu,p=Ad(()=>e.map(f=>({...f,words:f.prompt.evaluate(xe.getCtx({gameState:n}))})),[e,n]);function h(f){t(f)}return qt.createElement(qt.Fragment,null,qt.createElement(Kr,{value:{evaluated:p,choose:h,gameState:n}},qt.createElement(jr,{value:{register:c,unregister:l,getIndex:u}},qt.createElement(Bt,{className:"absolute"},r&&o&&qt.createElement(fi,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),qt.createElement(zt.Div,{color:"green",border:"dashed",className:bd("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},qt.createElement(d,{items:p.map((f,m)=>m)})))))}function il({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 Pd from"clsx";import xi from"react";var ol=120;function rl({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 xs({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=Ci(!1),a=Ci({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),c=Ci([]),l=Ci(null),u=Ci(null),[,d]=kd(T=>T+1,0),p=()=>{u.current&&(clearTimeout(u.current),u.current=null)},h=()=>{let T=l.current;if(!T)return;let g=a.current;T.forEach(({slot:y,presenceKey:b})=>{g.slotKeys.get(y)===b&&g.slotKeys.delete(y),g.exitingKeys.add(b)}),l.current=null,u.current=null,c.current=[],d()};wd(()=>()=>{p()},[]);let f=a.current,m=i.length>0?i.map(({action:T,onClick:g},y)=>({action:T,slot:y,useTypeEffect:!s.current,onFinished:b=>{b!==void 0&&(s.current=b),g(),o.events.emit(L.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((T,g)=>{if(!T.action.prompt||!T.action.words)return[];let y=f.menuPromptIds.get(T);return y||(y=`menu-prompt-${n.getId()}-${f.nextKey++}`,f.menuPromptIds.set(T,y)),[{action:{sentence:T.action.prompt,words:T.action.words,character:null,id:y},slot:g,useTypeEffect:!1}]}),v=rl({sources:m,menuCount:r.length,presence:f,retained:l.current,lastActive:c.current,sceneId:n.getId()});return l.current=v.retained,c.current=v.lastActive,v.retaining?u.current||(u.current=setTimeout(h,ol)):p(),xi.createElement("div",{className:Pd(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs",style:{pointerEvents:v.interactive?"auto":"none"}},xi.createElement(xd,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{a.current.exitingKeys.clear()}},v.items.map(({action:T,onFinished:g,presenceKey:y,active:b,useTypeEffect:k})=>xi.createElement(fi,{gameState:o,key:y,action:T,active:b,onFinished:g,useTypeEffect:k}))),r.map(({action:T,onClick:g},y)=>xi.createElement("div",{key:"menu-"+y,"data-element-type":"menu"},xi.createElement(Cs,{state:o,prompt:T.prompt,choices:T.choices,renderPrompt:!T.prompt,afterChoose:b=>{s.current=!1,g(b),o.stage.next()},words:T.words}))))}import hn,{useEffect as Ed,useRef as ws}from"react";import{motion as Dd}from"motion/react";function sl({state:o,camera:e,children:t}){let n=ws(null),i=ws(null),r=ws(null),{transformRef:s,transitionRefs:a,initDisplayable:c,applyTransition:l,applyTransform:u,applyLoop:d,stopLoop:p,updateStyleSync:h,deps:f}=jt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,companionRefs:[{ref:n,project:Da},{ref:i,project:Pa},{ref:r,project:Ea}],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},[...f]),Ed(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),hn.createElement(hn.Fragment,null,hn.createElement(Dd.div,{className:"absolute w-full h-full",ref:s,"data-element-type":"camera"},a.map(([m,v])=>hn.createElement("div",{className:"relative w-full h-full",ref:m,key:v},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 Ld from"react";import{useEffect as ks,useRef as Rd}from"react";import{useCallback as al}from"react";function cl(o){let e=al(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=al(()=>{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 Ps({gameState:o,video:e}){let t=Rd(null),{show:n,hide:i}=cl(t);ks(()=>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,[]),ks(()=>{i(),e.state.display&&n()},[]),ks(()=>{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
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 f=t.current;return h||f.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(f.currentTime=0,new Promise(m=>{let v=!1,T=null,g=[],y=()=>{v||(v=!0,c.delete(y),T&&T(),g.forEach(b=>b()),m())};c.add(y),T=o.schedule(({retry:b})=>{if(v)return;if(f.readyState<3){let x=()=>{f.removeEventListener("loadeddata",x),b()};f.addEventListener("loadeddata",x),g.push(()=>f.removeEventListener("loadeddata",x));return}let k=()=>y(),w=()=>y(),A=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),y()};f.addEventListener("ended",k),f.addEventListener("stopped",w),f.addEventListener("error",A),g.push(()=>{f.removeEventListener("ended",k),f.removeEventListener("stopped",w),f.removeEventListener("error",A)}),f.play().catch(x=>{o.logger.error("Failed to play video: "+x),y()})},10)}))},pause:()=>{if(!t.current)throw l();t.current.pause()},resume:()=>{if(!t.current)throw l();return t.current.play().catch(f=>{o.logger.error("Failed to resume video: "+f)})},stop:()=>{if(!t.current)throw l();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:f=>{if(!t.current)throw l();t.current.currentTime=f}}))},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 Ld.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 Id,{useEffect as Md,useRef as Nd}from"react";var ll={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 Gd(o,e){return e===void 0?"linear":Array.isArray(e)?`cubic-bezier(${e.join(", ")})`:typeof e=="string"&&ll[e]?ll[e]:(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease")}function Es({gameState:o,vfx:e}){let t=Nd(null);return Md(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,c=new Set,l=new Set,u=[],d=b=>{n.style.transition="",n.style.opacity=String(b)},p=()=>{n.play().catch(b=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+b)})},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(b=>{let k=!1,w=()=>x(),A=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),x()},x=()=>{k||(k=!0,l.delete(x),n.removeEventListener("loadeddata",w),n.removeEventListener("error",A),b())};l.add(x),n.addEventListener("loadeddata",w),n.addEventListener("error",A),(n.readyState>=2||n.error)&&x()}),f=(b,k,w)=>{let A=k?.duration??0,x=++s;return w.instant||A<=0?(d(b),Promise.resolve()):new Promise(O=>{let U=!1,ue=null,Ne=()=>{U||(U=!0,l.delete(Ne),ue!==null&&clearTimeout(ue),s===x&&t.current&&d(b),O())};l.add(Ne),n.style.transition=`opacity ${A}ms ${Gd(o,k?.easing)}`,n.offsetWidth,n.style.opacity=String(b),ue=setTimeout(Ne,A)})},m=b=>{r||(r=!0,i=b,o.mountState(e,{show:async k=>{a=!0;let w={instant:!1};c.add(w);try{if(await h(),!t.current)return;n.playbackRate=k?.rate??e.config.playbackRate,e.state.paused||p(),await f(k?.opacity??e.config.opacity,k,w)}finally{c.delete(w)}},hide:async k=>{a=!0;let w={instant:!1};c.add(w);try{await f(0,k,w),t.current&&n.pause()}finally{c.delete(w)}},pause:()=>{n.pause()},resume:()=>{p()},setRate:k=>{n.playbackRate=k}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&d(e.config.opacity)},0)))},v=()=>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)},g=o.events.on(L.EventTypes["event:state.player.skip"],()=>{c.size===0&&l.size===0||(c.forEach(b=>{b.instant=!0}),[...l].forEach(b=>b()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),y=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&t.current&&p()};return document.addEventListener("visibilitychange",y),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",v),n.addEventListener("error",T),n.readyState>=3?m(!1):n.error&&T(),()=>{n.removeEventListener("canplay",v),n.removeEventListener("error",T),document.removeEventListener("visibilitychange",y),g.cancel(),u.forEach(b=>b()),[...l].forEach(b=>b()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),Id.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 Fd from"clsx";import Od,{useCallback as Hd,useEffect as Qo,useRef as Vd}from"react";function Ds({children:o,className:e,gameState:t}){let{ratio:n}=he(),i=R(),[r]=se(),s=Vd(null),a=i.config.minWidth,c=i.config.minHeight,l=Hd(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 Qo(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Qo(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Qo(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Qo(()=>t.events.on(L.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),Od.createElement(Rc,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:Fd(e),onUpdate:l},o)}import ul,{useEffect as Ud,useRef as Wd,useState as pl}from"react";function Ls({src:o,width:e,height:t}){let[n,i]=pl({x:0,y:0}),[r,s]=pl(!1),a=Wd(null),{ratio:c}=he();return Ud(()=>{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]),ul.createElement(Bt,{ref:a,className:"overflow-hidden absolute"},ul.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 dl from"react";import tn from"react";function Rs({error:o,errorInfo:e}){return R().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 _o=class extends dl.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?dl.createElement(Rs,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import hl from"clsx";import W,{useEffect as Nt,useReducer as gl,useState as Kn}from"react";import{flushSync as yl}from"react-dom";import{useRef as Bd}from"react";import{useEffect as zd}from"react";function ml({gameState:o}){let e=Bd(null);return zd(()=>(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 Kd}from"react";function Is({gameState:o}){let[e]=se(),{ratio:t}=he(),n=o.notificationMgr;Kd(()=>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 fl({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 vl({story:o=si.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]=gl(D=>D+1,0),[f,m]=gl(D=>D+1,0),[v,T]=Kn(0),g=R(),[y]=Kn(()=>new L(g,{update:h,forceUpdate:()=>{y.logger.weakWarn("Player","force update"),yl(()=>{h()})},forceRemount:()=>{y.logger.weakWarn("Player","force remount"),yl(()=>{T(D=>D+1),h()})},next:Ue})),b=W.createRef(),k=W.createRef(),[w,A]=Kn(!1),x=W.useRef(!1),O=W.useRef(null),U=W.useRef(null),{preloaded:ue}=Kt(),[Ne,_e]=Kn(!1),bt=W.useRef(!1),[At,gn]=Kn(!1),mt=W.useRef(!1),B=W.useRef(null),Ee=W.useRef(!1),[ft]=Kn(new Map);function rt(D){return{game:g,gameState:y,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable(),scene:D}}function Ue(){let D=()=>{ft.forEach(M=>M.cancel())};if(y.rollLock.isLocked())return;D();let K=!1,ae=0;for(;!K;){if(ae++>g.config.maxStackModelLoop)throw new E("Max stack model loop reached");let M=g.getLiveGame().next();if(!M){if(g.getLiveGame().stackModel&&!g.getLiveGame().stackModel.isEmpty())continue;break}if(S.isAwaitable(M)){if(O.current===M)break;O.current=M,M.onSettled(()=>{M.isFailed()||(O.current===M&&(O.current=null),Ue())}),M.onFailed(ge=>{O.current===M&&(O.current=null),y.logger.error("Player",ge)}),K=!0;break}if(M instanceof En){if(U.current===M)break;U.current=M,M.nextUnlock().then(()=>{U.current===M&&(U.current=null),Ue()}),K=!0;break}if(Xe.isCalledActionResult(M)&&M.wait&&Xe.isStackModelsAwaiting(M.wait.type,M.wait.stackModels)){if(O.current===M)break;if(O.current=M,M.wait){let ge=Xe.executeStackModelGroup(M.wait.type,M.wait.stackModels);ge.then(()=>{O.current===M&&(O.current=null),Ue()}),ge.onFailed(De=>{O.current===M&&(O.current=null),y.logger.error("Player",De)})}K=!0;break}y.handle(M)}y.stage.update()}Nt(()=>{y.audioManager.initialize()},[]),Nt(()=>(g.getLiveGame().setGameState(y),o&&!g.getLiveGame().isPlaying()&&g.getLiveGame().loadStory(o),o?.entryScene&&!y.getPreloadingScene()&&!y.getLastScene()&&y.preloadScene(o.entryScene),y.playerCurrent=b.current,y.mainContentNode=k.current,()=>{g.getLiveGame().setGameState(void 0),y.playerCurrent=null}),[g,o]),Nt(()=>ct(()=>{A(!0);let D=y.getLastScene(),K=[];D?K.push(D.events.once("event:scene.mount",()=>{y.stage.next()}).cancel):y.stage.next();let ae=y.events.on(L.EventTypes["event:state.end"],()=>{c&&c({game:g,gameState:y,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable()})});return y.stage.update(),()=>{D&&K.forEach(M=>M()),ae.cancel()}}),[]),Nt(()=>ct(()=>{w&&i&&!x.current&&(x.current=!0,y.stage.forceUpdate(),g.hooks.trigger("init",[]),i({game:g,gameState:y,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable()}))}),[w]),Nt(()=>ct(()=>{if(Ne&&s&&!bt.current){bt.current=!0;let D=B.current||y.getLastScene()||y.getPreloadingScene(),K=rt(D);s(K)}}),[Ne]),Nt(()=>ct(()=>{if(At&&!mt.current){mt.current=!0;let D=B.current||y.getLastScene()||y.getPreloadingScene(),K=rt(D);g.markPreloadComplete(K)&&r&&r(K)}}),[At]),Nt(()=>y.events.on(L.EventTypes["event:state.scene.mount"],D=>{B.current||(B.current=D,m())}).cancel,[]),Nt(()=>{if(!At||!d||Ee.current||g.isFirstSceneReady())return;let D=B.current||y.getLastScene();if(!D)return;let K=null,ae=null,M=!1;Ee.current=!0;let ge=()=>{M=!0,Ee.current=!1;let De=rt(D);g.markFirstSceneReady(De)&&a&&a(De)};return typeof requestAnimationFrame=="function"?K=requestAnimationFrame(()=>{ae=setTimeout(ge,0)}):ae=setTimeout(ge,0),()=>{M||(Ee.current=!1,K!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(K),ae!==null&&clearTimeout(ae))}},[d,f,p,At]),Nt(()=>ue.events.depends([ue.events.on($e.EventTypes["event:preloaded.ready"],()=>{_e(!0),y.stage.update(),o&&g.getLiveGame().isPlaying()&&Ue()}),ue.events.on($e.EventTypes["event:preloaded.complete"],()=>{gn(!0)})]).cancel,[]),Nt(()=>{y.flushDep=p},[p]);let I=e||g.config.width,F=t||g.config.height;return W.createElement(_o,{onError:l},W.createElement("div",{style:{width:typeof I=="number"?`${I}px`:I,height:typeof F=="number"?`${F}px`:F},className:hl(n,"__narraleaf_content-player"),ref:b,tabIndex:0},W.createElement(Ds,{className:hl("flex-grow overflow-auto"),gameState:y},W.createElement(ls,{gameState:y}),W.createElement(ml,{gameState:y}),W.createElement(Bt,{className:"absolute",ref:k,style:{cursor:y.game.config.cursor?"none":"auto",overflow:y.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},g.config.cursor&&W.createElement(Ls,{src:g.config.cursor,width:g.config.cursorWidth,height:g.config.cursorHeight}),W.createElement($d,{show:Ne&&d,key:v},W.createElement(is,null,W.createElement(Oc,{state:y}),W.createElement(Bc,{state:y}),W.createElement(jd,{state:y},W.createElement("div",{className:"w-full h-full absolute",style:{isolation:"isolate"},"data-element-type":"scene-group"},y.getSceneElements().map(D=>W.createElement(bs,{key:"scene-"+D.scene.getId(),state:y,elements:D}))),W.createElement(qd,{state:y}),y.getVideos().map((D,K)=>W.createElement("div",{className:"w-full h-full absolute",key:"video-"+K,"data-element-type":"video"},W.createElement(Ps,{gameState:y,video:D}))),y.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(Es,{gameState:y,vfx:D})))),y.getSceneElements().map(D=>W.createElement(xs,{key:"scene-dialogs-"+D.scene.getId(),state:y,elements:D})),W.createElement(Yd,{NvlComponent:g.config.nvlDialog}))),W.createElement($c,{state:y}),W.createElement(wc,null,u),W.createElement(Is,{gameState:y})))))}function $d({children:o,show:e}){return W.createElement(W.Fragment,null,e?o:null)}function jd({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?W.createElement(sl,{state:o,camera:t},e):W.createElement(W.Fragment,null,e)}function qd({state:o}){let e=W.useRef(null);return Nt(()=>(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 Yd({NvlComponent:o}){let{dialogs:e,state:t}=$t(),i=R().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 $n from"react";function Sl({children:o,game:e}){return $n.createElement($n.Fragment,null,$n.createElement(Ka,null,$n.createElement(Va,{game:e},$n.createElement(bc,null,$n.createElement(za,null,o)))))}var Xd=(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))(Xd||{});import Qd from"clsx";import wt,{useEffect as bl,useRef as _d,useState as Jd}from"react";function Tl(o){return o?{className:"",ariaHidden:!1}:{className:"opacity-0",ariaHidden:!0}}import{motion as Zd,useIsPresent as em}from"motion/react";var tm={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function nm({children:o,initial:e,transition:t,...n}){let i=R(),r=Rt(),{ratio:s}=he(),[a]=mn(te.Preferences.showDialog),c=_d(null),[l]=xn("nextAction"),u=em(),[d,p]=Jd(null),h=Tl(a);function f(){a&&(r.config.gameState.isAdvanceSuspended()||r.requestComplete())}return bl(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
65
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 v=r.events.on(Me.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",m),v.cancel()}},[r,l]),bl(()=>{let m=i.preference.onPreferenceChange(te.Preferences.autoForward,v=>{v&&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:Qd("absolute bottom-0 w-full h-full",h.className),"aria-hidden":h.ariaHidden,onClick:f,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(as,{value:d},wt.createElement(Zd.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 Al({children:o,...e}){let t=Rt();return!t.config.action.sentence||!t.config.action.words?null:wt.createElement(nm,{...e},o)}var Xp=Al;function Cl(){return wt.createElement(Al,null,wt.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},wt.createElement(Xr,null),wt.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},wt.createElement(en,null),wt.createElement(fn,{...tm}))))}var ki={say:Cl,menu:il,notification:fl,nvlDialog:ss};var Jo=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 xl=(e=>(e.game="game",e))(xl||{}),Qe=class Qe{constructor(e){this.hooks=new Wi;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new di(Qe.DefaultPreference);this.audioBuses=new ti(()=>this.config.audioBuses??[],ga(this.preference));this.keyMap=new Pi({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new _;this.puppetBackends=new qo;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=q(Qe.DefaultConfig,e),this.plugins=new Jo(this),this.router=new dn(this)}configure(e){let[t,n]=oa(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=q(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,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=xl,Qe.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var te=Qe;var Zo=class Zo 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===oe.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===oe.doAsync){if(r.length===0)return super.executeAction(t,n);let s=Zo.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===oe.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===oe.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===oe.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===oe.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===oe.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===oe.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===oe.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===oe.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,f=null,m=null,v=null,T=()=>{m?.cancel(),v?.cancel(),f&&(clearTimeout(f),f=null)},g=()=>{h||(h=!0,T(),a.resolve())};return m=t.events.on(L.EventTypes["event:state.player.stageClick"],g),v=t.events.on(L.EventTypes["event:state.player.skip"],g),p!==null&&(f=setTimeout(g,p)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(y=>{y.onAbort(()=>{h||(h=!0,T(),c.abort())})}),s}else{if(this.type===oe.label)return super.executeAction(t,n);if(this.type===oe.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===oe.break||this.type===oe.waitForClick||this.type===oe.label||this.type===oe.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===oe.break)return super.stringifyWithContent("Control","break");if(this.type===oe.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===oe.label||this.type===oe.jump){let[a]=this.contentNode.getContent(),c=this.type===oe.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(";"))}};Zo.ActionTypes=oe;var re=Zo;var Fe=class o extends ce{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(re.ActionTypes.do,t)}doAsync(t){return this.push(re.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(re.ActionTypes.any,t)}all(t){return this.pushUnchained(re.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(re.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(re.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=Q.from(t);return this.pushWithLambda(re.ActionTypes.while,n,i)}breakLoop(){let t=new re(this.chain(),re.ActionTypes.break,new C().setContent([]));return this.chain(t)}sleep(t){return this.push(re.ActionTypes.sleep,[],t)}waitForClick(){let t=new re(this.chain(),re.ActionTypes.waitForClick,new C().setContent([]));return this.chain(t)}label(t){let n=new re(this.chain(),re.ActionTypes.label,new C().setContent([t]));return this.chain(n)}jump(t){let n=new re(this.chain(),re.ActionTypes.jump,new C().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new re(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 re(this.chain(),t,new C().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new re(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 j=class j extends Ke{static get DefaultUserConfig(){return j._defaultUserConfig??(j._defaultUserConfig=new $({name:"(anonymous)",autoInit:!0,src:j.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...ne.DefaultTransformState.getDefaultConfig()},{position:e=>G.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):j.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:j.isLayeredSrc(e)?null:j.isTagSrc(e)&&e.config.src.resolve?j.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):j.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=>j.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(j.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new j({src:e})}constructor(e={}){super();let t=j.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:j.StateSerializer.serialize(this.state),transformState:ne.TransformStateSerializer.serialize(this.transformState.get()),loop:this._serializeLoop()}}fromData(e){return this.state=j.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(!j.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(!j.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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "narraleaf-react",
3
- "version": "0.40.0",
3
+ "version": "0.40.1",
4
4
  "description": "A React visual novel player framework",
5
5
  "type": "module",
6
6
  "main": "./dist/main.js",