narraleaf-react 0.33.0 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js
CHANGED
|
@@ -1,81 +1,84 @@
|
|
|
1
|
-
var
|
|
1
|
+
var pe={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",applyLoop:"displayable:applyLoop",stopLoop:"displayable:stopLoop",init:"displayable:init",bringToFront:"displayable:bringToFront"},Yt={say:"character:say",action:"character:action",setName:"character:setName"},_={action:"scene:action",init:"scene:init",exit:"scene:exit",jumpTo:"scene:jumpTo",setBackgroundMusic:"scene:setBackgroundMusic",preUnmount:"scene:preUnmount",transitionToScene:"scene:transitionToScene",nvlBlock:"scene:nvlBlock",nvlShow:"scene:nvlShow",nvlHide:"scene:nvlHide",nvlEnd:"scene:nvlEnd"};var mt={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},Ws={action:"condition:action"},Bs={action:"script:action"},zs={action:"menu:action"},Gt={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume",mute:"sound:mute",seek:"sound:seek"},oe={action:"control:action",do:"control:do",doAsync:"control:doAsync",any:"control:any",all:"control:all",allAsync:"control:allAsync",repeat:"control:repeat",while:"control:while",break:"control:break",sleep:"control:sleep",waitForClick:"control:waitForClick",label:"control:label",jump:"control:jump"},Fi={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},Xn={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},yn={action:"layer:action",setZIndex:"layer:setZIndex"},wt={action:"video:action",preload:"video:preload",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"},Xt={action:"vfx:action",preload:"vfx:preload",show:"vfx:show",hide:"vfx:hide",pause:"vfx:pause",resume:"vfx:resume",setRate:"vfx:setRate"},Ze={action:"puppet:action",setMotion:"puppet:setMotion",setExpression:"puppet:setExpression",setSkin:"puppet:setSkin",setParam:"puppet:setParam",setSlot:"puppet:setSlot",command:"puppet:command"};var Ks=(p=>(p[p.string=0]="string",p[p.number=1]="number",p[p.boolean=2]="boolean",p[p.object=3]="object",p[p.array=4]="array",p[p.function=5]="function",p[p.symbol=6]="symbol",p[p.undefined=7]="undefined",p[p.null=8]="null",p[p.date=9]="date",p[p.regexp=10]="regexp",p[p.other=11]="other",p))(Ks||{}),ir=(function(o){return typeof o=="string"?0:typeof o=="number"?1:typeof o=="boolean"?2:typeof o=="object"?Array.isArray(o)?4:o===null?8:o instanceof Date?9:o instanceof RegExp?10:3:typeof o=="function"?5:typeof o=="symbol"?6:typeof o>"u"?7:11});ir.DataTypes=Ks;function K(o,e,...t){let n=(s,a)=>Object.prototype.hasOwnProperty.call(s,a),i={},r=(s,a,l)=>ir(a)===3&&ir(l)===3?a.constructor!==Object||l.constructor!==Object?l||a:K(a,l):Array.isArray(a)&&Array.isArray(l)?l&&l.length>0?[...l]:[...a]:a===void 0&&Array.isArray(l)?[...l]:l===void 0?Array.isArray(a)?[...a]:a:Array.isArray(l)?[...l]:l;for(let s in o)n(o,s)&&(i[s]=r(s,o[s],e[s]));for(let s in e)n(e,s)&&!n(i,s)&&(typeof e[s]=="object"&&e[s]!==null?e[s].constructor===Object?i[s]=K({},e[s]):Array.isArray(e[s])?i[s]=[...e[s]]:i[s]=e[s]:i[s]=e[s]);if(t.length){let[s,...a]=t;return K(i,s,...a)}return i}var qe=class qe{constructor(e=(n=>n),t){this.solved=!1;this.aborted=!1;this.failed=!1;this.error=null;this.listeners=[];this.failListeners=[];this.settledListeners=[];this.onRegisterSkipController=[];this.skipControllerAbortToken=null;this.settledNotified=!1;this.receiver=e,this.skipController=t,this.__stack=or()}static isAwaitable(e){return e instanceof qe}static fromPromise(e){let t=new qe;return e.then(n=>t.resolve(n)).catch(n=>t.fail(n)),t}static resolve(e){let t=new qe;return t.resolve(e),t}static delay(e){let t=new qe;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new qe;return e(t),t}static wait(e){let t=new qe;return e.then(()=>t.resolve()),e.onFailed(n=>t.fail(n)),t}static race(e){let t=new qe;return e.length===0?(t.resolve(void 0),t):(e.forEach(n=>{n.then(i=>{e.forEach(r=>{r!==n&&r.skipController?.abort()}),t.resolve(i)}),n.onFailed(i=>t.fail(i))}),t.registerSkipController(new V(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let i=new qe().registerSkipController(n||new V(()=>t));e.then(()=>i.resolve(t)),e.onFailed(a=>i.fail(a));let r=e.skipController?.onAbort(()=>{i.skipController?.abort(),r?.cancel(),s?.cancel()}),s=i.skipController?.onAbort(()=>{e.skipController?.abort(),r?.cancel(),s?.cancel()});return i}static toPromise(e){return new Promise((t,n)=>{e.then(t),e.onFailed(n)})}static toPromiseForce(e){return new Promise(t=>{e.onSettled(t)})}static any(...e){let t=new qe;return e.length===0?(t.resolve(),t):(e.forEach(n=>{n.onSettled(()=>t.resolve()),n.onFailed(i=>{e.forEach(r=>{r!==n&&r.abort()}),t.fail(i)})}),t.registerSkipController(new V(()=>{e.forEach(n=>n.abort())})),t)}static all(...e){let t=new qe;if(e.length===0)return t.resolve(),t;let n=0;return e.forEach(i=>{i.onSettled(()=>{n++,n===e.length&&t.resolve()}),i.onFailed(r=>{e.forEach(s=>{s!==i&&s.abort()}),t.fail(r)})}),t.registerSkipController(new V(()=>{e.forEach(i=>i.abort())})),t}registerSkipController(e){this.skipControllerAbortToken?.cancel(),this.skipController=e,this.skipControllerAbortToken=e.onAbort(()=>{this.aborted=!0,this.notifySettled()});for(let t of this.onRegisterSkipController)t(e);return this}resolve(e){if(!this.isSettled()){this.result=this.receiver(e),this.solved=!0,this.skipController&&this.skipController.cancel();for(let t of this.listeners)t(this.result);this.notifySettled()}}fail(e){if(!this.isSettled()){this.error=e,this.failed=!0,this.skipController&&this.skipController.cancel();for(let t of this.failListeners)t(e);this.notifySettled()}}then(e,t){return this.solved?e(this.result):this.failed?t?.(this.error):(this.pushListener(e),t&&this.pushFailListener(t)),this}onSettled(e){if(this.isSettled())e();else return this.settledListeners.push(e),{cancel:()=>{this.offSettledListener(e)}};return{cancel:()=>{}}}onFailed(e){if(this.failed)e(this.error);else if(!this.isSettled())return this.pushFailListener(e),{cancel:()=>{this.offFailListener(e)}};return{cancel:()=>{}}}onSkipControllerRegister(e){return this.skipController?e(this.skipController):this.onRegisterSkipController.push(e),{cancel:()=>{this.offSkipControllerRegister(e)}}}offSkipControllerRegister(e){let t=this.onRegisterSkipController.indexOf(e);return t!==-1&&this.onRegisterSkipController.splice(t,1),this}abort(){return this.isSettled()?this.result:(this.aborted=!0,this.skipController?this.skipController.abort():this.notifySettled(),this.result)}isSolved(){return this.solved&&!this.aborted&&!this.failed}isAborted(){return this.aborted}isFailed(){return this.failed}isSettled(){return this.solved||this.aborted||this.failed}pushListener(e){return this.listeners.length>=qe.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many listeners, this may cause performance issues."),this.listeners.push(e),this}pushFailListener(e){return this.failListeners.length>=qe.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many failure listeners, this may cause performance issues."),this.failListeners.push(e),this}offListener(e){let t=this.listeners.indexOf(e);return t!==-1&&this.listeners.splice(t,1),this}offFailListener(e){let t=this.failListeners.indexOf(e);return t!==-1&&this.failListeners.splice(t,1),this}offSettledListener(e){let t=this.settledListeners.indexOf(e);return t!==-1&&this.settledListeners.splice(t,1),this}notifySettled(){if(!this.settledNotified){this.settledNotified=!0;for(let e of this.settledListeners)e()}}};qe.nothing=e=>e,qe.maxListeners=8;var S=qe;function $s(o){let e=new WeakSet;function t(n){if(n===null||typeof n!="object")return n;if(e.has(n))return;if(e.add(n),Array.isArray(n)){let r=[];for(let s of n)r.push(t(s));return r}let i={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[r]=t(n[r]));return i}return t(o)}function Rn(o){return typeof o=="string"?o:`#${(o.r||0).toString(16).padStart(2,"0")}${(o.g||0).toString(16).padStart(2,"0")}${(o.b||0).toString(16).padStart(2,"0")}${o.a===void 0?"":o.a.toString(16).padStart(2,"0")}`}var Y=class{constructor(){this.events={};this.maxListeners=10}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),this.events[e].length>this.maxListeners&&console.warn(`NarraLeaf-React: Event ${e} has more than ${this.maxListeners} listeners (total: ${this.events[e].length}), this may cause performance issues.`),this.emit("event:EventDispatcher.register",e,t),{type:e,listener:t,cancel:()=>{this.off(e,t)}}}depends(e){return{cancel:()=>{e.forEach(t=>t.cancel())}}}off(e,t){this.events[e]&&(this.events[e]=this.events[e].filter(n=>n!==t))}emit(e,...t){if(!this.events[e])return 0;let n=this.events[e].length;return this.events[e].forEach(i=>{i(...t)}),n}once(e,t){let n=(...i)=>{t(...i),this.off(e,n)};return this.on(e,n)}async any(e,...t){if(this.events[e]||(this.events[e]=[]),this.events[e].length>0){await Promise.all(this.events[e].map(n=>n(...t)));return}return new Promise(n=>{let i="event:EventDispatcher.register",r=this.on(i,(s,a)=>{if(s===e){this.off(i,r);let l=a?.(...t);l!==null&&typeof l=="object"&&l.then?l.then(n):n(l)}}).listener})}setMaxListeners(e){return this.maxListeners=e,this}hasListeners(e){return this.events[e]?.length>0}clear(){this.events={}}};function or(o=1){let e=new Error().stack;return e?e.split(`
|
|
2
2
|
`).slice(o+1).join(`
|
|
3
|
-
`).trim():""}function Hi(o){return new Promise(e=>setTimeout(e,o))}var Gi=class Gi{constructor(e){this.abortHandler=e;this.events=new X;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Gi.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Gi.EventTypes={"event:skipController.abort":"event:skipController.abort"};var F=Gi;var $n=class{constructor(){this.locked=!1;this.listeners=[];this.unlockListeners=[]}lock(){return this.locked=!0,this}unlock(){this.locked=!1;for(let e of this.listeners)e();for(let e of this.unlockListeners)e();return this.listeners=[],this}onUnlock(e){return this.unlockListeners.push(e),e}offUnlock(e){this.unlockListeners=this.unlockListeners.filter(t=>t!==e)}async nextUnlock(){if(this.locked)return new Promise(e=>{this.listeners.push(e)})}isLocked(){return this.locked}},wn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new $n;return this.locks.push(t),t}off(e){this.locks=this.locks.filter(t=>t!==e)}async nextUnlock(){let e=this.locks.map(t=>t.nextUnlock());return Promise.all(e)}isLocked(){return this.locks.some(e=>e.isLocked())}};function Oi(o,e,t={}){return o?e:t}function Vs(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var Li=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,i=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(i),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function Fs(o,e){let t=[];for(let n=0;n<Math.max(o.length,e.length);n++)n<o.length&&t.push(o[n]),n<e.length&&t.push(e[n]);return t}async function Us(o,e){return new Promise((t,n)=>{fetch(o,e).then(i=>i.blob()).then(i=>{let r=new FileReader;r.onload=()=>{t(r.result)},r.readAsDataURL(i)}).catch(n)})}var kn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}get size(){return this.tasks.length}async start(){let e=async()=>{if(this.tasks.length===0)return;let t=this.tasks.splice(0,this.concurrency);await Promise.all(t.map(n=>n())),this.tasks.length!==0&&(await Hi(this.delay),await e())};await e()}};function ot(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function Ws(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var Ye=class o{constructor(e={},t={}){this.serializer=e;this.deserializer=t}serialize(e){let t={};for(let n of Object.keys(e))n in this.serializer&&e[n]!==void 0?t[n]=this.serializer[n]?.(e[n]):t[n]=e[n];return t}deserialize(e){let t={};for(let n of Object.keys(e))typeof this.deserializer[n]=="function"&&e[n]!==void 0?t[n]=this.deserializer[n](e[n]):t[n]=e[n];return t}extend(e,t){let n={...this.serializer,...e},i={...this.deserializer,...t};return new o(n,i)}};function Bs(o){return["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].includes(o)}function Ks(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function jn(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function Jo(o,e=new WeakSet){if(o===null||typeof o!="object"||Array.isArray(o)||o instanceof Date||o instanceof RegExp||Object.getPrototypeOf(o)!==Object.prototype||e.has(o))return!1;e.add(o);for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let n=o[t];if(n!==null&&typeof n=="object"&&!Jo(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Ri=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Vi(o=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let i=0;i<o;i++)e+=t.charAt(Math.floor(Math.random()*n));return e}function zs(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Ii=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Mi=class{constructor(){this.hooks={}}hook(e,t){return this.hooks[e]=this.hooks[e]||[],this.hooks[e].push(t),{cancel:()=>this.unhook(e,t)}}unhook(e,t){this.hooks[e]=this.hooks[e]?.filter(n=>n!==t)||[]}trigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t));return()=>{i.forEach(r=>r&&r())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t()));return()=>{i.forEach(r=>r&&r())}}};var Ni=class{constructor(e){this.items=[];this.pushValidator=[];e&&(this.items=[...e])}addPushValidator(e){return this.pushValidator.push(e),this}removePushValidator(e){this.pushValidator=this.pushValidator.filter(t=>t!==e)}push(...e){for(let t of e)this.pushValidator.some(n=>!n(t))||this.items.push(t)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}isEmpty(){return this.items.length===0}size(){return this.items.length}clear(){this.items=[]}toArray(){return[...this.items]}forEach(e){this.items.forEach(e)}forEachReverse(e){for(let t=this.items.length-1;t>=0;t--)e(this.items[t])}map(e){return this.items.map(e)}get(e){return this.items[e]}};function $s(o,e){let t={},n=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&(e.includes(i)?n.push(i):t[i]=o[i]);return[t,n]}function js(o){let e=3421674724,t=2216829733;for(let n=0;n<o.length;n++){let i=o.charCodeAt(n);e^=i;let r=e>>>0,s=t>>>0,a=435,l=16777216,c=r*a>>>0,u=r*l+s*a>>>0,d=s*l+(u>>>0)>>>0;e=c,t=d}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var qn=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Xo(),this._id="",this._staticId=null}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}getId(){return this._id}setId(e){this._id=e}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}setContent(e){return this.contentNode.setContent(e),this}setContentNode(e){return this.contentNode=e,this}getFutureActions(e,t){let n=this.contentNode.getChild();return n&&n.action?[n.action]:[]}};qn.ActionTypes={action:"action"};var q=class extends qn{constructor(e,t,n){super(e,t,n),this.callee=e.getSelf(),this.contentNode.action=this}unknownTypeError(){throw new Error("Unknown action type: "+this.type)}resolveAwaitable(e,t){let n=t||new S(i=>i);return(async()=>await e(n.resolve.bind(n),n))(),n}is(e,t){return this instanceof e&&this.type===t}stringify(e,t,n){return this.stringifyWithName("Action")}stringifyWithName(e){return`${e}#${this._id}(${this.type})`}stringifyWithContent(e,t){return`${e}#${this._id}(${this.type}){${t}}`}};var Yt=class Yt extends q{static handleSceneInit(e,t,n,i){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,async r=>{await Yt.initBackgroundMusic(e,r),i.resolve(t),n.logger.debug("Scene Action","Scene init")}),i)}static async initBackgroundMusic(e,t){e.state.backgroundMusic&&await t.setBackgroundMusic(e.state.backgroundMusic,e.config.backgroundMusicFade)}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new ne("Scene not found when creating snapshot (scene: "+e.getId()+")");return{state:e.toData(),local:e.local.getNamespace(t.getStorable()).toData(),element:t.createElementSnapshot(n),background:e.background.toData()}}static restoreSceneSnapshot(e,t){let n=e.element.scene,i=t.findElementByScene(n);i&&t.removeElement(i);let r=t.fromElementSnapshot(e.element);t.addElement(r),n.local.getNamespace(t.getStorable()).load(e.local),e.state&&n.fromData(e.state),e.background&&n.background.fromData(e.background)}applyStageTransition(e,t,n,i){let r=new S().registerSkipController(new F(()=>(e.logger.info("Stage Transition","Skipped"),super.executeAction(e,i)))),s=()=>{r.isSettled()||r.resolve(super.executeAction(e,i))},a=e.stageTransition.apply(t,{from:this.callee,to:n},s),l=e.timelines.attachTimeline(r).attachChild(a);return a.onCancelled(s),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:l},()=>{r.isSettled()||r.abort(),a.abort()}),r}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}applyNvlVisibility(e,t,n,i){e.setNvlVisibility(t,n);let r=Math.max(0,n?.duration||0);if(r===0)return super.executeAction(e,i);let s=super.executeAction(e,i),a=new S(c=>c),l=null;return a.registerSkipController(new F(()=>(l&&(clearTimeout(l),l=null),s))),l=e.setTimeout(()=>{l=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===_.action)return super.executeAction(e,t);if(this.is(Yt,"scene:init")){let n=new S(s=>s),i=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{this.exit(e)},[]);let r={type:this.type,node:this.contentNode.getChild()};return Yt.handleSceneInit(this.callee,r,e,S.forward(n,r))}else if(this.type===_.exit){let n=Yt.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new S(s=>s);e.timelines.attachTimeline(r),Yt.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),Yt.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===_.jumpTo){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));let r=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let[l]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,l)},[r]);let s=i.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:s}),null}else if(this.type===_.setBackgroundMusic){let[n,i]=this.contentNode.getContent(),r=this.callee,s=e.getExposedStateForce(r),a=r.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{s.setBackgroundMusic(l,0)},[a]),s.setBackgroundMusic(n,i||0),super.executeAction(e,t)}else{if(this.type===_.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===_.transitionToScene){let[n,i]=this.contentNode.getContent();return this.applyStageTransition(e,n,i,t)}else if(this.type===_.nvlBlock){let[n,i]=this.contentNode.getContent(),r=e.createNvlSnapshot();return e.enterNvlMode(i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{e.restoreNvlSnapshot(s)},[r]),n.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]}else if(this.type===_.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=S.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===_.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=S.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===_.nvlEnd){let[n]=this.contentNode.getContent(),i=e.createNvlSnapshot();return e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{e.restoreNvlSnapshot(r)},[i]),e.exitNvlMode(n||null),{type:this.type,node:null}}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===_.jumpTo&&t.allowFutureScene!==!1){let i=this.contentNode.getContent()[0],r=e.getScene(i,!0);r.isSceneRootConstructed()||r.constructSceneRoot(e);let s=e.getScene(i,!0).getSceneRoot()?.contentNode;return s?.action?[s.action]:[]}if(this.type===_.nvlBlock){let[i]=this.contentNode.getContent(),r=super.getFutureActions(e,t);return[...i??[],...r]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new ne(`Scene with name ${e} not found
|
|
3
|
+
`).trim():""}function Ki(o){return new Promise(e=>setTimeout(e,o))}var zi=class zi{constructor(e){this.abortHandler=e;this.events=new Y;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(zi.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};zi.EventTypes={"event:skipController.abort":"event:skipController.abort"};var V=zi;var Qn=class{constructor(){this.locked=!1;this.listeners=[];this.unlockListeners=[]}lock(){return this.locked=!0,this}unlock(){this.locked=!1;for(let e of this.listeners)e();for(let e of this.unlockListeners)e();return this.listeners=[],this}onUnlock(e){return this.unlockListeners.push(e),e}offUnlock(e){this.unlockListeners=this.unlockListeners.filter(t=>t!==e)}async nextUnlock(){if(this.locked)return new Promise(e=>{this.listeners.push(e)})}isLocked(){return this.locked}},Dn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Qn;return this.locks.push(t),t}off(e){this.locks=this.locks.filter(t=>t!==e)}async nextUnlock(){let e=this.locks.map(t=>t.nextUnlock());return Promise.all(e)}isLocked(){return this.locks.some(e=>e.isLocked())}};function Jn(o,e,t={}){return o?e:t}function js(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var Oi=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,i=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(i),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function qs(o,e){let t=[];for(let n=0;n<Math.max(o.length,e.length);n++)n<o.length&&t.push(o[n]),n<e.length&&t.push(e[n]);return t}async function Ys(o,e){return new Promise((t,n)=>{fetch(o,e).then(i=>i.blob()).then(i=>{let r=new FileReader;r.onload=()=>{t(r.result)},r.readAsDataURL(i)}).catch(n)})}var Ln=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}get size(){return this.tasks.length}async start(){let e=async()=>{if(this.tasks.length===0)return;let t=this.tasks.splice(0,this.concurrency);await Promise.all(t.map(n=>n())),this.tasks.length!==0&&(await Ki(this.delay),await e())};await e()}};function st(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function Xs(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var Ye=class o{constructor(e={},t={}){this.serializer=e;this.deserializer=t}serialize(e){let t={};for(let n of Object.keys(e))n in this.serializer&&e[n]!==void 0?t[n]=this.serializer[n]?.(e[n]):t[n]=e[n];return t}deserialize(e){let t={};for(let n of Object.keys(e))typeof this.deserializer[n]=="function"&&e[n]!==void 0?t[n]=this.deserializer[n](e[n]):t[n]=e[n];return t}extend(e,t){let n={...this.serializer,...e},i={...this.deserializer,...t};return new o(n,i)}};function Qs(o){return["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","transparent","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].includes(o)}function Js(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function _n(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function rr(o,e=new WeakSet){if(o===null||typeof o!="object"||Array.isArray(o)||o instanceof Date||o instanceof RegExp||Object.getPrototypeOf(o)!==Object.prototype||e.has(o))return!1;e.add(o);for(let t in o)if(Object.prototype.hasOwnProperty.call(o,t)){let n=o[t];if(n!==null&&typeof n=="object"&&!rr(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Vi=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function $i(o=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let i=0;i<o;i++)e+=t.charAt(Math.floor(Math.random()*n));return e}function _s(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Ui=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Wi=class{constructor(){this.hooks={}}hook(e,t){return this.hooks[e]=this.hooks[e]||[],this.hooks[e].push(t),{cancel:()=>this.unhook(e,t)}}unhook(e,t){this.hooks[e]=this.hooks[e]?.filter(n=>n!==t)||[]}trigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t));return()=>{i.forEach(r=>r&&r())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let i=n.map(r=>r(...t()));return()=>{i.forEach(r=>r&&r())}}};var Bi=class{constructor(e){this.items=[];this.pushValidator=[];e&&(this.items=[...e])}addPushValidator(e){return this.pushValidator.push(e),this}removePushValidator(e){this.pushValidator=this.pushValidator.filter(t=>t!==e)}push(...e){for(let t of e)this.pushValidator.some(n=>!n(t))||this.items.push(t)}pop(){return this.items.pop()}peek(){return this.items[this.items.length-1]}isEmpty(){return this.items.length===0}size(){return this.items.length}clear(){this.items=[]}toArray(){return[...this.items]}forEach(e){this.items.forEach(e)}forEachReverse(e){for(let t=this.items.length-1;t>=0;t--)e(this.items[t])}map(e){return this.items.map(e)}get(e){return this.items[e]}};function Zs(o,e){let t={},n=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&(e.includes(i)?n.push(i):t[i]=o[i]);return[t,n]}function ea(o){let e=3421674724,t=2216829733;for(let n=0;n<o.length;n++){let i=o.charCodeAt(n);e^=i;let r=e>>>0,s=t>>>0,a=435,l=16777216,c=r*a>>>0,u=r*l+s*a>>>0,d=s*l+(u>>>0)>>>0;e=c,t=d}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Zn=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=or(),this._id="",this._staticId=null}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}getId(){return this._id}setId(e){this._id=e}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}setContent(e){return this.contentNode.setContent(e),this}setContentNode(e){return this.contentNode=e,this}getFutureActions(e,t){let n=this.contentNode.getChild();return n&&n.action?[n.action]:[]}};Zn.ActionTypes={action:"action"};var $=class extends Zn{constructor(e,t,n){super(e,t,n),this.callee=e.getSelf(),this.contentNode.action=this}unknownTypeError(){throw new Error("Unknown action type: "+this.type)}resolveAwaitable(e,t){let n=t||new S(i=>i);return(async()=>await e(n.resolve.bind(n),n))(),n}is(e,t){return this instanceof e&&this.type===t}stringify(e,t,n){return this.stringifyWithName("Action")}stringifyWithName(e){return`${e}#${this._id}(${this.type})`}stringifyWithContent(e,t){return`${e}#${this._id}(${this.type}){${t}}`}};var Qt=class Qt extends ${static handleSceneInit(e,t,n,i){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,async r=>{await Qt.initBackgroundMusic(e,r),i.resolve(t),n.logger.debug("Scene Action","Scene init")}),i)}static async initBackgroundMusic(e,t){e.state.backgroundMusic&&await t.setBackgroundMusic(e.state.backgroundMusic,e.config.backgroundMusicFade)}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new ie("Scene not found when creating snapshot (scene: "+e.getId()+")");return{state:e.toData(),local:e.local.getNamespace(t.getStorable()).toData(),element:t.createElementSnapshot(n),background:e.background.toData()}}static restoreSceneSnapshot(e,t){let n=e.element.scene,i=t.findElementByScene(n);i&&t.removeElement(i);let r=t.fromElementSnapshot(e.element);t.addElement(r),n.local.getNamespace(t.getStorable()).load(e.local),e.state&&n.fromData(e.state),e.background&&n.background.fromData(e.background)}applyStageTransition(e,t,n,i){let r=new S().registerSkipController(new V(()=>(e.logger.info("Stage Transition","Skipped"),super.executeAction(e,i)))),s=()=>{r.isSettled()||r.resolve(super.executeAction(e,i))},a=e.stageTransition.apply(t,{from:this.callee,to:n},s),l=e.timelines.attachTimeline(r).attachChild(a);return a.onCancelled(s),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:l},()=>{r.isSettled()||r.abort(),a.abort()}),r}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}applyNvlVisibility(e,t,n,i){e.setNvlVisibility(t,n);let r=Math.max(0,n?.duration||0);if(r===0)return super.executeAction(e,i);let s=super.executeAction(e,i),a=new S(c=>c),l=null;return a.registerSkipController(new V(()=>(l&&(clearTimeout(l),l=null),s))),l=e.setTimeout(()=>{l=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===_.action)return super.executeAction(e,t);if(this.is(Qt,"scene:init")){let n=new S(s=>s),i=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{this.exit(e)},[]);let r={type:this.type,node:this.contentNode.getChild()};return Qt.handleSceneInit(this.callee,r,e,S.forward(n,r))}else if(this.type===_.exit){let n=Qt.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new S(s=>s);e.timelines.attachTimeline(r),Qt.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),Qt.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===_.jumpTo){let n=this.contentNode.getContent()[0],i=e.getStory().getScene(n);if(!i)throw this._sceneNotFoundError(this.getSceneName(n));let r=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let[l]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,l)},[r]);let s=i.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:s}),null}else if(this.type===_.setBackgroundMusic){let[n,i]=this.contentNode.getContent(),r=this.callee,s=e.getExposedStateForce(r),a=r.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{s.setBackgroundMusic(l,0)},[a]),s.setBackgroundMusic(n,i||0),super.executeAction(e,t)}else{if(this.type===_.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===_.transitionToScene){let[n,i]=this.contentNode.getContent();return this.applyStageTransition(e,n,i,t)}else if(this.type===_.nvlBlock){let[n,i]=this.contentNode.getContent(),r=e.createNvlSnapshot();return e.enterNvlMode(i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{e.restoreNvlSnapshot(s)},[r]),n.length===0?{type:this.type,node:this.contentNode.getChild()}:[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]}else if(this.type===_.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=S.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===_.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=S.isAwaitable(r)?e.timelines.attachTimeline(r):void 0;return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:s},a=>{e.setNvlVisibility(a)},[i]),r}else if(this.type===_.nvlEnd){let[n]=this.contentNode.getContent(),i=e.createNvlSnapshot();return e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{e.restoreNvlSnapshot(r)},[i]),e.exitNvlMode(n||null),{type:this.type,node:null}}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===_.jumpTo&&t.allowFutureScene!==!1){let i=this.contentNode.getContent()[0],r=e.getScene(i,!0);r.isSceneRootConstructed()||r.constructSceneRoot(e);let s=e.getScene(i,!0).getSceneRoot()?.contentNode;return s?.action?[s.action]:[]}if(this.type===_.nvlBlock){let[i]=this.contentNode.getContent(),r=super.getFutureActions(e,t);return[...i??[],...r]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new ie(`Scene with name ${e} not found
|
|
4
4
|
Make sure you have registered the scene using story.register
|
|
5
5
|
Action: (id: ${this.getId()}) ${this.type}
|
|
6
|
-
At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===_.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${i.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};Yt.ActionTypes=_;var ae=Yt;var Zo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},w=class o extends Zo{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var Fi={center:"center",left:"left",right:"right"};import{animate as Ys}from"motion/react";var En=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(En||{}),qs={left:"33.33%",center:"50%",right:"66.66%"},pt=class pt{static isUnknown(e){return e===pt.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},l=t?{right:s}:{left:s};return this.wrap({...a,...l})}static calc(e,t,n){if(!e||pt.isUnknown(e))return"auto";let i=!(t===void 0||pt.isUnknown(t));if(typeof n=="number"&&n>0){let s=pt.toPercent(e,n);if(s!==null){let a=i?t/n*100:0;return`${Math.round((s+a)*1e6)/1e6}%`}}return i?`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`:`calc(${e} + 0px)`}static toPercent(e,t){if(typeof e=="number")return t>0?e/t*100:null;let n=/^(-?\d+(?:\.\d+)?)%$/.exec(e.trim());return n?parseFloat(n[1]):null}static toCoord2D(e){if(rt.isCommonPositionType(e))return dt.fromCommonPosition(e);if(dt.isCoord2DPosition(e))return e;if(hn.isAlignPosition(e))return dt.fromAlignPosition(e);if(typeof e=="object"&&e!==null&&["x","y","xalign","yalign","xoffset","yoffset"].some(t=>t in e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static orUnknown(e){return pt.isUnknown(e)||e===void 0?pt.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return dt.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:pt.isUnknown(t.x)?0:t.x,y:pt.isUnknown(t.y)?0:t.y,xoffset:pt.isUnknown(t.xoffset)?0:t.xoffset,yoffset:pt.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(En).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&e!==null&&("xalign"in e||"yalign"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof rt||e instanceof dt||e instanceof hn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return dt.fromCommonPosition(new rt(e));if(this.isRawAlignPosition(e))return dt.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new dt(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};pt.Unknown=Symbol("Unknown");var M=pt,Ui=class Ui{static isCommonPositionType(e){return e instanceof Ui}constructor(e){this.position=e}toCSS(){return{x:qs[this.position],y:"50%",xoffset:0,yoffset:0}}};Ui.Positions=En;var rt=Ui,dt=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:qs[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||M.isUnknown(n)?M.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:M.isUnknown(t.x)?e.x:t.x,y:M.isUnknown(t.y)?e.y:t.y,xoffset:M.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:M.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=M.orUnknown(e.x),this.y=M.orUnknown(e.y),this.xoffset=M.orUnknown(e.xoffset),this.yoffset=M.orUnknown(e.yoffset)):(this.x=M.orUnknown(e),this.y=M.orUnknown(t),this.xoffset=M.Unknown,this.yoffset=M.Unknown),this.check()}check(){let e=t=>/^-?\d+(\.\d+)?%$/.test(t);if(typeof this.x=="string"&&!e(this.x))throw new Error(`Invalid x position: ${this.x}`);if(typeof this.y=="string"&&!e(this.y))throw new Error(`Invalid y position: ${this.y}`)}toCSS(){return{x:this.x,y:this.y,xoffset:this.xoffset,yoffset:this.yoffset}}},hn=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=M.orUnknown(e.xalign),this.yalign=M.orUnknown(e.yalign),this.xoffset=M.orUnknown(e.xoffset),this.yoffset=M.orUnknown(e.yoffset)):(this.xalign=M.orUnknown(e),this.yalign=M.orUnknown(t),this.xoffset=M.Unknown,this.yoffset=M.Unknown),this.check()}check(){if(typeof this.xalign=="number"&&isNaN(this.xalign))throw new Error("Invalid xalign position: "+this.xalign);if(typeof this.yalign=="number"&&isNaN(this.yalign))throw new Error("Invalid yalign position: "+this.yalign)}toCSS(){return{x:M.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:M.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var K=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new _o(this.mergeWithDefaultConfig(e))}copy(){return new o(j({},this.defaultConfig),this.handlers)}keys(){return Object.keys(this.defaultConfig)}getDefaultConfig(){return this.defaultConfig}mergeWithDefaultConfig(e){return Object.fromEntries(Object.entries(this.defaultConfig).map(([t,n])=>[t,this.mergeValue(t,n,e[t])]))}mergeValue(e,t,n){return this.isPlainObject(n)?j({},n):Array.isArray(t)?Array.isArray(n)&&n.length>0?[...n]:[...t]:n!==void 0?this.applyHandler(e,n):t}isPlainObject(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}applyHandler(e,t){return typeof this.handlers[e]=="function"?this.handlers[e](t):t}},_o=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(j({},this.config))}join(e){let t=Ws(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var nc={[Fi.left]:"25.33%",[Fi.center]:"50%",[Fi.right]:"75.66%"},xt=class xt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new xt(xt.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?M.toCoord2D(M.tryParsePosition(e||t)):M.mergePosition(M.tryParsePosition(e),M.tryParsePosition(t))}static mergeState(e,t){if("position"in e&&"position"in t){let n=this.mergePosition(e.position,t.position);return{...Object.assign({},e,t),position:n}}return{...Object.assign({},e,t)}}get(){return this.state}freeze(){return this.frozen=!0,this}assign(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=xt.mergeState(this.state,t),this}lock(){if(this.locked)throw new Error("Transform state is already locked.");return this.locked=Symbol(),this.locked}isLocked(){return!!this.locked}canWrite(e){return this.locked===null||this.locked===e}unlock(e){return this.locked===e&&(this.locked=null),this}toFramesDefinition(e,t){return jn(Z.constructStyle(e,this.state,t))}toStyle(e,t){return jn(Z.constructStyle(e,this.state,t))}serialize(){return xt.TransformStateSerializer.serialize(this.state)}clone(){return new xt(xt.mergeState({},this.state))}overwrite(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=xt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}resetTo(e){return this.state=e,this.locked=null,this.frozen=!1,this}};xt.DefaultTransformState=new K({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new rt("center"),opacity:0,alt:"",maskImage:void 0,maskSize:void 0,maskPosition:void 0,maskRepeat:void 0,maskMode:void 0,clipPath:void 0,filter:void 0,backdropFilter:void 0,mixBlendMode:void 0}),xt.TransformStateSerializer=new Ye({position:e=>M.serializePosition(M.tryParsePosition(e))},{position:e=>M.toCoord2D(e)});var ee=xt,Le=class Le{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},Le.defaultConfig,t||{});else{let[n,i]=[e,t||Le.defaultOptions];this.sequences.push({props:n,options:i||Le.defaultOptions}),this.config=Object.assign({},Le.defaultConfig)}}static isPosition(e){return rt.isCommonPositionType(e)||dt.isCoord2DPosition(e)||hn.isAlignPosition(e)}static immediate(e){return new Le(e,{duration:0,ease:"linear"})}static left(e,t){return new Le({position:rt.Positions.Left},{duration:e,ease:t})}static right(e,t){return new Le({position:rt.Positions.Right},{duration:e,ease:t})}static center(e,t){return new Le({position:rt.Positions.Center},{duration:e,ease:t})}static create(e){return new Le([],e)}static positionToCSS(e,t,n,i){return e?M.isRawPosition(e)?M.D2PositionToCSS(M.rawPositionToCoord2D(e),n,t,i):M.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?M.toCoord2D(M.tryParsePosition(e||t)):M.mergePosition(M.tryParsePosition(e),M.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...j(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,l=function(p,f,h){return typeof p>"u"?typeof h<"u"?f(h):"":f(p)},c=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${c}, ${u})`,l(t.rotation,p=>`rotate(${p}deg)`,0),l(t.scaleX,p=>`scaleX(${p*a})`,1),l(t.scaleY,p=>`scaleY(${p*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{},a=e.game?.config,l=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...Le.positionToCSS(t.position,i,r,l),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?Pn(t.fontColor):void 0,transform:Le.propToCSSTransform(e,t),...Le.constructVisualEffectStyle(t),...s?s(t):{}}}static constructVisualEffectStyle(e){let t=e;return{maskImage:t.maskImage,WebkitMaskImage:t.maskImage,maskSize:t.maskSize,WebkitMaskSize:t.maskSize,maskPosition:t.maskPosition,WebkitMaskPosition:t.maskPosition,maskRepeat:t.maskRepeat,WebkitMaskRepeat:t.maskRepeat,maskMode:t.maskMode,WebkitMaskMode:t.maskMode,clipPath:t.clipPath,filter:t.filter,backdropFilter:t.backdropFilter,WebkitBackdropFilter:t.backdropFilter,mixBlendMode:t.mixBlendMode}}animate(e,{gameState:t,ref:n,overwrites:i,companionRefs:r}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:s,sequences:a,options:l}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(m=>!!m.ref.current).map(({ref:m,project:v})=>({el:m.current,project:v}))});if(a.length||t.logger.warn("Transform","No sequences to animate."),l.repeat!==void 0&&!Number.isFinite(l.repeat))throw new ne("A transform applied with `transform()` (or `show`, `hide`, `pos`, ...) has to end, but this one repeats forever.\nUse `element.loop(transform)` for a motion that runs until it is stopped - the line does not wait for it, and `element.stopLoop()` ends it.");let c=!1,u=e.lock(),d=Ys(a,l),p=()=>{e.overwrite(u,s.get()).unlock(u),d.complete(),c=!0},f=new S().registerSkipController(new F(p)),h=()=>{c||e.overwrite(u,s.get()).unlock(u),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),f.resolve()};return d.then(h,(m=>{t.logger.error("Failed to animate transform. "+(m?.toString?.()||""));try{h()}catch{f.resolve()}})),d.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:s,sequences:a,options:l},this),f}startLoop(e,{gameState:t,ref:n,overwrites:i,companionRefs:r},s){if(!n.current)throw new Error("No ref found when looping.");this.commit();let{sequences:a,options:l}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(d=>!!d.ref.current).map(({ref:d,project:p})=>({el:d.current,project:p}))});a.length||t.logger.warn("Transform","No sequences to loop.");let c=[n.current,jn(e.toFramesDefinition(t,i)),{duration:0}],u=Ys([c,...a],{...l,repeat:1/0,repeatType:s?.repeatType??l.repeatType??"loop",repeatDelay:s?.repeatDelay!==void 0?this.toSeconds(s.repeatDelay,void 0):l.repeatDelay});return u.play(),t.logger.debug("Transform","Loop started.",{sequences:a,options:l},this),{stop:()=>{u.stop()}}}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...Le.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i,companions:r}){let s=t.clone(),a=s.lock(),l=this.sequences.flatMap(({props:c,options:u})=>{let d=s.assign(a,c),p=d.toFramesDefinition(e,n),f=this.getOptions(u),h=[i,p,f];if(!r||!r.length)return[h];let m=d.get();return[h,...r.map(({el:v,project:A})=>[v,jn(A(m)),{...f,at:"<"}])]});return{finalState:s.unlock(a).freeze(),sequences:l,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t,repeatType:n}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0),repeatType:n}}copy(){return new Le(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}effect(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}lens(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}maskImage(e){return this.pushChange({key:"maskImage",props:e})}clipPath(e){return this.pushChange({key:"clipPath",props:e})}filter(e){return this.pushChange({key:"filter",props:e})}backdropFilter(e){return this.pushChange({key:"backdropFilter",props:e})}mixBlendMode(e){return this.pushChange({key:"mixBlendMode",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new ne("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new ne("Invalid number in at definition.");let l=a/1e3;return r==="+"?`+${l}`:`-${l}`}};Le.defaultConfig={sync:!0},Le.defaultOptions={duration:0,ease:"linear"},Le.CommonImagePositionMap=nc;var Z=Le;var Wi=class{constructor(){this.id="";this._staticId=null;this._dirty=!1}setId(e){this.id=e}getId(){return this.id}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}markDirty(){return this._dirty=!0,this}isDirty(){return this._dirty}reset(){this._dirty=!1}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var Qs=Symbol("_Chained"),Xs;Xs=Qs;var er=class er{constructor(e){this[Xs]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Qs]}static toActions(e){return e.flat(2).map(t=>er.isChained(t)?t.fromChained(t):t).flat(3)}push(...e){this.__actions.push(...e)}getActions(){return this.__actions}getSelf(){return this.__self}newChain(){return this.getSelf().chain()}},Be=er,Dn=class extends Wi{chain(e){let t=Be.isChained(this)?this:this.proxy(this,new Be(this));if(!e)return t;let n=Array.isArray(e)?e:[e];return t.push(...n),t}proxy(e,t){let n=new Proxy(e,{get:function(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=e.do([n]).getActions()[0];return this.chain(i)}};var ce=class extends Dn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Nt=class extends q{executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",l=s.action?s.action.map(c=>c.stringify(e,t,n)).join(";"):"null";return`(${a}) {${l}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};Nt.ActionTypes=Ms;var Yn=64;function Zs(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function tr(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function Bi(o,e=0,t=new Set){if(e>Yn)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>Bi(n,e+1,t)):Zs(o)?Object.values(o).every(n=>Bi(n,e+1,t)):!1}finally{t.delete(o)}}function _s(o,e){let t=[],n=[];return{data:nr(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function nr(o,e,t,n,i,r,s){if(t>Yn)throw new E(`A stored value nests deeper than ${Yn} levels and cannot be saved
|
|
7
|
-
at ${s}, ${
|
|
6
|
+
At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===_.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[i]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${i.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};Qt.ActionTypes=_;var ae=Qt;var sr=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},k=class o extends sr{static create(e){return new o().setContent(e)}static forEachParent(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getParent()}static forEachChild(e,t){let n=new Set,i=e;for(;i&&!n.has(i);)n.add(i),t(i),i=i.getChild()}constructor(e,t,n){super("ContentNode"),this.child=n||null,this.parent=t||null,this.action=e||null}setParent(e){if(e===this)throw new Error("Cannot set parent to itself");return this.parent&&this.parent.setChild(null),this.parent=e,this}setChild(e){if(e===this)throw new Error("Cannot set child to itself");return this.child&&(this.child.parent=null),this.child=e,e&&e.parent!==this&&(e.remove(),e.parent=this),this}getChild(){return this.child||null}getParent(){return this.parent||null}addChild(e){return this.setChild(e),this}removeChild(e){return e&&this.child===e?(this.child=null,e.setParent(null)):e||(this.child=null),this}remove(){return this.parent&&this.parent.removeChild(this),this.child&&this.child.setParent(null),this}hasChild(){return!!this.child}};var ji={center:"center",left:"left",right:"right"};import{animate as na}from"motion/react";var In=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(In||{}),ta={left:"33.33%",center:"50%",right:"66.66%"},ft=class ft{static isUnknown(e){return e===ft.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},l=t?{right:s}:{left:s};return this.wrap({...a,...l})}static calc(e,t,n){if(!e||ft.isUnknown(e))return"auto";let i=!(t===void 0||ft.isUnknown(t));if(typeof n=="number"&&n>0){let s=ft.toPercent(e,n);if(s!==null){let a=i?t/n*100:0;return`${Math.round((s+a)*1e6)/1e6}%`}}return i?`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`:`calc(${e} + 0px)`}static toPercent(e,t){if(typeof e=="number")return t>0?e/t*100:null;let n=/^(-?\d+(?:\.\d+)?)%$/.exec(e.trim());return n?parseFloat(n[1]):null}static toCoord2D(e){if(at.isCommonPositionType(e))return ht.fromCommonPosition(e);if(ht.isCoord2DPosition(e))return e;if(vn.isAlignPosition(e))return ht.fromAlignPosition(e);if(typeof e=="object"&&e!==null&&["x","y","xalign","yalign","xoffset","yoffset"].some(t=>t in e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static orUnknown(e){return ft.isUnknown(e)||e===void 0?ft.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return ht.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:ft.isUnknown(t.x)?0:t.x,y:ft.isUnknown(t.y)?0:t.y,xoffset:ft.isUnknown(t.xoffset)?0:t.xoffset,yoffset:ft.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(In).includes(e)}static isRawCoord2DPosition(e){return typeof e=="object"&&("x"in e||"y"in e||"xoffset"in e||"yoffset"in e)}static isRawAlignPosition(e){return typeof e=="object"&&e!==null&&("xalign"in e||"yalign"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof at||e instanceof ht||e instanceof vn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return ht.fromCommonPosition(new at(e));if(this.isRawAlignPosition(e))return ht.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new ht(e);throw new Error("Invalid position type")}static tryParsePosition(e){if(this.isPosition(e))return e;if(this.isRawPosition(e))return this.rawPositionToCoord2D(e);throw new Error("Invalid position type")}static wrap(e){return{left:"auto",top:"auto",right:"auto",bottom:"auto",...e}}};ft.Unknown=Symbol("Unknown");var H=ft,qi=class qi{static isCommonPositionType(e){return e instanceof qi}constructor(e){this.position=e}toCSS(){return{x:ta[this.position],y:"50%",xoffset:0,yoffset:0}}};qi.Positions=In;var at=qi,ht=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:ta[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||H.isUnknown(n)?H.Unknown:`${n*100}%`;return new o({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new o({x:H.isUnknown(t.x)?e.x:t.x,y:H.isUnknown(t.y)?e.y:t.y,xoffset:H.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:H.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=H.orUnknown(e.x),this.y=H.orUnknown(e.y),this.xoffset=H.orUnknown(e.xoffset),this.yoffset=H.orUnknown(e.yoffset)):(this.x=H.orUnknown(e),this.y=H.orUnknown(t),this.xoffset=H.Unknown,this.yoffset=H.Unknown),this.check()}check(){let e=t=>/^-?\d+(\.\d+)?%$/.test(t);if(typeof this.x=="string"&&!e(this.x))throw new Error(`Invalid x position: ${this.x}`);if(typeof this.y=="string"&&!e(this.y))throw new Error(`Invalid y position: ${this.y}`)}toCSS(){return{x:this.x,y:this.y,xoffset:this.xoffset,yoffset:this.yoffset}}},vn=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=H.orUnknown(e.xalign),this.yalign=H.orUnknown(e.yalign),this.xoffset=H.orUnknown(e.xoffset),this.yoffset=H.orUnknown(e.yoffset)):(this.xalign=H.orUnknown(e),this.yalign=H.orUnknown(t),this.xoffset=H.Unknown,this.yoffset=H.Unknown),this.check()}check(){if(typeof this.xalign=="number"&&isNaN(this.xalign))throw new Error("Invalid xalign position: "+this.xalign);if(typeof this.yalign=="number"&&isNaN(this.yalign))throw new Error("Invalid yalign position: "+this.yalign)}toCSS(){return{x:H.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:H.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var B=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new ar(this.mergeWithDefaultConfig(e))}copy(){return new o(K({},this.defaultConfig),this.handlers)}keys(){return Object.keys(this.defaultConfig)}getDefaultConfig(){return this.defaultConfig}mergeWithDefaultConfig(e){return Object.fromEntries(Object.entries(this.defaultConfig).map(([t,n])=>[t,this.mergeValue(t,n,e[t])]))}mergeValue(e,t,n){return this.isPlainObject(n)?K({},n):Array.isArray(t)?Array.isArray(n)&&n.length>0?[...n]:[...t]:n!==void 0?this.applyHandler(e,n):t}isPlainObject(e){return typeof e=="object"&&!Array.isArray(e)&&e!==null&&Object.getPrototypeOf(e)===Object.prototype}applyHandler(e,t){return typeof this.handlers[e]=="function"?this.handlers[e](t):t}},ar=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(K({},this.config))}join(e){let t=Xs(this.config,Object.keys(e));return new o(Object.assign(t,e instanceof o?e.get():e))}extract(e){let t={},n={};for(let i of e)t[i]=this.config[i];for(let i in this.config)e.includes(i)||(n[i]=this.config[i]);return[new o(t),new o(n)]}assign(e){return new o(Object.assign({},this.config,e))}};var gc={[ji.left]:"25.33%",[ji.center]:"50%",[ji.right]:"75.66%"},kt=class kt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new kt(kt.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?H.toCoord2D(H.tryParsePosition(e||t)):H.mergePosition(H.tryParsePosition(e),H.tryParsePosition(t))}static mergeState(e,t){if("position"in e&&"position"in t){let n=this.mergePosition(e.position,t.position);return{...Object.assign({},e,t),position:n}}return{...Object.assign({},e,t)}}get(){return this.state}freeze(){return this.frozen=!0,this}assign(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=kt.mergeState(this.state,t),this}lock(){if(this.locked)throw new Error("Transform state is already locked.");return this.locked=Symbol(),this.locked}isLocked(){return!!this.locked}canWrite(e){return this.locked===null||this.locked===e}unlock(e){return this.locked===e&&(this.locked=null),this}toFramesDefinition(e,t){return _n(J.constructStyle(e,this.state,t))}toStyle(e,t){return _n(J.constructStyle(e,this.state,t))}serialize(){return kt.TransformStateSerializer.serialize(this.state)}clone(){return new kt(kt.mergeState({},this.state))}overwrite(e,t){if(this.frozen)throw new Error("Trying to write a frozen transform state.");if(!this.canWrite(e))throw new Error("Trying to write a locked transform state.");return this.state=kt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}resetTo(e){return this.state=e,this.locked=null,this.frozen=!1,this}};kt.DefaultTransformState=new B({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new at("center"),opacity:0,alt:"",maskImage:void 0,maskSize:void 0,maskPosition:void 0,maskRepeat:void 0,maskMode:void 0,clipPath:void 0,filter:void 0,backdropFilter:void 0,mixBlendMode:void 0}),kt.TransformStateSerializer=new Ye({position:e=>H.serializePosition(H.tryParsePosition(e))},{position:e=>H.toCoord2D(e)});var ee=kt,Le=class Le{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},Le.defaultConfig,t||{});else{let[n,i]=[e,t||Le.defaultOptions];this.sequences.push({props:n,options:i||Le.defaultOptions}),this.config=Object.assign({},Le.defaultConfig)}}static isPosition(e){return at.isCommonPositionType(e)||ht.isCoord2DPosition(e)||vn.isAlignPosition(e)}static immediate(e){return new Le(e,{duration:0,ease:"linear"})}static left(e,t){return new Le({position:at.Positions.Left},{duration:e,ease:t})}static right(e,t){return new Le({position:at.Positions.Right},{duration:e,ease:t})}static center(e,t){return new Le({position:at.Positions.Center},{duration:e,ease:t})}static create(e){return new Le([],e)}static positionToCSS(e,t,n,i){return e?H.isRawPosition(e)?H.D2PositionToCSS(H.rawPositionToCoord2D(e),n,t,i):H.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?H.toCoord2D(H.tryParsePosition(e||t)):H.mergePosition(H.tryParsePosition(e),H.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...K(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,l=function(p,h,f){return typeof p>"u"?typeof f<"u"?h(f):"":h(p)},c=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${c}, ${u})`,l(t.rotation,p=>`rotate(${p}deg)`,0),l(t.scaleX,p=>`scaleX(${p*a})`,1),l(t.scaleY,p=>`scaleY(${p*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{},a=e.game?.config,l=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...Le.positionToCSS(t.position,i,r,l),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?Rn(t.fontColor):void 0,transform:Le.propToCSSTransform(e,t),...Le.constructVisualEffectStyle(t),...s?s(t):{}}}static constructVisualEffectStyle(e){let t=e;return{maskImage:t.maskImage,WebkitMaskImage:t.maskImage,maskSize:t.maskSize,WebkitMaskSize:t.maskSize,maskPosition:t.maskPosition,WebkitMaskPosition:t.maskPosition,maskRepeat:t.maskRepeat,WebkitMaskRepeat:t.maskRepeat,maskMode:t.maskMode,WebkitMaskMode:t.maskMode,clipPath:t.clipPath,filter:t.filter,backdropFilter:t.backdropFilter,WebkitBackdropFilter:t.backdropFilter,mixBlendMode:t.mixBlendMode}}animate(e,{gameState:t,ref:n,overwrites:i,companionRefs:r}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:s,sequences:a,options:l}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(m=>!!m.ref.current).map(({ref:m,project:v})=>({el:m.current,project:v}))});if(a.length||t.logger.warn("Transform","No sequences to animate."),l.repeat!==void 0&&!Number.isFinite(l.repeat))throw new ie("A transform applied with `transform()` (or `show`, `hide`, `pos`, ...) has to end, but this one repeats forever.\nUse `element.loop(transform)` for a motion that runs until it is stopped - the line does not wait for it, and `element.stopLoop()` ends it.");let c=!1,u=e.lock(),d=na(a,l),p=()=>{e.overwrite(u,s.get()).unlock(u),d.complete(),c=!0},h=new S().registerSkipController(new V(p)),f=()=>{c||e.overwrite(u,s.get()).unlock(u),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),h.resolve()};return d.then(f,(m=>{t.logger.error("Failed to animate transform. "+(m?.toString?.()||""));try{f()}catch{h.resolve()}})),d.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:s,sequences:a,options:l},this),h}startLoop(e,{gameState:t,ref:n,overwrites:i,companionRefs:r},s){if(!n.current)throw new Error("No ref found when looping.");this.commit();let{sequences:a,options:l}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(d=>!!d.ref.current).map(({ref:d,project:p})=>({el:d.current,project:p}))});a.length||t.logger.warn("Transform","No sequences to loop.");let c=[n.current,_n(e.toFramesDefinition(t,i)),{duration:0}],u=na([c,...a],{...l,repeat:1/0,repeatType:s?.repeatType??l.repeatType??"loop",repeatDelay:s?.repeatDelay!==void 0?this.toSeconds(s.repeatDelay,void 0):l.repeatDelay});return u.play(),t.logger.debug("Transform","Loop started.",{sequences:a,options:l},this),{stop:()=>{u.stop()}}}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...Le.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i,companions:r}){let s=t.clone(),a=s.lock(),l=this.sequences.flatMap(({props:c,options:u})=>{let d=s.assign(a,c),p=d.toFramesDefinition(e,n),h=this.getOptions(u),f=[i,p,h];if(!r||!r.length)return[f];let m=d.get();return[f,...r.map(({el:v,project:C})=>[v,_n(C(m)),{...h,at:"<"}])]});return{finalState:s.unlock(a).freeze(),sequences:l,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t,repeatType:n}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0),repeatType:n}}copy(){return new Le(this.sequences,this.config)}commit(e){if(!this.stagedChanges.length)return this;let t=this.constructCommit(this.stagedChanges,this.getSequenceOptions());return this.sequences.push({props:t.props,options:{...this.getSequenceOptions(),...e}}),this.stagedChanges=[],this}zoom(e){return this.pushChange({key:"zoom",props:e})}scaleX(e){return this.pushChange({key:"scaleX",props:e})}scaleY(e){return this.pushChange({key:"scaleY",props:e})}scale(e,t){return this.pushChange({key:"scaleX",props:e}).pushChange({key:"scaleY",props:t})}rotation(e){return this.pushChange({key:"rotation",props:e})}position(e){return this.pushChange({key:"position",props:e})}opacity(e){return this.pushChange({key:"opacity",props:e})}fontColor(e){return this.pushChange({key:"fontColor",props:e})}effect(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}lens(e){for(let t of Object.keys(e))this.pushChange({key:t,props:e[t]});return this}maskImage(e){return this.pushChange({key:"maskImage",props:e})}clipPath(e){return this.pushChange({key:"clipPath",props:e})}filter(e){return this.pushChange({key:"filter",props:e})}backdropFilter(e){return this.pushChange({key:"backdropFilter",props:e})}mixBlendMode(e){return this.pushChange({key:"mixBlendMode",props:e})}constructCommit(e,t){let n={props:{},options:t};for(let i of e)n.props[i.key]=i.props;return n}pushChange(e){return this.stagedChanges.push(e),this}toSeconds(e,t){return typeof e>"u"?t:e/1e3}atToSeconds(e){if(typeof e>"u")return e;if(typeof e=="number")return e/1e3;let n=/^([+-])(\d+)$/.exec(e);if(!n)throw new ie("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[i,r,s]=n,a=Number(s);if(isNaN(a))throw new ie("Invalid number in at definition.");let l=a/1e3;return r==="+"?`+${l}`:`-${l}`}};Le.defaultConfig={sync:!0},Le.defaultOptions={duration:0,ease:"linear"},Le.CommonImagePositionMap=gc;var J=Le;var Yi=class{constructor(){this.id="";this._staticId=null;this._dirty=!1}setId(e){this.id=e}getId(){return this.id}getStaticId(){return this._staticId}setStaticId(e){return this._staticId=e,this}resolveId(e){return this.setId(this._staticId||e),this}markDirty(){return this._dirty=!0,this}isDirty(){return this._dirty}reset(){this._dirty=!1}fromData(e){return this}construct(e){for(let t=0;t<e.length;t++){let n=e[t];t!==0&&e[t-1]?.contentNode.setChild(n.contentNode)}return e}};var ia=Symbol("_Chained"),oa;oa=ia;var lr=class lr{constructor(e){this[oa]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[ia]}static toActions(e){return e.flat(2).map(t=>lr.isChained(t)?t.fromChained(t):t).flat(3)}push(...e){this.__actions.push(...e)}getActions(){return this.__actions}getSelf(){return this.__self}newChain(){return this.getSelf().chain()}},We=lr,Mn=class extends Yi{chain(e){let t=We.isChained(this)?this:this.proxy(this,new We(this));if(!e)return t;let n=Array.isArray(e)?e:[e];return t.push(...n),t}proxy(e,t){let n=new Proxy(e,{get:function(i,r){if(r in t)return t[r];let s=i[r];return typeof s=="function"?s.bind(n):s},set:function(i,r,s){return i[r]=s,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),i=e.do([n]).getActions()[0];return this.chain(i)}};var ce=class extends Mn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Ht=class extends ${executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",l=s.action?s.action.map(c=>c.stringify(e,t,n)).join(";"):"null";return`(${a}) {${l}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};Ht.ActionTypes=Ws;var ei=64;function sa(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function cr(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function Xi(o,e=0,t=new Set){if(e>ei)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>Xi(n,e+1,t)):sa(o)?Object.values(o).every(n=>Xi(n,e+1,t)):!1}finally{t.delete(o)}}function aa(o,e){let t=[],n=[];return{data:ur(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function ur(o,e,t,n,i,r,s){if(t>ei)throw new E(`A stored value nests deeper than ${ei} levels and cannot be saved
|
|
7
|
+
at ${s}, ${cr(e)}
|
|
8
8
|
A saved game this deep is almost always a data-structure bug. Flatten the value,
|
|
9
9
|
or keep the deep part outside the store and save an id for it.`);if(o===void 0)return r.push([...e]),null;if(o===null)return null;if(o instanceof Date)return i.push([...e]),o.toISOString();if(typeof o=="number"||typeof o=="string"||typeof o=="boolean")return o;if(typeof o=="object"){if(n.has(o))throw new E(`A stored value refers back to itself and cannot be saved
|
|
10
|
-
at ${s}, ${
|
|
10
|
+
at ${s}, ${cr(e)}
|
|
11
11
|
A saved game is a tree. Cutting the back-edge would save a different object graph
|
|
12
12
|
than the one you built, so this is refused rather than guessed at \u2014 break the
|
|
13
|
-
reference, or store an id in place of the object.`);if(Array.isArray(o)||
|
|
14
|
-
at ${s}, ${
|
|
15
|
-
at namespace "${this.name}"`),this.content[e]=t,this.reportChange(e,n,t),this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}has(e){return this.content[e]!==void 0}keys(){return Object.keys(this.content)}values(){return Object.values(this.content)}entries(){return Object.entries(this.content)}reset(){let e=this.content;return this.content=
|
|
16
|
-
at namespace "${this.name}"`),e?.data)}attach(e){return this.owner=e,this}detach(e){return this.owner===e&&(this.owner=null),this}reportChange(e,t,n){!this.owner||
|
|
17
|
-
Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]?.detach(this),this.namespaces[e]=t,t.attach(this),this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return this.namespaces[e]?.detach(this),delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}onChange(e,t,n){let i=typeof e=="string"?e:null,r=typeof t=="string"?t:null,s=typeof e=="function"?e:typeof t=="function"?t:n;if(!s)throw new E("No listener provided when subscribing to storable changes");return this.events.on(nn.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(nn.EventTypes["event:storable.restore"],e)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}let t=this.restoreBatch=new Set;try{Object.entries(e).forEach(([n,i])=>{this.namespaces[n]||this.addNamespace(new Gt(n,{})),this.namespaces[n].deserialize(i)})}finally{this.restoreBatch=null}this.events.emit(nn.EventTypes["event:storable.restore"],{namespaces:Array.from(t)})}clear(){return this.values().forEach(e=>e.detach(this)),this.namespaces={},this}reportChange(e){this.events.emit(nn.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(nn.EventTypes["event:storable.restore"],{namespaces:[e]})}};nn.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var Qn=nn;var Qt=class Qt extends q{executeAction(e,t){if(this.type===de.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===de.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===de.applyLoop){let[n,i]=this.contentNode.getContent();return this.applyLoop(e,this.callee,n,i,t)}else if(this.type===de.stopLoop){let[n]=this.contentNode.getContent();return this.stopLoop(e,this.callee,n,t)}else if(this.type===de.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}else if(this.type===de.bringToFront)return this.bringToFront(e,this.callee,t);throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new S().registerSkipController(new F(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t),c=t.transformState.clone(),u=t._getLoop(),d=t._getLoopActionId();u&&(t._setLoop(null,{},null),t.markDirty());let p=l.applyTransform(n,a),f=e.timelines.attachTimeline(s).attachChild(p);return p.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:f},(h,m,v)=>{s.isSettled()||s.abort(),p.abort(),t.transformState.forceOverwrite(h.state),Qt.restoreLoop(e,t,m,v)},[c,u,d]),s}applyLoop(e,t,n,i,r){let s=t._getLoop(),a=t._getLoopActionId(),l=i??{};t._setLoop(n,l,this.getId()),t.markDirty(),e.getExposedState(t)?.applyLoop(n,l),e.actionHistory.push({action:this,stackModel:r.stackModel},(u,d)=>{Qt.restoreLoop(e,t,u,d)},[s,a]);let c=new S;return c.resolve(super.executeAction(e,r)),c}stopLoop(e,t,n,i){let r=t._getLoop(),s=t._getLoopActionId();t._setLoop(null,{},null),t.markDirty();let a=new S().registerSkipController(new F(()=>(e.logger.info("Displayable Loop","Skipped"),super.executeAction(e,i)))),l=()=>{a.isSettled()||a.resolve(super.executeAction(e,i))},c=e.getExposedState(t);if(!c||!r)return e.actionHistory.push({action:this,stackModel:i.stackModel},(p,f)=>{Qt.restoreLoop(e,t,p,f)},[r,s]),l(),a;let u=c.stopLoop(n,l),d=e.timelines.attachTimeline(a).attachChild(u);return u.onCancelled(l),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:d},(p,f)=>{a.isSettled()||a.abort(),u.abort(),Qt.restoreLoop(e,t,p,f)},[r,s]),a}static restoreLoop(e,t,n,i){if(!n&&!t._getLoop())return;t._setLoop(n?.transform??null,n?.options??{},i),t.markDirty();let r=e.getExposedState(t);r&&(n?r.applyLoop(n.transform,n.options):r.stopLoop(void 0,()=>{}))}applyTransition(e,t,n,i,r){let s=new S().registerSkipController(new F(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t).applyTransition(n,a),u=e.timelines.attachTimeline(s).attachChild(c);return c.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{s.isSettled()||s.abort(),c.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let c=e.findElementByDisplayable(this.callee,i);c&&e.disposeDisplayable(n,c.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new S().registerSkipController(new F(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,c=>{c.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let l=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:l},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}bringToFront(e,t,n){let i=e.findElementByDisplayable(t),r=i&&Qt.getLayerElements(i,t);if(!r)throw new E(`Displayable not found when bringing it to front. The element may not be on stage yet. (element: ${t.getId()})`);let s=r.indexOf(t);s!==r.length-1&&(r.splice(s,1),r.push(t),e.flush()),e.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let c=e.findElementByDisplayable(t),u=c&&Qt.getLayerElements(c,t);if(!u)return;let d=u.indexOf(t);d!==l&&(u.splice(d,1),u.splice(l,0,t),e.flush())},[s]);let a=new S;return a.resolve(super.executeAction(e,n)),a}static getLayerElements(e,t){for(let n of e.layers.values())if(n.includes(t))return n;return null}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};Qt.ActionTypes=de;var Te=Qt;var _e=class extends q{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Mt.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Mt.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Mt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=S.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,l=>{l&&this.callee.fromData(l)},[s]),a}else if(this.type===Mt.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Mt.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Mt.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Mt.seek){let[i]=this.contentNode.getContent(),r=e.audioManager.getPosition(this.callee),s=S.forward(e.audioManager.seek(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{e.audioManager.seek(this.callee,a)},[r]),s}else if(this.type===Mt.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};_e.ActionTypes=Mt;var et={bgm:"bgm",sound:"sound",voice:"voice"},Ki=8,on=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function Ln(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var Jn=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=l=>{t.set(l.id,{id:l.id,parentId:l.parentId??null,volume:Ln(l.volume)})};Object.values(et).forEach(l=>n({id:l}));let i=new Set;e.forEach(l=>{let c=l?.id;if(typeof c!="string"||c.trim().length===0)throw new on(`Audio bus id must be a non-empty string, got ${JSON.stringify(c)}.`);if(i.has(c))throw new on(`Audio bus "${c}" is declared more than once.`);i.add(c),n(l)}),o.assertResolvable(t);let r=[],s=new Map,a=l=>{let c=s.get(l);if(c)return c;let u=t.get(l),d=u.parentId===null?null:a(u.parentId),p={id:u.id,parentId:u.parentId,volume:u.volume,depth:d?d.depth+1:1};return s.set(l,p),r.push(p),p};return t.forEach(l=>a(l.id)),new o(r,s)}static isSeeded(e){return Object.values(et).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new on(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new on(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>Ki)throw new on(`Audio bus "${t.id}" nests deeper than ${Ki}: ${n.join(" -> ")}.`);r=s}})}getNodes(){return this.nodes}get(e){return this.index.get(e)??null}has(e){return this.index.has(e)}isUnder(e,t){let n=this.index.get(e),i=0;for(;n&&i<=Ki;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},rr=Jn.resolve();function oc(o){rr=o}function sr(){return rr}function zi(o,e){let t=rr;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var na={[et.bgm]:"bgmVolume",[et.sound]:"soundVolume",[et.voice]:"voiceVolume"};function ia(o){let e={};return Object.entries(na).forEach(([t,n])=>{e[t]={get:()=>Ln(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var Xn=class Xn{constructor(e,t={}){this.declarations=e;this.events=new X;this.overrides=new Map;this.aliasTokens=[];this.tree=null;this.events.setMaxListeners(64),this.aliases=t,Object.entries(t).forEach(([n,i])=>{this.aliasTokens.push(i.subscribe(r=>{this.announce(n,Ln(r))}))})}dispose(){this.aliasTokens.forEach(e=>e.cancel()),this.aliasTokens.length=0}announce(e,t){let n=t;try{n=this.getEffectiveVolume(e)}catch{}this.events.emit(Xn.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=Jn.resolve(this.declarations()??[]),oc(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=Ln(t),i=this.aliases[e];return i?(i.set(n),this):(this.overrides.set(e,n),this.announce(e,n),this)}setVolumes(e){return Object.entries(e).forEach(([t,n])=>this.setVolume(t,n)),this}getVolume(e){let t=this.aliases[e];return t?Ln(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return Ln(this.getDeclaredVolume(e)*this.getVolume(e))}list(){return this.getTree().getNodes().map(e=>({id:e.id,parentId:e.parentId,volume:this.getVolume(e.id),declaredVolume:e.volume,effectiveVolume:this.getEffectiveVolume(e.id)}))}getVolumes(){let e={};return this.list().forEach(t=>{e[t.id]=t.volume}),e}onVolumeChange(e){return this.events.on(Xn.EventTypes["event:audioBus.volumeChange"],e)}};Xn.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var Zn=Xn;var oa=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(oa||{}),xe=class xe extends ce{static toSound(e){return e==null?null:typeof e=="string"?new xe({src:e}):e}static isSound(e){return e instanceof xe}static voice(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=xe.DefaultUserConfig.create(t),[i]=n.extract(xe.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){return sr().isUnder(this.config.type,et.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(_e.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(_e.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(_e.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(_e.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(_e.ActionTypes.setRate,[e])}pause(e){return this.pushAction(_e.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(_e.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(_e.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state:xe.StateSerializer.serialize(this.state)}}fromData(e){return this.state=xe.StateSerializer.deserialize(e.state),this}copy(){return new xe(this.userConfig.get())}reset(){return super.reset(),this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return xe.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new _e(this.chain(),e,new w().setContent(t)))}};xe.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",xe.DefaultUserConfig=new K({src:xe.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),xe.DefaultConfig=new K({src:xe.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),xe.DefaultState=new K({volume:1,rate:1,paused:!1,muted:!1}),xe.StateSerializer=new Ye;var be=xe;var gn=class gn{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===gn.SrcTypes.image?t.add(s):r===gn.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof I?I.getSrcURL(e):e.type==="image"?I.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(ae,_.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(P.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof Ae){let n=t;if(t.is(Ae,ut.setSrc)){let i=t.contentNode.getContent()[0];if(P.isImageSrc(i))return{type:"image",src:P.srcToURL(i),activeType:"scene"}}else{if(t.type===ut.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===ut.setAppearance){let i=t.contentNode.getContent()[0];if(I.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(I.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:I.getSrcFromTags(i,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof be){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof I||P.isStaticImageData(e)){if(e instanceof I){if(!P.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(I.getSrcURL(e)))return this}else if(this.isSrcRegistered(P.srcToURL(e.src)))return this;this.src.push({type:"image",src:P.isStaticImageData(e)?P.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof be?t:new be({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof be?e.getSrc():e;return this.src.some(n=>n.type===gn.SrcTypes.audio?t===n.src.getSrc():n.type===gn.SrcTypes.image?t===I.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};gn.SrcTypes={image:"image",video:"video",audio:"audio"};var Re=gn;var Qe=class o extends ce{constructor(){super(...arguments);this.srcManager=new Re;this.loopTransform=null;this.loopOptions={};this.loopActionId=null}_getLoop(){return this.loopTransform?{transform:this.loopTransform,options:this.loopOptions}:null}_setLoop(t,n,i){return this.loopTransform=t,this.loopOptions=t?n:{},this.loopActionId=t?i:null,this}_getLoopActionId(){return this.loopActionId}_serializeLoop(){return this.loopActionId?{actionId:this.loopActionId,options:{...this.loopOptions}}:null}_deserializeLoop(t){return this.loopTransform=null,this.loopOptions=t?{...t.options}:{},this.loopActionId=t?t.actionId:null,this}_rebindLoop(t){if(!this.loopActionId||this.loopTransform)return this;let i=t.get(this.loopActionId)?.contentNode?.getContent(),r=Array.isArray(i)?i[0]:void 0;return r instanceof Z?(this.loopTransform=r,this):this._setLoop(null,{},null)}reset(){super.reset(),this._setLoop(null,{},null)}pos(t,n,i){return this.transform(new Z({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new Z({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new Z({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new Z({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new Z({scaleX:t,scaleY:n},{duration:i,ease:r}))}scaleXY(t,n,i,r){return this.scale(t,n,i,r)}rotate(t,n,i){return this.transform(new Z({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new Z({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new Z(t,n))}mask(t,n={}){let i=P.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:l,...c}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:l},c)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:l="easeInOut",...c}=t,u={duration:a,ease:l,...c},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Ke,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:l="easeInOut",...c}=t,u={duration:a,ease:l,...c},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Ke,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...l}=t,c={duration:s,ease:a,...l},u=o.wipeClipPath(n,100),d=o.wipeClipPath(n,0),p=o.createClipPathTransform([[i?d:u,{duration:0}],[i?u:d,c]]);return r?this.combineActions(new Ke,f=>f.transform(p).clearClip({duration:0})):this.transform(p)}filter(t,n){return this.effect({filter:t},n)}clearFilter(t){return this.effect({filter:"none"},t)}backdrop(t,n){return this.effect({backdropFilter:t},n)}blend(t,n){return this.effect({mixBlendMode:t},n)}transform(t){let n=this.chain(),i=new Te(n,de.applyTransform,new w().setContent([t.copy()]));return n.chain(i)}loop(t,n){let i=this.chain(),r=new Te(i,de.applyLoop,new w().setContent([t.copy(),n]));return i.chain(r)}stopLoop(t){let n=this.chain(),i=new Te(n,de.stopLoop,new w().setContent([t]));return n.chain(i)}bringToFront(){let t=this.chain(),n=new Te(t,de.bringToFront,new w().setContent([]));return t.chain(n)}registerEffectSrc(t){let n=t.maskImage;if(typeof n=="string")for(let i of o.extractCSSUrls(n))this.srcManager.registerRawSrc(i)}static toCSSUrl(t){return`url("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}")`}static extractCSSUrls(t){let n=[],i=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g,r;for(;r=i.exec(t);){let s=r[1]||r[2]||r[3];s&&n.push(s.trim())}return n}static createClipPathTransform(t){return new Z(t.map(([n,i])=>({props:{clipPath:n},options:i})))}static circleClipPath(t,n){return`circle(${t}% at ${n})`}static wipeClipPath(t,n){switch(t){case"right":return`inset(0 0 0 ${n}%)`;case"top":return`inset(0 0 ${n}% 0)`;case"bottom":return`inset(${n}% 0 0 0)`;case"left":default:return`inset(0 ${n}% 0 0)`}}show(t){let n=this.chain(),i=t instanceof Z?t.copy():new Z({opacity:1},t),r=new Te(n,de.applyTransform,new w().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof Z?t.copy():new Z({opacity:0},t),r=new Te(n,de.applyTransform,new w().setContent([i]));return n.chain(r)}};var ra=3;var hf={};var Rn=class extends Dn{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let l=a.getFutureActions(e,i).filter(c=>!r.has(c));s.push(...l)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var ze=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var st=class o{static isTextEvent(e){return e instanceof o}static expression(e,t,n={}){return new o({expression:{image:e,appearance:t},sound:n.sound})}static sound(e){return new o({sound:e})}constructor(e){this.config=e}};function sa(o,e){let{render:t,data:n,...i}=e,r=j(o,i);return"render"in e?r.render=e.render:"render"in o&&(r.render=o.render),"data"in e?r.data=e.data:"data"in o&&(r.data=o.data),r}var Ie=class Ie{static isWord(e){return e instanceof Ie}static color(e,t){return Ie.isWord(e)?e.copy().assign({color:t}):new Ie(e,{color:t})}static bold(e){return Ie.isWord(e)?e.copy().assign({bold:!0}):new Ie(e,{bold:!0})}static italic(e){return Ie.isWord(e)?e.copy().assign({italic:!0}):new Ie(e,{italic:!0})}static custom(e,t,n={}){let i={...n,render:t};return Ie.isWord(e)?e.copy().assign(i):new Ie(e,i)}static getText(e){return e.filter(t=>!t.isPause()&&!t.isTextEvent()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=sa(Ie.defaultConfig,t)}evaluate(e){if(ze.isPause(this.text))return[this];if(st.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>Ie.isWord(n)?n.inherit(this.config).evaluate(e):new Ie(n,this.config)).flat():Ie.isWord(t)?t.inherit(this.config).evaluate(e):[new Ie(t,this.config)]}return[this]}inherit(e){return this.config.color=this.config.color||e.color,this.config.italic=this.config.italic??e.italic,this.config.bold=this.config.bold??e.bold,this.config.cps=this.config.cps??e.cps,this}assign(e){return this.config=sa(this.config,e),this}copy(){return new Ie(this.text,this.config)}isPause(){return ze.isPause(this.text)}isTextEvent(){return st.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Ie.defaultConfig={},Ie.defaultColor="#000";var te=Ie;var rn=class extends q{executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};rn.ActionTypes=Ns;var we=class o extends ce{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new rn(t,rn.ActionTypes.action,new w().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new rn(this.chain(),rn.ActionTypes.action,new w().setContent(e))]}};var $i=class{constructor(e){this.config=e;this.watching=null;this.warnings=[]}observe(e){return this.watching=e,this}warn(e,t){return this.warnings.push([e,t]),this.watching?.logger.warn(t),t}getWarnings(){return[...this.warnings]}};var ke=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),ot(()=>{this.preventAttach()})}static proxy(e){let t=new S,n=new S,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new E("Cannot create an 'any' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new E("Cannot create an 'all' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let l=e[a];i.attachChild(l),l.then(c=>{r[a]=c,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new S,s=()=>{if(i){let a;i.onSkipControllerRegister(l=>{a=l.onAbort(()=>{r.abort()})}),i.then(l=>{a?.cancel(),n=l,i=e(l),i?ot(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new F(()=>(i&&i.abort(),t))),i=e(t),i?ot(()=>s()):ot(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}isFailed(){return this._status==="failed"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onFailed(e){this._onFailed.push(e)}onSettled(e){this.isSettled()?ot(e):(this.onResolved(e),this.onCancelled(e),this.onFailed(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new E(`Attaching to this timeline violates the timeline's state.
|
|
13
|
+
reference, or store an id in place of the object.`);if(Array.isArray(o)||sa(o)){n.add(o);try{if(Array.isArray(o))return o.map((l,c)=>ur(l,[...e,c],t+1,n,i,r,s));let a={};return Object.entries(o).forEach(([l,c])=>{a[l]=ur(c,[...e,l],t+1,n,i,r,s)}),a}finally{n.delete(o)}}}return console.warn(`Value of type "${yc(o)}" cannot be saved and was stored as null
|
|
14
|
+
at ${s}, ${cr(e)}`),null}function yc(o){return typeof o!="object"||o===null?typeof o:o.constructor?.name??"object"}function la(o,e,t){let n=ra(o,e,pr);return n=ra(n,t,()=>{}),n}function ra(o,e,t){if(!Array.isArray(e)||!e.length)return o;let n=o;for(let i of e){if(!Array.isArray(i))continue;if(!i.length){n=t(n);continue}let r=n;for(let a=0;a<i.length-1&&r!==null&&typeof r=="object";a++)r=r[i[a]];if(r===null||typeof r!="object")continue;let s=i[i.length-1];r[s]=t(r[s])}return n}function pr(o){return o instanceof Date?o:typeof o=="string"||typeof o=="number"?new Date(o):new Date(NaN)}function ca(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function dr(o,e,t=0){if(Object.is(o,e))return!0;if(t>ei)return!1;if(o instanceof Date||e instanceof Date)return o instanceof Date&&e instanceof Date&&o.getTime()===e.getTime();if(Array.isArray(o)||Array.isArray(e))return Array.isArray(o)&&Array.isArray(e)&&o.length===e.length&&o.every((n,i)=>dr(n,e[i],t+1));if(ca(o)&&ca(e)){let n=Object.keys(o);return n.length===Object.keys(e).length&&n.every(i=>Object.prototype.hasOwnProperty.call(e,i)&&dr(o[i],e[i],t+1))}return!1}var Ft=class o{constructor(e,t,n){this.owner=null;this.name=e,this.key=n||e,this.content=K({},t),this.defaultContent=t}static isSerializable(e){return Xi(e)}set(e,t){let n=this.content[e];return o.isSerializable(t)?(this.content[e]=t,this.reportChange(e,n,t),this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
|
|
15
|
+
at namespace "${this.name}"`),this.content[e]=t,this.reportChange(e,n,t),this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}has(e){return this.content[e]!==void 0}keys(){return Object.keys(this.content)}values(){return Object.values(this.content)}entries(){return Object.entries(this.content)}reset(){let e=this.content;return this.content=K({},this.defaultContent),new Set([...Object.keys(e),...Object.keys(this.content)]).forEach(n=>{this.reportChange(n,e[n],this.content[n])}),this}getContent(){return this.content}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content={},this.deserialize(e)}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n,t)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)}),this.owner?.reportRestore(this.key)}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e,t){let n=`namespace "${this.name}"`+(t===void 0?"":`, key "${t}"`),i={any:s=>{let a=aa(s,n),l={type:"any",data:a.data};return a.dates.length&&(l.dates=a.dates),a.undefineds.length&&(l.undefineds=a.undefineds),l},date:s=>({type:"date",data:s.toISOString()})},r=this.toTypeName(e);return i[r](e)}unwrap(e){let n={any:i=>la(i.data,i.dates,i.undefineds),date:i=>pr(i.data)}[e?.type];return n?n(e):(console.warn(`Unknown stored value type "${e?.type}", reading it as-is
|
|
16
|
+
at namespace "${this.name}"`),e?.data)}attach(e){return this.owner=e,this}detach(e){return this.owner===e&&(this.owner=null),this}reportChange(e,t,n){!this.owner||dr(t,n)||this.owner.reportChange({namespace:this.key,key:String(e),previous:t,next:n})}},sn=class sn{constructor(){this.events=new Y;this.namespaces={};this.restoreBatch=null;this.events.setMaxListeners(64)}static createNamespace(e,t,n){return new Ft(e,t,n)}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,e.attach(this),this}getNamespace(e){if(!this.namespaces[e])throw new E(`Namespace ${e} is not initialized, did you forget to register it?
|
|
17
|
+
Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]?.detach(this),this.namespaces[e]=t,t.attach(this),this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return this.namespaces[e]?.detach(this),delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}onChange(e,t,n){let i=typeof e=="string"?e:null,r=typeof t=="string"?t:null,s=typeof e=="function"?e:typeof t=="function"?t:n;if(!s)throw new E("No listener provided when subscribing to storable changes");return this.events.on(sn.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(sn.EventTypes["event:storable.restore"],e)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}let t=this.restoreBatch=new Set;try{Object.entries(e).forEach(([n,i])=>{this.namespaces[n]||this.addNamespace(new Ft(n,{})),this.namespaces[n].deserialize(i)})}finally{this.restoreBatch=null}this.events.emit(sn.EventTypes["event:storable.restore"],{namespaces:Array.from(t)})}clear(){return this.values().forEach(e=>e.detach(this)),this.namespaces={},this}reportChange(e){this.events.emit(sn.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(sn.EventTypes["event:storable.restore"],{namespaces:[e]})}};sn.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var ti=sn;var Jt=class Jt extends ${executeAction(e,t){if(this.type===pe.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===pe.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===pe.applyLoop){let[n,i]=this.contentNode.getContent();return this.applyLoop(e,this.callee,n,i,t)}else if(this.type===pe.stopLoop){let[n]=this.contentNode.getContent();return this.stopLoop(e,this.callee,n,t)}else if(this.type===pe.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}else if(this.type===pe.bringToFront)return this.bringToFront(e,this.callee,t);throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new S().registerSkipController(new V(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t),c=t.transformState.clone(),u=t._getLoop(),d=t._getLoopActionId();u&&(t._setLoop(null,{},null),t.markDirty());let p=l.applyTransform(n,a),h=e.timelines.attachTimeline(s).attachChild(p);return p.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:h},(f,m,v)=>{s.isSettled()||s.abort(),p.abort(),t.transformState.forceOverwrite(f.state),Jt.restoreLoop(e,t,m,v)},[c,u,d]),s}applyLoop(e,t,n,i,r){let s=t._getLoop(),a=t._getLoopActionId(),l=i??{};t._setLoop(n,l,this.getId()),t.markDirty(),e.getExposedState(t)?.applyLoop(n,l),e.actionHistory.push({action:this,stackModel:r.stackModel},(u,d)=>{Jt.restoreLoop(e,t,u,d)},[s,a]);let c=new S;return c.resolve(super.executeAction(e,r)),c}stopLoop(e,t,n,i){let r=t._getLoop(),s=t._getLoopActionId();t._setLoop(null,{},null),t.markDirty();let a=new S().registerSkipController(new V(()=>(e.logger.info("Displayable Loop","Skipped"),super.executeAction(e,i)))),l=()=>{a.isSettled()||a.resolve(super.executeAction(e,i))},c=e.getExposedState(t);if(!c||!r)return e.actionHistory.push({action:this,stackModel:i.stackModel},(p,h)=>{Jt.restoreLoop(e,t,p,h)},[r,s]),l(),a;let u=c.stopLoop(n,l),d=e.timelines.attachTimeline(a).attachChild(u);return u.onCancelled(l),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:d},(p,h)=>{a.isSettled()||a.abort(),u.abort(),Jt.restoreLoop(e,t,p,h)},[r,s]),a}static restoreLoop(e,t,n,i){if(!n&&!t._getLoop())return;t._setLoop(n?.transform??null,n?.options??{},i),t.markDirty();let r=e.getExposedState(t);r&&(n?r.applyLoop(n.transform,n.options):r.stopLoop(void 0,()=>{}))}applyTransition(e,t,n,i,r){let s=new S().registerSkipController(new V(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t).applyTransition(n,a),u=e.timelines.attachTimeline(s).attachChild(c);return c.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{s.isSettled()||s.abort(),c.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let c=e.findElementByDisplayable(this.callee,i);c&&e.disposeDisplayable(n,c.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new S().registerSkipController(new V(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,c=>{c.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let l=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:l},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}bringToFront(e,t,n){let i=e.findElementByDisplayable(t),r=i&&Jt.getLayerElements(i,t);if(!r)throw new E(`Displayable not found when bringing it to front. The element may not be on stage yet. (element: ${t.getId()})`);let s=r.indexOf(t);s!==r.length-1&&(r.splice(s,1),r.push(t),e.flush()),e.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let c=e.findElementByDisplayable(t),u=c&&Jt.getLayerElements(c,t);if(!u)return;let d=u.indexOf(t);d!==l&&(u.splice(d,1),u.splice(l,0,t),e.flush())},[s]);let a=new S;return a.resolve(super.executeAction(e,n)),a}static getLayerElements(e,t){for(let n of e.layers.values())if(n.includes(t))return n;return null}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};Jt.ActionTypes=pe;var ye=Jt;var et=class extends ${executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Gt.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.play(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Gt.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.stop(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Gt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=S.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,l=>{l&&this.callee.fromData(l)},[s]),a}else if(this.type===Gt.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.setRate(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Gt.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.pause(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Gt.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.resume(this.callee,i.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}else if(this.type===Gt.seek){let[i]=this.contentNode.getContent(),r=e.audioManager.getPosition(this.callee),s=S.forward(e.audioManager.seek(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{e.audioManager.seek(this.callee,a)},[r]),s}else if(this.type===Gt.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};et.ActionTypes=Gt;var tt={bgm:"bgm",sound:"sound",voice:"voice"},Qi=8,an=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function Nn(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var ii=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=l=>{t.set(l.id,{id:l.id,parentId:l.parentId??null,volume:Nn(l.volume)})};Object.values(tt).forEach(l=>n({id:l}));let i=new Set;e.forEach(l=>{let c=l?.id;if(typeof c!="string"||c.trim().length===0)throw new an(`Audio bus id must be a non-empty string, got ${JSON.stringify(c)}.`);if(i.has(c))throw new an(`Audio bus "${c}" is declared more than once.`);i.add(c),n(l)}),o.assertResolvable(t);let r=[],s=new Map,a=l=>{let c=s.get(l);if(c)return c;let u=t.get(l),d=u.parentId===null?null:a(u.parentId),p={id:u.id,parentId:u.parentId,volume:u.volume,depth:d?d.depth+1:1};return s.set(l,p),r.push(p),p};return t.forEach(l=>a(l.id)),new o(r,s)}static isSeeded(e){return Object.values(tt).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new an(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new an(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>Qi)throw new an(`Audio bus "${t.id}" nests deeper than ${Qi}: ${n.join(" -> ")}.`);r=s}})}getNodes(){return this.nodes}get(e){return this.index.get(e)??null}has(e){return this.index.has(e)}isUnder(e,t){let n=this.index.get(e),i=0;for(;n&&i<=Qi;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},mr=ii.resolve();function vc(o){mr=o}function fr(){return mr}function Ji(o,e){let t=mr;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var ua={[tt.bgm]:"bgmVolume",[tt.sound]:"soundVolume",[tt.voice]:"voiceVolume"};function pa(o){let e={};return Object.entries(ua).forEach(([t,n])=>{e[t]={get:()=>Nn(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var ni=class ni{constructor(e,t={}){this.declarations=e;this.events=new Y;this.overrides=new Map;this.aliasTokens=[];this.tree=null;this.events.setMaxListeners(64),this.aliases=t,Object.entries(t).forEach(([n,i])=>{this.aliasTokens.push(i.subscribe(r=>{this.announce(n,Nn(r))}))})}dispose(){this.aliasTokens.forEach(e=>e.cancel()),this.aliasTokens.length=0}announce(e,t){let n=t;try{n=this.getEffectiveVolume(e)}catch{}this.events.emit(ni.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=ii.resolve(this.declarations()??[]),vc(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=Nn(t),i=this.aliases[e];return i?(i.set(n),this):(this.overrides.set(e,n),this.announce(e,n),this)}setVolumes(e){return Object.entries(e).forEach(([t,n])=>this.setVolume(t,n)),this}getVolume(e){let t=this.aliases[e];return t?Nn(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return Nn(this.getDeclaredVolume(e)*this.getVolume(e))}list(){return this.getTree().getNodes().map(e=>({id:e.id,parentId:e.parentId,volume:this.getVolume(e.id),declaredVolume:e.volume,effectiveVolume:this.getEffectiveVolume(e.id)}))}getVolumes(){let e={};return this.list().forEach(t=>{e[t.id]=t.volume}),e}onVolumeChange(e){return this.events.on(ni.EventTypes["event:audioBus.volumeChange"],e)}};ni.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var oi=ni;var da=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(da||{}),xe=class xe extends ce{static toSound(e){return e==null?null:typeof e=="string"?new xe({src:e}):e}static isSound(e){return e instanceof xe}static voice(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new xe({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=xe.DefaultUserConfig.create(t),[i]=n.extract(xe.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){return fr().isUnder(this.config.type,tt.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(et.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(et.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(et.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(et.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(et.ActionTypes.setRate,[e])}pause(e){return this.pushAction(et.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(et.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(et.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state:xe.StateSerializer.serialize(this.state)}}fromData(e){return this.state=xe.StateSerializer.deserialize(e.state),this}copy(){return new xe(this.userConfig.get())}reset(){return super.reset(),this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return xe.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new et(this.chain(),e,new k().setContent(t)))}};xe.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",xe.DefaultUserConfig=new B({src:xe.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),xe.DefaultConfig=new B({src:xe.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),xe.DefaultState=new B({volume:1,rate:1,paused:!1,muted:!1}),xe.StateSerializer=new Ye;var ve=xe;var Sn=class Sn{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,i=new Set;return e.forEach(({type:r,src:s})=>{r===Sn.SrcTypes.image?t.add(s):r===Sn.SrcTypes.video?n.add(s):i.add(s)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(i)}}static getSrc(e){return typeof e=="string"?e:e instanceof G?G.getSrcURL(e):e.type==="image"?G.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(ae,_.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(P.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof Se){let n=t;if(t.is(Se,mt.setSrc)){let i=t.contentNode.getContent()[0];if(P.isImageSrc(i))return{type:"image",src:P.srcToURL(i),activeType:"scene"}}else{if(t.type===mt.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===mt.setAppearance){let i=t.contentNode.getContent()[0];if(G.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(G.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:G.getSrcFromTags(i,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof ve){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof G||P.isStaticImageData(e)){if(e instanceof G){if(!P.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(G.getSrcURL(e)))return this}else if(this.isSrcRegistered(P.srcToURL(e.src)))return this;this.src.push({type:"image",src:P.isStaticImageData(e)?P.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof ve?t:new ve({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof ve?e.getSrc():e;return this.src.some(n=>n.type===Sn.SrcTypes.audio?t===n.src.getSrc():n.type===Sn.SrcTypes.image?t===G.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};Sn.SrcTypes={image:"image",video:"video",audio:"audio"};var Re=Sn;var ze=class o extends ce{constructor(){super(...arguments);this.srcManager=new Re;this.loopTransform=null;this.loopOptions={};this.loopActionId=null}_getLoop(){return this.loopTransform?{transform:this.loopTransform,options:this.loopOptions}:null}_setLoop(t,n,i){return this.loopTransform=t,this.loopOptions=t?n:{},this.loopActionId=t?i:null,this}_getLoopActionId(){return this.loopActionId}_serializeLoop(){return this.loopActionId?{actionId:this.loopActionId,options:{...this.loopOptions}}:null}_deserializeLoop(t){return this.loopTransform=null,this.loopOptions=t?{...t.options}:{},this.loopActionId=t?t.actionId:null,this}_rebindLoop(t){if(!this.loopActionId||this.loopTransform)return this;let i=t.get(this.loopActionId)?.contentNode?.getContent(),r=Array.isArray(i)?i[0]:void 0;return r instanceof J?(this.loopTransform=r,this):this._setLoop(null,{},null)}reset(){super.reset(),this._setLoop(null,{},null)}pos(t,n,i){return this.transform(new J({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new J({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new J({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new J({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new J({scaleX:t,scaleY:n},{duration:i,ease:r}))}scaleXY(t,n,i,r){return this.scale(t,n,i,r)}rotate(t,n,i){return this.transform(new J({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new J({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new J(t,n))}mask(t,n={}){let i=P.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:l,...c}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:l},c)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:l="easeInOut",...c}=t,u={duration:a,ease:l,...c},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Be,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:l="easeInOut",...c}=t,u={duration:a,ease:l,...c},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new Be,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...l}=t,c={duration:s,ease:a,...l},u=o.wipeClipPath(n,100),d=o.wipeClipPath(n,0),p=o.createClipPathTransform([[i?d:u,{duration:0}],[i?u:d,c]]);return r?this.combineActions(new Be,h=>h.transform(p).clearClip({duration:0})):this.transform(p)}filter(t,n){return this.effect({filter:t},n)}clearFilter(t){return this.effect({filter:"none"},t)}backdrop(t,n){return this.effect({backdropFilter:t},n)}blend(t,n){return this.effect({mixBlendMode:t},n)}transform(t){let n=this.chain(),i=new ye(n,pe.applyTransform,new k().setContent([t.copy()]));return n.chain(i)}loop(t,n){let i=this.chain(),r=new ye(i,pe.applyLoop,new k().setContent([t.copy(),n]));return i.chain(r)}stopLoop(t){let n=this.chain(),i=new ye(n,pe.stopLoop,new k().setContent([t]));return n.chain(i)}bringToFront(){let t=this.chain(),n=new ye(t,pe.bringToFront,new k().setContent([]));return t.chain(n)}registerEffectSrc(t){let n=t.maskImage;if(typeof n=="string")for(let i of o.extractCSSUrls(n))this.srcManager.registerRawSrc(i)}static toCSSUrl(t){return`url("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}")`}static extractCSSUrls(t){let n=[],i=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g,r;for(;r=i.exec(t);){let s=r[1]||r[2]||r[3];s&&n.push(s.trim())}return n}static createClipPathTransform(t){return new J(t.map(([n,i])=>({props:{clipPath:n},options:i})))}static circleClipPath(t,n){return`circle(${t}% at ${n})`}static wipeClipPath(t,n){switch(t){case"right":return`inset(0 0 0 ${n}%)`;case"top":return`inset(0 0 ${n}% 0)`;case"bottom":return`inset(${n}% 0 0 0)`;case"left":default:return`inset(0 ${n}% 0 0)`}}show(t){let n=this.chain(),i=t instanceof J?t.copy():new J({opacity:1},t),r=new ye(n,pe.applyTransform,new k().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof J?t.copy():new J({opacity:0},t),r=new ye(n,pe.applyTransform,new k().setContent([i]));return n.chain(r)}};var ma=3;var Uf={};var Gn=class extends Mn{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let l=a.getFutureActions(e,i).filter(c=>!r.has(c));s.push(...l)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var Ke=class o{static from(e){return o.isPauseConstructor(e)?new o:e}static wait(e){return new o({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof o}static isPauseConstructor(e){return e===o}constructor(e={}){this.config=e}};var lt=class o{static isTextEvent(e){return e instanceof o}static expression(e,t,n={}){return new o({expression:{image:e,appearance:t},sound:n.sound})}static sound(e){return new o({sound:e})}constructor(e){this.config=e}};function fa(o,e){let{render:t,data:n,...i}=e,r=K(o,i);return"render"in e?r.render=e.render:"render"in o&&(r.render=o.render),"data"in e?r.data=e.data:"data"in o&&(r.data=o.data),r}var Ie=class Ie{static isWord(e){return e instanceof Ie}static color(e,t){return Ie.isWord(e)?e.copy().assign({color:t}):new Ie(e,{color:t})}static bold(e){return Ie.isWord(e)?e.copy().assign({bold:!0}):new Ie(e,{bold:!0})}static italic(e){return Ie.isWord(e)?e.copy().assign({italic:!0}):new Ie(e,{italic:!0})}static custom(e,t,n={}){let i={...n,render:t};return Ie.isWord(e)?e.copy().assign(i):new Ie(e,i)}static getText(e){return e.filter(t=>!t.isPause()&&!t.isTextEvent()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=fa(Ie.defaultConfig,t)}evaluate(e){if(Ke.isPause(this.text))return[this];if(lt.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>Ie.isWord(n)?n.inherit(this.config).evaluate(e):new Ie(n,this.config)).flat():Ie.isWord(t)?t.inherit(this.config).evaluate(e):[new Ie(t,this.config)]}return[this]}inherit(e){return this.config.color=this.config.color||e.color,this.config.italic=this.config.italic??e.italic,this.config.bold=this.config.bold??e.bold,this.config.cps=this.config.cps??e.cps,this}assign(e){return this.config=fa(this.config,e),this}copy(){return new Ie(this.text,this.config)}isPause(){return Ke.isPause(this.text)}isTextEvent(){return lt.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Ie.defaultConfig={},Ie.defaultColor="#000";var te=Ie;var ln=class extends ${executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};ln.ActionTypes=Bs;var we=class o extends ce{static getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}static execute(e){return new o(e)}constructor(e){super(),this.handler=e;let t=this.chain(),n=new ln(t,ln.ActionTypes.action,new k().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new ln(this.chain(),ln.ActionTypes.action,new k().setContent(e))]}};var _i=class{constructor(e){this.config=e;this.watching=null;this.warnings=[]}observe(e){return this.watching=e,this}warn(e,t){return this.warnings.push([e,t]),this.watching?.logger.warn(t),t}getWarnings(){return[...this.warnings]}};var ke=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),st(()=>{this.preventAttach()})}static proxy(e){let t=new S,n=new S,i=new o(n);return i.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[r,s]=i.catSettled();e(r,s)}),t.onSkipControllerRegister(r=>{r.onAbort(()=>{i.abort()})}),[t,i]}static any(e){if(e.length===0)throw new E("Cannot create an 'any' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=!1;for(let s of e)i.attachChild(s),s.then(a=>{r||(r=!0,t.resolve(a))});return t.onSkipControllerRegister(s=>{s.onAbort(()=>{i.abort()})}),[t,i]}static all(e){if(e.length===0)throw new E("Cannot create an 'all' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let l=e[a];i.attachChild(l),l.then(c=>{r[a]=c,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new S,s=()=>{if(i){let a;i.onSkipControllerRegister(l=>{a=l.onAbort(()=>{r.abort()})}),i.then(l=>{a?.cancel(),n=l,i=e(l),i?st(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new V(()=>(i&&i.abort(),t))),i=e(t),i?st(()=>s()):st(()=>r.resolve(n)),r}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}isFailed(){return this._status==="failed"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onFailed(e){this._onFailed.push(e)}onSettled(e){this.isSettled()?st(e):(this.onResolved(e),this.onCancelled(e),this.onFailed(e))}abort(){this.isSettled()||(this.awaitable.abort(),this.setStatus("cancelled",this.emitEvents.bind(this)),this.children.forEach(e=>e.abort()))}attachChild(e){if(!this._ableToAttach)throw new E(`Attaching to this timeline violates the timeline's state.
|
|
18
18
|
Timeline attaching is only allowed synchronously after the timeline is created.
|
|
19
|
-
Current _ableToAttach: `+this._ableToAttach);let t=S.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){let e=this.children.find(t=>t.isFailed());this.awaitable.failed||e?this.setStatus("failed",this.emitEvents.bind(this)):this.awaitable.solved&&this.children.every(t=>t.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){if(this.isResolved())this._onResolved.forEach(e=>e());else if(this.isCancelled())this._onCancelled.forEach(e=>e());else if(this.isFailed()){let e=this.children.find(t=>t.isFailed());this._onFailed.forEach(t=>t(this.awaitable.error??e?.awaitable.error))}this._onResolved=[],this._onCancelled=[],this._onFailed=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},
|
|
20
|
-
This should not happen, please report this issue to the developers`);return this._element.state}};var qi=class o extends _n{constructor(e){super(),this.fontSize=e.fontSize,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.fontSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{fontSize:`${e}px`}}))]}}copy(){return new o({fontSize:this.fontSize,duration:this.duration,easing:this.easing})}};var Pe=class Pe extends Qe{static get DefaultUserConfig(){return Pe._defaultUserConfig??(Pe._defaultUserConfig=new K({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:"",...ee.DefaultTransformState.getDefaultConfig()},{position:e=>M.tryParsePosition(e)}))}static get DefaultTextTransformState(){return Pe._defaultTextTransformState??(Pe._defaultTextTransformState=new K({fontColor:"#000000",...ee.DefaultTransformState.getDefaultConfig()}))}constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=Pe.DefaultUserConfig.create(n),r=Pe.DefaultTextConfig.create(i.get());this.userConfig=i,this.config=r.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(i)}setText(e){let t=this.chain(),n=new sn(t,sn.ActionTypes.setText,new w().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new Z({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Ke,i=>{if(t){let s=new qi({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new sn(i,sn.ActionTypes.setFontSize,new w().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:Pe.StateSerializer.serialize(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.state=Pe.StateSerializer.deserialize(e.state),this.transformState.resetTo(ee.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}_init(e){return new Te(this.chain(),de.init,new w().setContent([e||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}getInitialTransformState(e){let[t]=e.extract(Pe.DefaultTextTransformState.keys());return new ee(Pe.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Te(e,de.applyTransition,new w().setContent([t,n=>n._setElement(this)]))}getInitialState(){return Pe.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};Pe._defaultUserConfig=null,Pe.DefaultTextConfig=new K({alignX:"center",alignY:"center",className:"",layer:void 0}),Pe.DefaultTextState=new K({fontSize:16,display:!1,text:""}),Pe._defaultTextTransformState=null,Pe.StateSerializer=new Ye;var yn=Pe;var ei=class extends q{executeAction(e,t){if(this.type===Ze.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===Ze.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===Ze.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===Ze.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===Ze.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===Ze.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let l=new S().registerSkipController(new F(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{l.isSettled()||l.resolve(super.executeAction(e,t))});let c=e.timelines.attachTimeline(l);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:c},()=>{l.isSettled()||l.abort()}),l}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};ei.ActionTypes=Ze;var He=class He extends Qe{constructor(t){super();this.events=new X;this.instance=null;this.status="unmounted";let n=He.DefaultUserConfig.create(t),i=He.DefaultPuppetConfig.create(n.get());if(this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(n),!this.config.backend)throw new ne("Puppet must have a backend name");if(!this.config.src)throw new ne("Puppet must have a src")}static get DefaultUserConfig(){return He._defaultUserConfig??(He._defaultUserConfig=new K({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...ee.DefaultTransformState.getDefaultConfig()},{position:t=>M.tryParsePosition(t)}))}static normalizeState(t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{...n,motion:typeof n.motion=="string"?n.motion:null,expression:typeof n.expression=="string"?n.expression:null,skin:typeof n.skin=="string"?n.skin:null,params:He.copyParams(n.params),slots:He.copySlots(n.slots)}}static mergeState(t,n){return He.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(Ze.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(Ze.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(Ze.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(Ze.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(Ze.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(Ze.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:He.normalizeState(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(t){return this.state=He.normalizeState(t.state),this.transformState.resetTo(ee.deserialize(t.transformState).get()),this._deserializeLoop(t.loop),this}_init(t){return new Te(this.chain(),de.init,new w().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}_resolveSize(t){let n=this.config.size;return n?{width:n.width,height:n.height}:{width:t.width,height:t.height}}_getStatus(){return this.getStatus()}_setStatus(t){this.status!==t&&(this.status=t,this.events.emit("event:puppet.statusChange",t))}_onStatusChange(t){return this.onStatusChange(t)}_attachInstance(t){this.instance=t}_getInstance(){return this.instance}_patchState(t){let n=He.normalizeState(this.state);return this.state=He.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(He.normalizeState(this.state))}async _runCommand(t,n){let i=this.instance;return i?(await i.command(t,n),!0):!1}async _describe(){let t=this.instance;return!t||typeof t.describe!="function"?null:await t.describe()}createAction(t,n){return new ei(this.chain(),t,w.create(n))}getInitialTransformState(t){let[n]=t.extract(ee.DefaultTransformState.keys());return new ee(ee.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return He.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};He._defaultUserConfig=null,He.DefaultPuppetConfig=new K({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var kt=He;var ti=class ti extends q{executeAction(e,t){let n=this;if(n.is(ti,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let l=s.get(i);s.set(i,r(l))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{s.set(i,l)},[a]),super.executeAction(e,t)}else if(n.is(ti,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(l=>{s[l]=r.get(l),r.set(l,a[l])}),e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{Object.keys(l).forEach(c=>{r.set(c,l[c])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};ti.ActionTypes=zn;var Yi=ti;var at=class at{static isSentence(e){return e instanceof at}static toSentence(e){return at.isSentence(e)?e:new at(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return te.isWord(e)?e:new te(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[te.isWord(e)?e:new te(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(at.isSingleWord):at.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||te.isWord(e)||ze.isPause(e)||st.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=at.format(e),this.config=j(at.defaultConfig,{...t,voice:typeof t.voice=="string"?be.voice(t.voice):be.toSound(t.voice)}),this.state=Os(at.defaultState)}toData(){return null}fromData(e){return this.state=j(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...at.formatStaticWord(i))}return t}copy(){return new at([...this.text],this.config)}};at.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},at.defaultState={};var ge=at;var an=class an extends ce{constructor(e,t={}){super(),this.config=j(an.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(l=>typeof l=="string")&&[t,...n].length>0&&[t,...n].every(l=>ge.isSingleWord(l))){let l=e,c=ge.format([t,...n]),u=new ge(Fs(l,c),{character:this}),d=new tt(this.chain(),tt.ActionTypes.say,new w().setContent(u));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new ge(r,{...i,character:this}):(ge.isSentence(r)?r:new ge(r,{...i,character:this})).copy();s.setCharacter(this);let a=new tt(this.chain(),tt.ActionTypes.say,new w().setContent(s));return this.chain(a)}setName(e){let t=new tt(this.chain(),tt.ActionTypes.setName,new w().setContent([e]));return this.chain(t)}setAvatar(e){return this.config.avatar=e===null?null:e,this}addPortrait(e,t={}){return this.config.portraits.push({image:e,avatar:t.avatar}),this}setPortraits(e){return this.config.portraits=[...e],this}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&ge.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):ge.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:an.StateSerializer.serialize(this.state)}}fromData(e){return this.state=an.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};an.defaultCharacterColor="#000",an.defaultConfig={portraits:[]},an.StateSerializer=new Ye;var Qi=an,Xt=new Qi(null);var Y=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},cr=class o extends ce{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new o().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new Oe(`ELSE condition already set
|
|
21
|
-
You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:
|
|
22
|
-
You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let i={gameState:n};if(t.If.condition?.evaluate(i)?.value)return t.If.action||null;for(let s of t.ElseIf)if(s.condition?.evaluate(i)?.value)return s.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(
|
|
23
|
-
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
|
|
19
|
+
Current _ableToAttach: `+this._ableToAttach);let t=S.isAwaitable(e)?new o(e,this.guard):e;return this.children.push(t),this.guard&&t.setGuard(this.guard),t.onSettled(()=>{this.resolveStatus()}),this}setGuard(e){return this.guard=e,this}catSettled(){return this.children.reduce(([e,t],n)=>(n.isResolved()?e.push(n):n.isCancelled()&&t.push(n),[e,t]),[[],[]])}onTimelineRegistered(e){return this._onTimelineRegistered.push(e),this}resolveStatus(){let e=this.children.find(t=>t.isFailed());this.awaitable.failed||e?this.setStatus("failed",this.emitEvents.bind(this)):this.awaitable.solved&&this.children.every(t=>t.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){if(this.isResolved())this._onResolved.forEach(e=>e());else if(this.isCancelled())this._onCancelled.forEach(e=>e());else if(this.isFailed()){let e=this.children.find(t=>t.isFailed());this._onFailed.forEach(t=>t(this.awaitable.error??e?.awaitable.error))}this._onResolved=[],this._onCancelled=[],this._onFailed=[]}setStatus(e,t){if(this.isSettled()){this.guard&&this.guard.warn("unexpectedTimelineStatusChange",`Trying to resolve a settled timeline: ${this._status} -> ${e}`);return}e!==this._status&&t?(this._status=e,t()):this._status=e}preventAttach(){this._ableToAttach=!1,this._onTimelineRegistered.forEach(e=>e())}},Zi=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof ke?e:new ke(e);return this.timelines.push(t),this.guard&&t.setGuard(this.guard),t}abortAll(){for(let e of this.timelines)e.abort();this.cleanupSettled()}cleanupSettled(){this.timelines=this.timelines.filter(e=>!e.isSettled())}};var Pt=class Pt extends ${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:ve.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=Pt.trailingVoice.get(e);n&&n!==t&&e.audioManager.isPlaying(n)&&e.timelines.attachTimeline(e.audioManager.stop(n,0)),t?Pt.trailingVoice.set(e,t):Pt.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 ke(s),l=this.contentNode.getContent(),c=e.isNvlMode(),u=e.getLiveGame(),d=e.createPresentationSnapshot(),p=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,h=Pt.getVoice(e,l);if(h){Pt.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=Pt.endVoiceWithPreference(e,h);v&&e.timelines.attachTimeline(v),f?.cancel()}):null;if(c){let v=this.getId(),g=(e.getActiveNvlDialogForAction(v)||e.getLatestNvlDialogForAction(v))?.id||e.allocateNvlDialogId(v),y=l.evaluate(we.getCtx({gameState:e}));i=te.getText(y),u.events.emit(Ot.EventTypes["event:character.prompt"],{character:l.config.character,sentence:l,text:i});let T=!1,A=()=>{T||(T=!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:l,text:i});r=g;let b=e.consumeNvlTypingSuppression(),x=w&&!b?"typing":"awaitAdvance";e.activateNvlDialog(g,x,!w);let F=e.waitForNvlAdvance(g,()=>{e.settleNvlDialog(g),A()});n=()=>{F.cancel()}}else{let v=e.idManager.generateId(),C=e.createDialog(v,l,()=>{e.settleAdvDialog(v),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()})});e.beginAdvDialog(v,this.getId()),i=C.text,n=()=>{e.settleAdvDialog(v),C.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=Pt.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:l.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")}};Pt.ActionTypes=Yt,Pt.trailingVoice=new WeakMap;var nt=Pt;function gr(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function ya(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return ga(o);let i=hr(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=hr(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=hr(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function hr(o,e){if(o===!1||typeof o>"u")return{resolved:!1,source:null};if(typeof o=="function"){let t=o(e);return{resolved:typeof t<"u",source:t??null}}return{resolved:!0,source:o}}function ga(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}function va(o,e){let t=[],n=i=>{i&&typeof i!="function"&&P.isImageSrc(i)&&t.push(i)};n(e?.config.avatar),n(o.config.avatar);for(let i of o.config.portraits||[])n(gr(i).avatar);return t}var cn=class extends ${executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Fi.setText){let i=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.text=r},[i]),super.executeAction(e,t)}else if(this.type===Fi.setFontSize){let i=this.callee.state.fontSize;this.callee.state.fontSize=this.contentNode.getContent()[0];let r=e.getExposedStateForce(this.callee);return r.flush(),r.updateStyleSync(),e.actionHistory.push(n,s=>{this.callee.state.fontSize=s},[i]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};cn.ActionTypes=Fi;var gt=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(gt||{});import{animate as Sc}from"motion/react";var Vt=class{requestAnimations(e){let t=e.map(m=>m.start),n=[],i=0,r=!1,s=!1,a=!1,l=[],c=[],u=[],d=()=>{e.forEach((m,v)=>{t[v]=m.end}),i=e.length,l.forEach(m=>m(t)),c.forEach(m=>m())};return{onUpdate:m=>(l.push(m),{cancel:()=>{let v=l.indexOf(m);v!==-1&&l.splice(v,1)}}),onComplete:m=>(c.push(m),{cancel:()=>{let v=c.indexOf(m);v!==-1&&c.splice(v,1)}}),onCanceled:m=>(u.push(m),{cancel:()=>{let v=u.indexOf(m);v!==-1&&u.splice(v,1)}}),complete:()=>{if(!(i===e.length||s)){if(!r){a=!0;return}n.forEach(m=>m.complete())}},start:()=>{if(!(r||s||i===e.length)){if(r=!0,a){d();return}e.forEach((m,v)=>{n.push(this.requestMotion(m,{onComplete:()=>{t[v]=m.end,l.forEach(C=>C(t)),i++,i===e.length&&c.forEach(C=>C())},onUpdate:C=>{t[v]=C,l.forEach(g=>g(t))}}))})}},cancel:()=>{s=!0,n.forEach(m=>m.cancel()),u.forEach(m=>m())}}}toFinalStyle(e){return e.resolve.map(t=>typeof t=="function"?t(...e.animations.map(n=>n.end)):t.resolver(...e.animations.map(n=>n.end)))}asPrev(e){return{resolver:e,key:"current"}}asTarget(e){return{resolver:e,key:"target"}}requestMotion(e,t){return Sc(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Vt.AnimationType=gt;var ri=class extends Vt{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new E(`Trying to access text state, but element is not set
|
|
20
|
+
This should not happen, please report this issue to the developers`);return this._element.state}};var eo=class o extends ri{constructor(e){super(),this.fontSize=e.fontSize,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.fontSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{fontSize:`${e}px`}}))]}}copy(){return new o({fontSize:this.fontSize,duration:this.duration,easing:this.easing})}};var Pe=class Pe extends ze{static get DefaultUserConfig(){return Pe._defaultUserConfig??(Pe._defaultUserConfig=new B({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:"",...ee.DefaultTransformState.getDefaultConfig()},{position:e=>H.tryParsePosition(e)}))}static get DefaultTextTransformState(){return Pe._defaultTextTransformState??(Pe._defaultTextTransformState=new B({fontColor:"#000000",...ee.DefaultTransformState.getDefaultConfig()}))}constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=Pe.DefaultUserConfig.create(n),r=Pe.DefaultTextConfig.create(i.get());this.userConfig=i,this.config=r.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(i)}setText(e){let t=this.chain(),n=new cn(t,cn.ActionTypes.setText,new k().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new J({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Be,i=>{if(t){let s=new eo({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new cn(i,cn.ActionTypes.setFontSize,new k().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:Pe.StateSerializer.serialize(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.state=Pe.StateSerializer.deserialize(e.state),this.transformState.resetTo(ee.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}_init(e){return new ye(this.chain(),pe.init,new k().setContent([e||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}getInitialTransformState(e){let[t]=e.extract(Pe.DefaultTextTransformState.keys());return new ee(Pe.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new ye(e,pe.applyTransition,new k().setContent([t,n=>n._setElement(this)]))}getInitialState(){return Pe.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};Pe._defaultUserConfig=null,Pe.DefaultTextConfig=new B({alignX:"center",alignY:"center",className:"",layer:void 0}),Pe.DefaultTextState=new B({fontSize:16,display:!1,text:""}),Pe._defaultTextTransformState=null,Pe.StateSerializer=new Ye;var Tn=Pe;var si=class extends ${executeAction(e,t){if(this.type===Ze.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===Ze.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===Ze.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===Ze.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===Ze.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===Ze.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let l=new S().registerSkipController(new V(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{l.isSettled()||l.resolve(super.executeAction(e,t))});let c=e.timelines.attachTimeline(l);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:c},()=>{l.isSettled()||l.abort()}),l}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};si.ActionTypes=Ze;var Ge=class Ge extends ze{constructor(t){super();this.events=new Y;this.instance=null;this.status="unmounted";let n=Ge.DefaultUserConfig.create(t),i=Ge.DefaultPuppetConfig.create(n.get());if(this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(n),!this.config.backend)throw new ie("Puppet must have a backend name");if(!this.config.src)throw new ie("Puppet must have a src")}static get DefaultUserConfig(){return Ge._defaultUserConfig??(Ge._defaultUserConfig=new B({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...ee.DefaultTransformState.getDefaultConfig()},{position:t=>H.tryParsePosition(t)}))}static normalizeState(t){let n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{...n,motion:typeof n.motion=="string"?n.motion:null,expression:typeof n.expression=="string"?n.expression:null,skin:typeof n.skin=="string"?n.skin:null,params:Ge.copyParams(n.params),slots:Ge.copySlots(n.slots)}}static mergeState(t,n){return Ge.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(Ze.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(Ze.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(Ze.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(Ze.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(Ze.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(Ze.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:Ge.normalizeState(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(t){return this.state=Ge.normalizeState(t.state),this.transformState.resetTo(ee.deserialize(t.transformState).get()),this._deserializeLoop(t.loop),this}_init(t){return new ye(this.chain(),pe.init,new k().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get())}_resolveSize(t){let n=this.config.size;return n?{width:n.width,height:n.height}:{width:t.width,height:t.height}}_getStatus(){return this.getStatus()}_setStatus(t){this.status!==t&&(this.status=t,this.events.emit("event:puppet.statusChange",t))}_onStatusChange(t){return this.onStatusChange(t)}_attachInstance(t){this.instance=t}_getInstance(){return this.instance}_patchState(t){let n=Ge.normalizeState(this.state);return this.state=Ge.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(Ge.normalizeState(this.state))}async _runCommand(t,n){let i=this.instance;return i?(await i.command(t,n),!0):!1}async _describe(){let t=this.instance;return!t||typeof t.describe!="function"?null:await t.describe()}createAction(t,n){return new si(this.chain(),t,k.create(n))}getInitialTransformState(t){let[n]=t.extract(ee.DefaultTransformState.keys());return new ee(ee.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return Ge.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};Ge._defaultUserConfig=null,Ge.DefaultPuppetConfig=new B({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var Et=Ge;var ai=class ai extends ${executeAction(e,t){let n=this;if(n.is(ai,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let l=s.get(i);s.set(i,r(l))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{s.set(i,l)},[a]),super.executeAction(e,t)}else if(n.is(ai,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(l=>{s[l]=r.get(l),r.set(l,a[l])}),e.actionHistory.push({action:this,stackModel:t.stackModel},l=>{Object.keys(l).forEach(c=>{r.set(c,l[c])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};ai.ActionTypes=Xn;var to=ai;var ct=class ct{static isSentence(e){return e instanceof ct}static toSentence(e){return ct.isSentence(e)?e:new ct(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return te.isWord(e)?e:new te(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[te.isWord(e)?e:new te(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(ct.isSingleWord):ct.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||te.isWord(e)||Ke.isPause(e)||lt.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=ct.format(e),this.config=K(ct.defaultConfig,{...t,voice:typeof t.voice=="string"?ve.voice(t.voice):ve.toSound(t.voice)}),this.state=$s(ct.defaultState)}toData(){return null}fromData(e){return this.state=K(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...ct.formatStaticWord(i))}return t}copy(){return new ct([...this.text],this.config)}};ct.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},ct.defaultState={};var me=ct;var un=class un extends ce{constructor(e,t={}){super(),this.config=K(un.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(l=>typeof l=="string")&&[t,...n].length>0&&[t,...n].every(l=>me.isSingleWord(l))){let l=e,c=me.format([t,...n]),u=new me(qs(l,c),{character:this}),d=new nt(this.chain(),nt.ActionTypes.say,new k().setContent(u));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new me(r,{...i,character:this}):(me.isSentence(r)?r:new me(r,{...i,character:this})).copy();s.setCharacter(this);let a=new nt(this.chain(),nt.ActionTypes.say,new k().setContent(s));return this.chain(a)}setName(e){let t=new nt(this.chain(),nt.ActionTypes.setName,new k().setContent([e]));return this.chain(t)}setAvatar(e){return this.config.avatar=e===null?null:e,this}addPortrait(e,t={}){return this.config.portraits.push({image:e,avatar:t.avatar}),this}setPortraits(e){return this.config.portraits=[...e],this}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&me.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):me.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:un.StateSerializer.serialize(this.state)}}fromData(e){return this.state=un.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};un.defaultCharacterColor="#000",un.defaultConfig={portraits:[]},un.StateSerializer=new Ye;var no=un,_t=new no(null);var j=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},yr=class o extends ce{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new o().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new He(`ELSE condition already set
|
|
21
|
+
You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:j.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new He(`ELSE condition already set
|
|
22
|
+
You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let i={gameState:n};if(t.If.condition?.evaluate(i)?.value)return t.If.action||null;for(let s of t.ElseIf)if(s.condition?.evaluate(i)?.value)return s.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(Ht,[this,Ht.ActionTypes.action,new k().setContent(t.conditions)])]}construct(t,n,i){let r=this.narrativeToActions(t);for(let s=0;s<r.length;s++){let a=r[s].contentNode,l=r[s+1]?.contentNode;l&&a.setChild(l),s===r.length-1&&n&&a.setChild(n),s===0&&i&&i.setChild(a)}return r}_getFutureActions(){return We.toActions([this.conditions.If.action?.[0]||[],...this.conditions.ElseIf.flatMap(t=>t.action?.[0]||[]),this.conditions.Else.action?.[0]||[]])}createIfCondition(t,n){this.conditions.If.condition=j.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new Ht(i,Ht.ActionTypes.action,new k().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?_t.say(n).getActions():We.toActions([n]))}};var io=class io extends ce{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new Ft(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Xn.set,[e,t]))}assign(e){return this.chain(this.createAction(Xn.assign,[e]))}equals(e,t){return new j(n=>{let i=n.storable.getNamespace(this.namespace),r=j.isLambda(t)||j.isLambdaHandler(t)?j.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new j(n=>{let i=n.storable.getNamespace(this.namespace),r=j.isLambda(t)||j.isLambdaHandler(t)?j.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new j(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new j(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new j(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new te(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new te(i=>j.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new j(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=io.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new to(this.chain(),e,k.create(t))}};io.NamespacePrefix="persistent";var Hn=io,oo=class oo extends Hn{constructor(e){super(e,{}),this.namespace=this.prefix(e,oo.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new Ft(this.namespace,this.defaultContent))}};oo.LocalNamespacePrefix="local";var Fn=oo;var On=class extends ${executeAction(e,t){if(this.type===yn.action)return super.executeAction(e,t);if(this.type===yn.setZIndex){let[n]=this.contentNode.getContent(),i=this.callee.state.zIndex;return this.callee.state.zIndex=n,e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.zIndex=r},[i]),e.stage.update(),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("LayerAction")}};On.ActionTypes=yn;var it=class it extends ze{static get DefaultUserConfig(){return it._defaultUserConfig??(it._defaultUserConfig=new B({zIndex:0,...ee.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e,t={}){super();let n=it.DefaultUserConfig.create(t),i=it.DefaultConfig.create({...n.get(),name:e});this.userConfig=n,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState()}include(e){return(Array.isArray(e)?e:[e]).forEach(n=>{n.useLayer(this)}),this}setZIndex(e){return this.chain(new On(this.chain(),yn.setZIndex,new k().setContent([e])))}bringToFront(){throw new E(`A layer cannot be brought to front. Layers are ordered by z-index, not by the order they were added in \u2014 use Layer.setZIndex to raise one. (layer: ${this.config.name})`)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState().get()),this}toData(){return{state:it.StateSerializer.serialize(this.state),transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.state=it.StateSerializer.deserialize(e.state),this.transformState.resetTo(ee.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}copy(){return new it(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new On(this.chain(),yn.action,new k),new ye(this.chain(),pe.init,new k().setContent([e,null,!1]))]}getInitialState(){return it.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(ee.DefaultTransformState.keys());return new ee(ee.DefaultTransformState.create(e.get()).get())}};it._defaultUserConfig=null,it.DefaultConfig=new B({name:"(anonymous)",zIndex:0}),it.StateSerializer=new Ye,it.DefaultState=new B({zIndex:0});var Vn=it;var li=class extends ce{constructor(e){super(),this.scene=e}show(e){let t=new ae(this.scene.chain(),_.nvlShow,new k().setContent([e]));return this.chain(t)}hide(e){let t=new ae(this.scene.chain(),_.nvlHide,new k().setContent([e]));return this.chain(t)}end(){let e=new ae(this.scene.chain(),_.nvlEnd,new k().setContent([]));return this.chain(e)}};var Fe=class Fe extends Gn{constructor(t,n){super();this.srcManager=new Re;this.events=new Y;this.actions=[];this.voiceCache=new Map;this._futureActions_=[];this.labelMap=new Map;let i=Fe.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=Fe.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=Fe.DefaultUserConfig.create(n),a=Fe.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 Fe._defaultSceneConfig??(Fe._defaultSceneConfig=new B({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Vn("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Vn("[[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=>{ve.isSound(r)&&Fe.validateVoice(r)}),i(t))return t;throw new He(`Invalid voices config: ${t}`)}}))}static validateVoice(t){if(!Ji(t.config.type,[tt.voice,tt.sound]))throw new He(`Voice must be a voice, but got ${t.config.type}.
|
|
23
|
+
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 Fe}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new Ye({backgroundImage:n=>n.toData(),backgroundMusic:n=>n?.toData()||null},{backgroundImage:n=>t.state.backgroundImage.fromData(n),backgroundMusic:n=>t.state.backgroundMusic&&n?t.state.backgroundMusic.fromData(n):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(Be.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new Be({allowFutureScene:!1}),i=>{let s=K({},n instanceof Vt?{transition:n}:n);return i.chain(new ae(i,"scene:preUnmount",new k().setContent([]))).chain(this._initScene(t))._transitionToScene(s.transition,t).chain(this._exit()),i})._jumpTo(t)}setBackgroundMusic(t,n){return this.chain(new ae(this.chain(),_.setBackgroundMusic,new k().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new li(this),a=typeof r=="function"?r(s):r,l=this.narrativeToActions(a),c={showTransition:i,hideTransition:i},u=new ae(this.chain(),_.nvlEnd,new k().setContent([c])),d=[...l,u];super.constructNodes(d);let p=new ae(this.chain(),_.nvlBlock,new k().setContent([d,c]));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:Fe.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=Fe.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new ae(this.chain(),"scene:action",new k);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(m=>We.isChained(m)?m.fromChained(m):m).flat(2),s=[],a=[],l=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(m=>{We.isChained(m)||(m instanceof G?s.push(m):m instanceof Tn?a.push(m):m instanceof Et&&l.push(m))});let c=[],u=[],d=new Map;s.forEach(m=>{m.config.isWearable?u.push(m):m.config.autoInit&&c.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
|
|
24
24
|
Maybe you bind the same wearable image to multiple parent images
|
|
25
25
|
Parent Conflict (src: `+d.get(v)?.state.currentSrc+`)
|
|
26
|
-
Current Parent (src: `+m.state.currentSrc+")");d.set(v,m)}});let p=[...this._initScene(this),...c.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()),...l.map(m=>m._init()),...r],
|
|
27
|
-
To prevent unintended behavior and unexpected results, the sound have to be on the music bus (or any bus beneath it). Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new I({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new ae(this.chain(),"scene:jumpTo",new w().setContent([t])))}_exit(){return new ae(this.chain(),"scene:exit",new w().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new ae(i,_.transitionToScene,new w().setContent([t,n]))):i}_init(t){return new ae(this.chain(),"scene:init",new w().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};Ve.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},Ve.DefaultUserConfig=new K({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),Ve._defaultSceneConfig=null;var ft=Ve;import*as ba from"howler";var Zi=class{constructor(e,t){this.game=e,this.prefix=t}log(e,...t){this.isEnabled("log")&&console.log(...this.colorLog("gray",e,...t))}info(e,...t){this.isEnabled("info")&&console.info(...this._log(e,...t))}warn(e,...t){this.isEnabled("warn")&&console.warn(...this._log(e,...t))}error(e,...t){this.isEnabled("error")&&console.error(...this._log(e,...t))}debug(e,...t){this.isEnabled("debug")&&console.debug(...this.colorLog("gray",e,...t))}trace(e,...t){this.isEnabled("trace")&&console.trace(this._log(e,...t))}weakWarn(e,...t){this.isEnabled("warn")&&console.log(...this.colorLog("yellow",e,...t))}weakError(e,...t){this.isEnabled("error")&&console.log(...this.colorLog("red",e,...t))}verbose(e,...t){this.isEnabled("verbose")&&console.log(...this.colorLog("gray",e,...t))}group(e,t=!1){let n=this._log(e).join(" ");return this.isEnabled("info")&&(t?console.groupCollapsed(n):console.group(n)),{end:()=>{this.isEnabled("info")&&console.groupEnd()}}}isEnabled(e){return typeof this.game.config.app.logger=="boolean"?this.game.config.app.logger:this.game.config.app.logger[e]}_log(e,...t){return t.length===0?[this.prefix||"",e]:[`${this.prefix||""} [${e}]`,...t]}colorLog(e,t,...n){if(n.length===0)return[`%c${this.prefix||""} ${t}`,`color: ${e}`];let i=[],r=[],s=[];return this.prefix?(i.push(`%c${this.prefix} [${t}]`),r.push(`color: ${e}`)):(i.push(`%c[${t}]`),r.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(i.push(`%c${a}`),r.push(`color: ${e}`)):(i.push("%O"),s.push(a),r.push(""))}),[i.join(" ")].concat(r,s)}};var sc={volume:1,limit:1/0},ac=class da{constructor(e,t,n,i){this.subChannels=new Map,this.tokens=new Set,this.tokenQueue=[],this.muted=!1,this.removed=!1,this.name=e,this.audioProvider=t,this.parentChannel=i??null,this.options={...sc,...n},this.volume=this.options.volume;let r=this.audioProvider.getAudioContext();this.gainNode=r.createGain(),this.gainNode.gain.value=this.muted?0:this.volume,this.connectToParent()}connectToParent(){this.parentChannel?this.gainNode.connect(this.parentChannel.getGainNode()):this.gainNode.connect(this.audioProvider.getAudioContext().destination)}getGainNode(){return this.gainNode}ensureNotRemoved(){if(this.removed)throw new Error(`Channel "${this.name}" has been removed and cannot be used.`)}getName(){return this.name}async play(e,t){if(this.ensureNotRemoved(),this.tokens.size>=this.options.limit){let r=this.tokenQueue.shift();r&&r.stop()}let n=await this.audioProvider.createToken(e,t,this.gainNode);this.tokens.add(n),this.tokenQueue.push(n);let i=()=>{this.tokens.delete(n);let r=this.tokenQueue.indexOf(n);r!==-1&&this.tokenQueue.splice(r,1)};return n.once("ended",i),n.once("stop",i),n}createChannel(e,t){if(this.ensureNotRemoved(),this.subChannels.has(e))throw new Error(`Channel "${e}" already exists under "${this.name}".`);this.audioProvider.checkChannelLimit();let n=new da(e,this.audioProvider,t,this);return this.subChannels.set(e,n),this.audioProvider.registerChannel(n),n}getChannel(e){return this.ensureNotRemoved(),this.subChannels.get(e)??null}getChannels(){return this.ensureNotRemoved(),Array.from(this.subChannels.values())}setVolume(e){return this.ensureNotRemoved(),this.volume=Math.max(0,Math.min(1,e)),this.muted||(this.gainNode.gain.value=this.volume),this}getVolume(){return this.volume}mute(e){return this.ensureNotRemoved(),this.muted=e!==void 0?e:!0,this.gainNode.gain.value=this.muted?0:this.volume,this}unmute(){return this.mute(!1)}isMuted(){return this.muted}remove(){if(this.removed)return this;this.removed=!0;for(let t of this.tokens)t.stop();this.tokens.clear();let e=Array.from(this.subChannels.values());this.subChannels.clear();for(let t of e)t.remove();try{this.gainNode.disconnect()}catch(t){console.warn("Failed to disconnect Channel gain node during remove().",t)}return this.audioProvider.unregisterChannel(this),this.parentChannel&&this.parentChannel.removeSubChannel(this.name),this}removeSubChannel(e){this.subChannels.delete(e)}getTokens(){this.ensureNotRemoved();let e=[...this.tokenQueue];for(let t of this.subChannels.values())e.push(...t.getTokens());return e}isRemoved(){return this.removed}getParent(){return this.parentChannel}getOptions(){return{...this.options}}},ma=!1;function lc(o){ma=o}function ln(o,e){ma||(e!==void 0?console.warn(o,e):console.warn(o))}var cc=class{constructor(o,e){this.currentSource=null,this.mediaElementSource=null,this.endedHandler=null,this.eventListeners=new Map,this.audioContext=o,this.gainNode=e}setSource(o){this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.setupEventListeners()}getSource(){return this.currentSource}refreshSource(o){let e=new Map(this.eventListeners);this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.eventListeners=e,this.setupEventListeners()}disconnectSource(){if(this.currentSource){if(this.removeAllEventListeners(),this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.disconnect()}catch(o){ln("Failed to disconnect AudioBufferSourceNode in disconnectSource().",o)}else this.currentSource instanceof HTMLAudioElement&&(this.currentSource.pause(),this.currentSource.src="",this.currentSource.load());if(this.mediaElementSource){try{this.mediaElementSource.disconnect()}catch(o){ln("Failed to disconnect MediaElementAudioSourceNode in disconnectSource().",o)}this.mediaElementSource=null}this.currentSource=null}}setupEventListeners(){this.currentSource&&(this.endedHandler=o=>{this.emit("ended")},this.currentSource instanceof HTMLAudioElement?this.currentSource.addEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.addEventListener("ended",this.endedHandler))}removeAllEventListeners(){!this.currentSource||!this.endedHandler||(this.currentSource instanceof HTMLAudioElement?this.currentSource.removeEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.removeEventListener("ended",this.endedHandler),this.endedHandler=null)}emit(o){let e=this.eventListeners.get(o);e&&[...e].forEach((t,n)=>{try{t.callback()}catch(i){console.error(`Error in event listener for '${o}':`,i)}t.once&&e.splice(e.indexOf(t),1)})}on(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!1})}off(o,e){let t=this.eventListeners.get(o);if(!t)return;let n=t.findIndex(i=>i.callback===e);n!==-1&&t.splice(n,1)}once(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!0})}stop(){if(this.currentSource){if(this.currentSource instanceof HTMLAudioElement)this.currentSource.pause(),this.currentSource.currentTime=0;else if(this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.stop()}catch(o){ln("Failed to stop AudioBufferSourceNode in stop().",o)}}}destroy(){this.disconnectSource(),this.eventListeners.clear()}start(o=0,e=0){this.currentSource instanceof AudioBufferSourceNode?this.currentSource.start(o,e):this.currentSource instanceof HTMLAudioElement&&this.currentSource.play()}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},pa=class{constructor(o,e){this.token=o,this.endVolume=e,this.cancelled=!1,this.finishedInternal=!1,this._finished=new Promise(t=>{this.resolveFinished=t})}get finished(){return this._finished}cancel(){this.cancelled||this.finishedInternal||(this.cancelled=!0,this.resolveFinished())}finish(){this.finishedInternal||(this.finishedInternal=!0,this.token.setVolume(this.endVolume),this.resolveFinished())}isCancelled(){return this.cancelled}isFinished(){return this.finishedInternal}getTargetVolume(){return this.endVolume}},uc=class{constructor(o,e,t={},n){this._isPlaying=!1,this._isPaused=!1,this._isMuted=!1,this.volume=1,this.rate=1,this.contextStartTime=0,this.startOffset=0,this.pauseOffset=0,this.duration=0,this.currentFade=null,this.audioContext=o,this.volume=t.volume??1,this.rate=t.rate??1,this.startOffset=t.startOffset??0,this.duration=t.duration??0,this.outputNode=n??o.destination,this.gainNode=o.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.outputNode),this.sourceController=new cc(o,this.gainNode),this.sourceController.setSource(e);let i=this.startOffset;this.sourceController.start(0,i),this.contextStartTime=this.audioContext.currentTime,this._isPlaying=!0,this.duration>0&&setTimeout(()=>{this._isPlaying&&this.stop()},this.duration*1e3)}emit(o){if(this.sourceController.emit(o),o==="ended"){this._isPlaying=!1;try{this.gainNode.disconnect()}catch(e){ln("Failed to disconnect gain node on natural end.",e)}}}setVolume(o){return this.currentFade&&(this.currentFade.cancel(),this.currentFade=null),o=Math.max(0,Math.min(1,o)),this.volume=o,this._isMuted||(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=o),this}getVolume(){return this.volume}mute(o){let e=o!==void 0?o:!0;if(this._isMuted=e,this.currentFade&&!this.currentFade.isFinished()&&!this.currentFade.isCancelled()){let t=this.currentFade.getTargetVolume();this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.volume=t,this.gainNode.gain.value=e?0:t,this.currentFade.finish(),this.currentFade=null}else this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=e?0:this.volume;return this}unmute(){return this.mute(!1)}isMuted(){return this._isMuted}pause(){if(!this._isPlaying||this._isPaused)return this;let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?(o.pause(),this.pauseOffset=o.currentTime):o instanceof AudioBufferSourceNode&&(this.pauseOffset=this.getCurrentTime(),this.sourceController.stop()),this._isPlaying=!1,this._isPaused=!0,this.emit("pause"),this}resume(){if(!this._isPaused)return this;let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement){let e=o.play();e&&typeof e.catch=="function"&&e.catch(()=>{this._isPlaying=!1,this._isPaused=!0})}else if(o instanceof AudioBufferSourceNode){let e=this.audioContext.createBufferSource();e.buffer=o.buffer,e.playbackRate.value=this.rate,e.loop=o.loop,e.loopStart=o.loopStart,e.loopEnd=o.loopEnd,this.sourceController.refreshSource(e),this.startOffset=this.pauseOffset,this.contextStartTime=this.audioContext.currentTime,this.sourceController.start(0,this.pauseOffset)}return this._isPlaying=!0,this._isPaused=!1,this.emit("resume"),this}isPlaying(){return this._isPlaying}isPaused(){return this._isPaused}stop(o={}){let{fadeDuration:e=0}=o;return e>0?this.fade(this.getVolume(),0,e).finished.then(()=>{this.doStop()}):this.doStop(),this}doStop(){this.sourceController.stop(),this._isPlaying=!1,this._isPaused=!1,this.emit("stop"),this.sourceController.destroy();try{this.gainNode.disconnect()}catch(o){ln("Failed to disconnect gain node on stop().",o)}}setRate(o){o=Math.max(.001,o),this.rate=o;let e=this.sourceController.getSource();return e instanceof HTMLAudioElement?e.playbackRate=o:e instanceof AudioBufferSourceNode&&(e.playbackRate.value=o),this}getRate(){return this.rate}seek(o){o=Math.max(0,o);let e=this.sourceController.getSource();if(e instanceof HTMLAudioElement)e.currentTime=o,this.emit("seek");else if(e instanceof AudioBufferSourceNode){let t=this.getCurrentTime();if(Math.abs(o-t)>.01){if(this._isPlaying){this.sourceController.stop();let n=this.audioContext.createBufferSource();n.buffer=e.buffer,n.playbackRate.value=this.rate,n.loop=e.loop,n.loopStart=e.loopStart,n.loopEnd=e.loopEnd,this.sourceController.refreshSource(n),this.startOffset=this.audioContext.currentTime-o,this.sourceController.start(0,o)}else this._isPaused&&(this.pauseOffset=o);this.emit("seek")}}return this}getCurrentTime(){let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement)return o.currentTime;if(o instanceof AudioBufferSourceNode){if(this._isPaused)return this.pauseOffset;if(this._isPlaying)return(this.audioContext.currentTime-this.contextStartTime)*this.rate+this.startOffset}return 0}getDuration(){let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?o.duration||0:o instanceof AudioBufferSourceNode&&o.buffer?o.buffer.duration:this.duration}fade(o,e,t){if(this.currentFade&&this.currentFade.cancel(),o=Math.max(0,Math.min(1,o)),e=Math.max(0,Math.min(1,e)),t=Math.max(0,t),t===0){this.setVolume(e);let r=new pa(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new pa(this,e);this.currentFade=n;let i=this.audioContext.currentTime;return this.gainNode.gain.setValueAtTime(o,i),this.gainNode.gain.linearRampToValueAtTime(e,i+t/1e3),setTimeout(()=>{!n.isCancelled()&&!n.isFinished()&&(this.volume=e,n.finish(),this.currentFade=null)},t),n}on(o,e){return this.sourceController.on(o,e),this}off(o,e){return this.sourceController.off(o,e),this}once(o,e){return this.sourceController.once(o,e),this}},pc=class{constructor(o){this.alive=!0,this.refCount=0,this.audioBuffer=o}addRef(){this.refCount++}releaseRef(){this.refCount>0&&this.refCount--}getRefCount(){return this.refCount}async unload(){this.refCount>0||(this.alive=!1)}async forceUnload(){this.alive=!1,this.refCount=0}isAlive(){return this.alive}raw(){if(!this.alive)throw new Error("CachedAudio has been unloaded.");return this.audioBuffer}},dc=10*1024*1024,mc=class{constructor(o){this.cache=new Map,this.loadingPromises=new Map,this.audioContext=o}async load(o){let e=this.cache.get(o);if(e&&e.isAlive())return e;let t=this.loadingPromises.get(o);if(t)return t;let n=this.doLoad(o);this.loadingPromises.set(o,n);try{let i=await n;return this.cache.set(o,i),i}finally{this.loadingPromises.delete(o)}}async doLoad(o){let e=await(await fetch(o)).arrayBuffer(),t=await this.audioContext.decodeAudioData(e);return new pc(t)}clear(){for(let o of this.cache.values())o.forceUnload();this.cache.clear(),this.loadingPromises.clear()}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size}}},fc={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},fa=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...fc,...o},lc(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new mc(this.audioContext),this.masterChannel=new ac("__master__",this,{volume:this.options.volume},null),this.initialize()}async onceReady(){return this.readyPromise?(await this.readyPromise,this):this}initialize(){this.isReady||(this.readyPromise=this.waitForUnlock())}waitForUnlock(){return typeof document>"u"?(this.isReady=!0,Promise.resolve()):this.audioContext.state==="running"?(this.isReady=!0,Promise.resolve()):new Promise(o=>{let e=()=>{if(this.destroyed){this.clearUnlockHandler(),o();return}this.audioContext.resume().then(()=>{this.audioContext.state==="running"&&(this.clearUnlockHandler(),this.isReady=!0,o())}).catch(t=>{ln("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:l=!1}=e??{},c,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")c=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),c=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),c=p}let d=new uc(this.audioContext,c,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(c instanceof AudioBufferSourceNode?(c.loop=l,l&&s!==void 0&&(c.loopStart=r,c.loopEnd=s)):c instanceof HTMLAudioElement&&(c.loop=l),u){let p=!1,f=()=>{p||(p=!0,u.releaseRef?.())};d.once("ended",f),d.once("stop",f)}return d}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<dc?"full":"stream"}catch(t){return ln("Failed to resolve load mode via HEAD request, falling back to 'stream'.",t),"stream"}}createStreamSource(o){let e=new Audio(o);return e.crossOrigin="anonymous",e}checkChannelLimit(){if(this.registeredChannels.size+1>=this.options.maxChannels)throw new Error(`Maximum number of channels (${this.options.maxChannels}) reached.`)}registerChannel(o){this.registeredChannels.add(o)}unregisterChannel(o){this.registeredChannels.delete(o)}setVolume(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.setVolume(o),this}getVolume(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getVolume()}mute(o){return this.ensureNotDestroyed(),this.ensureReady(),o===void 0?this.masterChannel.mute():this.masterChannel.mute(o),this}unmute(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.unmute(),this}isMuted(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.isMuted()}createChannel(o,e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.createChannel(o,e)}getChannel(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannel(o)}getChannels(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannels()}async load(o){return this.ensureNotDestroyed(),this.ensureReady(),this.audioCache.load(o)}async play(o,e){this.ensureNotDestroyed(),this.ensureReady();let t=this.masterChannel.getTokens();for(let n of t)try{n.stop()}catch{}return this.masterChannel.play(o,e)}getTokens(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getTokens()}destroy(){this.destroyed||(this.destroyed=!0,this.clearUnlockHandler(),this.audioCache.clear(),this.masterChannel.remove(),this.registeredChannels.clear(),this.audioContext.close().catch(o=>{ln("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var fe=class fe{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new fa({maxChannels:fe.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=fe.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,fe.BusRampTimeConstant),r.setValueAtTime(s,a+fe.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${et.sound}" instead.`)),this.channels.get(et.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=fe.defaultFade(e)){let n=new S;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=fe.clipRegionOf(e),a=await i.play(r,{volume:0,...fe.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&fe.applyLoopRegion(a,s);let l=e.state.muted??!1;a.mute(l),e.state.muted=l,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(c=>{a.once("ended",()=>c())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t=fe.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new E(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=fe.clipRegionOf(e),s=await n.play(i,{volume:0,...fe.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&fe.applyLoopRegion(s,r);let a=e.state.muted??!1;return s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:i,originalVolume:t.end}),t.duration>0?s.fade(0,t.end,t.duration):s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,s}catch(n){throw this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,n),n}}stop(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.token.stop(),this.state.delete(e),n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.token.stop(),this.state.delete(e),n.resolve()}),n}setVolume(e,t,n=0){let i=new S;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new S;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}pause(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition=i.token.getCurrentTime(),i.token.pause(),e.state.paused=!0,n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.pausePosition=i.token.getCurrentTime(),i.token.pause(),i.token.setVolume(i.originalVolume),e.state.paused=!0,n.resolve()}),n}resume(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,n.resolve()):(i.token.setVolume(0),i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),i.token.fade(0,i.originalVolume,t).finished.then(()=>{e.state.paused=!1,n.resolve()})),n}seek(e,t){if(!this.state.has(e))return S.resolve(void 0);let n=this.state.get(e),i=fe.clampToRegion(t,fe.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),S.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,l=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=l<i?l:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,S.resolve(void 0)):S.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime()}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=await this.sound.load(e.config.src),r=fe.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...fe.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&fe.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(fe.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let l=e.state.muted??!1;a.mute(l),e.state.muted=l,e.state.paused?a.pause():t.isPlaying||a.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}preload(e){return this.ready.then(()=>this.sound.load(e.config.src)).then(()=>{}).catch(t=>{this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${e.config.src}")`,t)})}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),this.isReady&&this.busTree&&this.busTree.getNodes().forEach(e=>{this.applyBusVolume(this.channels.get(e.id),this.mixer.getEffectiveVolume(e.id),!1)})}setBusVolume(e,t){this.mixer.setVolume(e,t)}getBusVolume(e){return this.mixer.getVolume(e)}getBuses(){return this.mixer.list()}setGroupVolume(e,t){this.setBusVolume(e,t)}getGroupVolume(e){return this.getBusVolume(e)}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}destroy(){this.reset(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};fe.MaxChannels=1024,fe.BusRampTimeConstant=.02,fe.BusRampSettle=fe.BusRampTimeConstant*5;var _i=fe;import*as Tc from"html-to-image";var eo=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new X}addNotification(e){this.notifications.push(e),this.flush()}removeNotification(e){this.notifications=this.notifications.filter(t=>t!==e),this.flush()}clearNotifications(){this.notifications=[],this.flush()}consume(e){let t=new S,n=new ke(t);return t.registerSkipController(new F(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};function to(o,e,t){let n={},i={};Object.keys(e).forEach(s=>{let a=s;a==="style"&&e.style?Object.assign(n,e.style):e[a]!==void 0&&a!=="key"&&(i[a]=e[a])}),Object.keys(n).length>0&&Object.assign(o.style,n);let r=t?t(i):i;for(let[s,a]of Object.entries(r))o.getAttribute(s)!==a&&o.setAttribute(s,a)}var hc=4e3,ya={zIndex:0,visibility:"visible"},gc={...ya,zIndex:1},ha={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function no(){return{zIndex:"auto",visibility:"visible",opacity:1,transform:"none",translate:"none",filter:"none",clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat"}}function yc(){return{...no(),visibility:"hidden"}}var io=class{constructor(e){this.gameState=e;this.sceneElements=new Map;this.overlayHost=null;this.running=null}registerScene(e,t){t?this.sceneElements.set(e.getId(),t):this.sceneElements.delete(e.getId())}registerOverlayHost(e){this.overlayHost=e}reset(){this.running?.controller.complete(),this.running=null}skip(){this.running&&(this.gameState.logger.debug("StageTransition","Transition skipped"),this.running.controller.complete())}apply(e,t,n){this.running?.controller.complete();let i=e;typeof i._setDetached=="function"&&i._setDetached(!0);let r=e.createTask(this.gameState),s=e.requestAnimations(r.animations),a=new S().registerSkipController(new F(s.cancel)),l=new ke(a),c=[],u=r.resolve.map(f=>{if(typeof f=="function"){let m=this.createOverlay();return c.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(f.key==="target"?t.to:t.from).getId(),role:f.key}}),d={task:r,controller:s,roles:t,targets:u,overlays:c,cancelLoadGate:()=>{},stale:!1};this.running=d,s.onUpdate(f=>this.applyFrame(d,f)),s.onComplete(()=>{this.settle(d,[[t.to,no()],[t.from,yc()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(d,[[t.from,no()],[t.to,no()]]),l.abort()}),this.applyFrame(d,r.animations.map(f=>f.start));let p=this.waitForSceneReady(t.to);return d.cancelLoadGate=p.cancel,p.promise.then(()=>{d.stale||s.start()}),l}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?r.element:this.sceneElements.get(r.sceneId)??null;if(!s)return;let a=typeof n=="function"?n:n.resolver,l=r.kind==="overlay"?ha:r.role==="target"?gc:ya,c=j({style:l},a(...t));to(s,c,vc)})}settle(e,t){e.stale=!0,e.cancelLoadGate(),e.overlays.forEach(n=>n.remove()),e.overlays.length=0,t.forEach(([n,i])=>{let r=this.sceneElements.get(n.getId());r&&Object.assign(r.style,i)}),this.running===e&&(this.running=null)}createOverlay(){let e=document.createElement("div");return e.setAttribute("data-element-type","stage-transition-overlay"),Object.assign(e.style,ha),this.overlayHost?.appendChild(e),e}waitForSceneReady(e){let t=this.sceneElements.get(e.getId());if(!t)return{promise:Promise.resolve(),cancel:()=>{}};let n=()=>{},i=new Promise(s=>{n=this.gameState.schedule(()=>{this.gameState.logger.weakWarn("StageTransition","Timed out waiting for the incoming scene to load"),s()},hc)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(Sc)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},ga=["src","width","height"];function vc(o){if(!ga.some(t=>t in o))return o;let e={...o};return ga.forEach(t=>delete e[t]),e}function Sc(o){return o.getAttribute("src")?typeof o.decode=="function"?o.decode().then(()=>{},()=>{}):o.complete?Promise.resolve():new Promise(e=>{let t=()=>{o.removeEventListener("load",t),o.removeEventListener("error",t),e()};o.addEventListener("load",t),o.addEventListener("error",t)}):Promise.resolve()}var oo=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=Vi(6),{action:r,timeline:s,stackModel:a}=e,l=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:l,stackModel:a}),this.history.length>this.maxHistorySize){let c=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(c))}return{id:i}}has(e){return this.history.some(t=>t.id===e)}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var ro=class o{constructor(e){this.history=[];this.cursor=-1;this.resumingAtCursor=!1;this.actionHistoryMgr=e,this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){let t=this.history[this.cursor];if(this.resumingAtCursor&&t&&t.action===e.action)return this.history[this.cursor]={...e,token:t.token},this.resumingAtCursor=!1,this;this.resumingAtCursor=!1;let n=this.history[this.cursor+1];return n&&n.action===e.action?this.history[this.cursor+1]={...e,token:n.token}:(this.history.length=this.cursor+1,this.history.push(e)),this.cursor++,this}getHistory(){return this.history.slice(0,this.cursor+1)}getFuture(){return this.history.slice(this.cursor+1)}getCursor(){return this.cursor}getAt(e){return this.history[e]??null}indexOfToken(e){return this.history.findIndex(t=>t.token===e)}setCursor(e){return this.cursor=Math.max(-1,Math.min(e,this.history.length-1)),this.resumingAtCursor=!0,this}canUndo(){return this.cursor>0}canRedo(){return this.cursor<this.history.length-1}getByToken(e){return this.history.find(t=>t.token===e)??null}serialize(){return this.history.slice(0,this.cursor+1).map(e=>o.toSerialized(e))}serializeAll(){return this.history.map(e=>o.toSerialized(e))}load(e,t){this.history=[];for(let n of e){let i=n.actionId!=null?t.get(n.actionId):void 0;i&&this.history.push({token:n.token??Vi(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1}reset(){this.history=[],this.cursor=-1,this.resumingAtCursor=!1}static toSerialized(e){return{token:e.token,actionId:e.action.getId(),element:e.element,isPending:e.isPending,snapshot:e.snapshot??null}}updateByToken(e,t){let n=this.history.find(i=>i.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(i=>i.id)),n=this.history.slice(0,this.cursor+1).filter(i=>t.has(i.token)).length;this.history=this.history.filter(i=>!t.has(i.token)),this.cursor=Math.max(-1,Math.min(this.cursor-n,this.history.length-1))}};var vn=class extends q{executeAction(e,t){let n=new S().registerSkipController(new F(()=>{l.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,l=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.reset()},e.gameHistory.updateByToken(c,p=>{p&&p.element.type==="menu"&&(p.element.selected=u.evaluated,p.isPending=!1)})}),{id:c}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{l.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:c,action:this,element:{type:"menu",text:l.prompt,selected:null},isPending:!0,snapshot:e.getLiveGame().captureGameState()}),n}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(l=>l.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};vn.ActionTypes=Gs;var Sn=class Sn extends ce{constructor(t,n={}){super();this.choices=[];this.prompt=ge.isSentence(t)?t:t===null?null:new ge(t),this.config=j(Sn.defaultConfig,n)}static prompt(t,n={}){return new Sn(t!==void 0?t:null,n)}static choose(t,n){return new Sn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return ge.isSentence(t)&&n?i.choices.push({prompt:ge.toSentence(t),action:this.narrativeToActions(n),config:{}}):(te.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:ge.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:ge.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?Y.from(t.config.disabled):void 0,hidden:t.config?.hidden?Y.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),i}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Oe("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.hideIf` before `menu.choose`");return n.config.hidden=Y.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Oe("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.disableIf` before `menu.choose`");return n.config.disabled=Y.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:Y.not(Y.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:Y.not(Y.from(t))}})}fromChained(t){return[new vn(this.chain(),vn.ActionTypes.action,new w().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?Xt.say(n).getActions():Be.toActions([n])))}constructNodes(t,n,i){for(let r=0;r<t.length;r++){let s=t[r].contentNode,a=t[r+1]?.contentNode;a&&s.setChild(a),r===this.choices.length-1&&n&&s.setChild(n),r===0&&i&&i.setChild(s)}return t}constructChoices(){return this.choices.map(t=>({action:this.constructNodes(t.action),prompt:t.prompt,config:t.config??{}}))}};Sn.defaultConfig={},Sn.targetAction=vn;var ur=Sn;var ht={shutter:0,shutterColor:"#000",vignette:0,vignetteColor:"#000",vignetteInner:"44%",vignetteOuter:"78%"};function pr(o){return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(1,o))}function ii(o,e){return typeof o=="string"&&o.length>0?o:e}function va(o){let e=pr(o.shutter);return{backgroundColor:ii(o.shutterColor,ht.shutterColor),clipPath:`inset(0 0 ${100-50*e}% 0)`}}function Sa(o){let e=pr(o.shutter);return{backgroundColor:ii(o.shutterColor,ht.shutterColor),clipPath:`inset(${100-50*e}% 0 0 0)`}}function Ta(o){let e=ii(o.vignetteInner,ht.vignetteInner),t=ii(o.vignetteOuter,ht.vignetteOuter),n=`radial-gradient(circle at center, transparent ${e}, black ${t})`;return{backgroundColor:ii(o.vignetteColor,ht.vignetteColor),opacity:pr(o.vignette),maskImage:n,WebkitMaskImage:n,maskSize:"100% 100%",WebkitMaskSize:"100% 100%",maskPosition:"center",WebkitMaskPosition:"center",maskRepeat:"no-repeat",WebkitMaskRepeat:"no-repeat",maskMode:"alpha",WebkitMaskMode:"alpha"}}var lt=class lt extends Qe{static get DefaultUserConfig(){return lt._defaultUserConfig??(lt._defaultUserConfig=new K({...ee.DefaultTransformState.getDefaultConfig(),opacity:1,...ht}))}constructor(e={}){super();let t=lt.DefaultUserConfig.create(e),n=lt.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}shutter(e,t,n){return this.lens({shutter:lt.clampLens(e)},{duration:t,ease:n})}vignette(e,t,n){return this.lens({vignette:lt.clampLens(e)},{duration:t,ease:n})}lens(e,t){return this.transform(new Z(e,t))}resetCamera(e,t){return this.transform(new Z([{props:{filter:"none"},options:{duration:0}},{props:{position:new rt("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,shutter:ht.shutter,vignette:ht.vignette},options:{duration:e,ease:t}},{props:{shutterColor:ht.shutterColor,vignetteColor:ht.vignetteColor,vignetteInner:ht.vignetteInner,vignetteOuter:ht.vignetteOuter},options:{duration:0}}]))}static clampLens(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}bringToFront(){throw new E(`A camera cannot be brought to front. It is not an element inside a layer, it is what the layers are viewed through, so it has nothing to be in front of \u2014 waiting for it to be added to the stage will not help. Use a camera transform such as Camera.zoom or Camera.pan to change what is in view. (camera: ${this.config.name})`)}reset(){return super.reset(),this.transformState.resetTo(this.getInitialTransformState().get()),this}toData(){return{transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.transformState.resetTo(ee.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}copy(){return new lt(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(lt.DefaultUserConfig.keys());return new ee(lt.DefaultUserConfig.create(e.get()).get())}};lt._defaultUserConfig=null,lt.DefaultConfig=new K({name:"(camera)"});var oi=lt;var cn=class cn extends Rn{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.elementBaseline=null;this.name=t;let{camera:i,...r}=n;this.config=j(cn.defaultConfig,r),this._camera=i??new oi}static empty(){return new cn("empty").entry(new ft("empty"))}get camera(){return this._camera}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let i=new In(t,n);return this.registerPersistent(i),i}registerService(t,n){return this.services.set(t,n),this}getService(t){let n=this.services.get(t);if(!n)throw new Oe(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return js(this.stringify(t))}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,i)=>{if(!n.serialize||typeof n.serialize!="function")return;let r=n.serialize();if(r!==null){{if(r instanceof Promise)throw new ne(`Service ${i} serialize method should not return a promise`);if(!Jo(r))throw new ne(`Service ${i} serialize method should return a pure object.
|
|
26
|
+
Current Parent (src: `+m.state.currentSrc+")");d.set(v,m)}});let p=[...this._initScene(this),...c.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()),...l.map(m=>m._init()),...r],h=super.constructNodes(p),f=new k(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 He(`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 He(`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():We.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 l=s.shift();if(!i.has(l)){if(i.add(l),l instanceof ae){let c=l.callee;if(P.isImageSrc(c.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:P.srcToURL(c.state.backgroundImage.state.currentSrc)}),l.type===_.jumpTo){let u=l,d=Fe.getScene(t,u.contentNode.getContent()[0]);if(!d)throw l._sceneNotFoundError(l.getSceneName(u.contentNode.getContent()[0]));let p=Re.getPreloadableSrc(t,l);if(p&&this.srcManager.register(p),r.has(u)||n.has(d))continue;r.add(u),a.add(d),n.add(d)}}else if(l instanceof Se){let c=Re.getPreloadableSrc(t,l);c&&this.srcManager.register(c)}else if(l instanceof et)this.srcManager.register(l.callee);else if(l instanceof nt){let c=l.type===Yt.say?l.contentNode.getContent():null;for(let u of va(l.callee,c))this.srcManager.register({type:"image",src:P.srcToURL(u)})}else if(l instanceof re){let u=l.getFutureActions(t,{allowFutureScene:!0});s.push(...u)}else l instanceof ye&&this.srcManager.register(l.callee.srcManager.getSrc());s.push(...l.getFutureActions(t,{allowFutureScene:!0}))}}a.forEach(l=>{l.registerSrc(t,n),this.srcManager.registerFuture(l.srcManager)})}assignActionId(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}),i=new Set;n.forEach(a=>{let l=a.getStaticId();if(l){if(i.has(l))throw new He(`Duplicate static action id: ${l}`);i.add(l)}});let r=0,s=()=>{let a=`a-${r++}`;for(;i.has(a);)a=`a-${r++}`;return i.add(a),a};n.forEach(a=>{let l=a.getStaticId();a.resolveId(l||s())})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((i,r)=>{i.resolveId(`e-${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):(Fe.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=ve.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,[tt.bgm]))throw new He(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
|
|
27
|
+
To prevent unintended behavior and unexpected results, the sound have to be on the music bus (or any bus beneath it). Please use \`Sound.bgm()\` to create the sound.`);let n=this.state?.backgroundImage?this.state.backgroundImage.reset():new G({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),i=t.backgroundMusic?this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic:null;return{backgroundImage:n,backgroundMusic:i}}_jumpTo(t){return this.chain(new ae(this.chain(),"scene:jumpTo",new k().setContent([t])))}_exit(){return new ae(this.chain(),"scene:exit",new k().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new ae(i,_.transitionToScene,new k().setContent([t,n]))):i}_init(t){return new ae(this.chain(),"scene:init",new k().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};Fe.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},Fe.DefaultUserConfig=new B({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),Fe._defaultSceneConfig=null;var yt=Fe;import*as Da from"howler";var ro=class{constructor(e,t){this.game=e,this.prefix=t}log(e,...t){this.isEnabled("log")&&console.log(...this.colorLog("gray",e,...t))}info(e,...t){this.isEnabled("info")&&console.info(...this._log(e,...t))}warn(e,...t){this.isEnabled("warn")&&console.warn(...this._log(e,...t))}error(e,...t){this.isEnabled("error")&&console.error(...this._log(e,...t))}debug(e,...t){this.isEnabled("debug")&&console.debug(...this.colorLog("gray",e,...t))}trace(e,...t){this.isEnabled("trace")&&console.trace(this._log(e,...t))}weakWarn(e,...t){this.isEnabled("warn")&&console.log(...this.colorLog("yellow",e,...t))}weakError(e,...t){this.isEnabled("error")&&console.log(...this.colorLog("red",e,...t))}verbose(e,...t){this.isEnabled("verbose")&&console.log(...this.colorLog("gray",e,...t))}group(e,t=!1){let n=this._log(e).join(" ");return this.isEnabled("info")&&(t?console.groupCollapsed(n):console.group(n)),{end:()=>{this.isEnabled("info")&&console.groupEnd()}}}isEnabled(e){return typeof this.game.config.app.logger=="boolean"?this.game.config.app.logger:this.game.config.app.logger[e]}_log(e,...t){return t.length===0?[this.prefix||"",e]:[`${this.prefix||""} [${e}]`,...t]}colorLog(e,t,...n){if(n.length===0)return[`%c${this.prefix||""} ${t}`,`color: ${e}`];let i=[],r=[],s=[];return this.prefix?(i.push(`%c${this.prefix} [${t}]`),r.push(`color: ${e}`)):(i.push(`%c[${t}]`),r.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(i.push(`%c${a}`),r.push(`color: ${e}`)):(i.push("%O"),s.push(a),r.push(""))}),[i.join(" ")].concat(r,s)}};var Tc={volume:1,limit:1/0},bc=class Ta{constructor(e,t,n,i){this.subChannels=new Map,this.tokens=new Set,this.tokenQueue=[],this.muted=!1,this.removed=!1,this.name=e,this.audioProvider=t,this.parentChannel=i??null,this.options={...Tc,...n},this.volume=this.options.volume;let r=this.audioProvider.getAudioContext();this.gainNode=r.createGain(),this.gainNode.gain.value=this.muted?0:this.volume,this.connectToParent()}connectToParent(){this.parentChannel?this.gainNode.connect(this.parentChannel.getGainNode()):this.gainNode.connect(this.audioProvider.getAudioContext().destination)}getGainNode(){return this.gainNode}ensureNotRemoved(){if(this.removed)throw new Error(`Channel "${this.name}" has been removed and cannot be used.`)}getName(){return this.name}async play(e,t){if(this.ensureNotRemoved(),this.tokens.size>=this.options.limit){let r=this.tokenQueue.shift();r&&r.stop()}let n=await this.audioProvider.createToken(e,t,this.gainNode);this.tokens.add(n),this.tokenQueue.push(n);let i=()=>{this.tokens.delete(n);let r=this.tokenQueue.indexOf(n);r!==-1&&this.tokenQueue.splice(r,1)};return n.once("ended",i),n.once("stop",i),n}createChannel(e,t){if(this.ensureNotRemoved(),this.subChannels.has(e))throw new Error(`Channel "${e}" already exists under "${this.name}".`);this.audioProvider.checkChannelLimit();let n=new Ta(e,this.audioProvider,t,this);return this.subChannels.set(e,n),this.audioProvider.registerChannel(n),n}getChannel(e){return this.ensureNotRemoved(),this.subChannels.get(e)??null}getChannels(){return this.ensureNotRemoved(),Array.from(this.subChannels.values())}setVolume(e){return this.ensureNotRemoved(),this.volume=Math.max(0,Math.min(1,e)),this.muted||(this.gainNode.gain.value=this.volume),this}getVolume(){return this.volume}mute(e){return this.ensureNotRemoved(),this.muted=e!==void 0?e:!0,this.gainNode.gain.value=this.muted?0:this.volume,this}unmute(){return this.mute(!1)}isMuted(){return this.muted}remove(){if(this.removed)return this;this.removed=!0;for(let t of this.tokens)t.stop();this.tokens.clear();let e=Array.from(this.subChannels.values());this.subChannels.clear();for(let t of e)t.remove();try{this.gainNode.disconnect()}catch(t){console.warn("Failed to disconnect Channel gain node during remove().",t)}return this.audioProvider.unregisterChannel(this),this.parentChannel&&this.parentChannel.removeSubChannel(this.name),this}removeSubChannel(e){this.subChannels.delete(e)}getTokens(){this.ensureNotRemoved();let e=[...this.tokenQueue];for(let t of this.subChannels.values())e.push(...t.getTokens());return e}isRemoved(){return this.removed}getParent(){return this.parentChannel}getOptions(){return{...this.options}}},ba=!1;function Ac(o){ba=o}function pn(o,e){ba||(e!==void 0?console.warn(o,e):console.warn(o))}var Cc=class{constructor(o,e){this.currentSource=null,this.mediaElementSource=null,this.endedHandler=null,this.eventListeners=new Map,this.audioContext=o,this.gainNode=e}setSource(o){this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.setupEventListeners()}getSource(){return this.currentSource}refreshSource(o){let e=new Map(this.eventListeners);this.disconnectSource(),this.currentSource=o,o instanceof AudioBufferSourceNode?o.connect(this.gainNode):o instanceof HTMLAudioElement&&(this.mediaElementSource=this.audioContext.createMediaElementSource(o),this.mediaElementSource.connect(this.gainNode)),this.eventListeners=e,this.setupEventListeners()}disconnectSource(){if(this.currentSource){if(this.removeAllEventListeners(),this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.disconnect()}catch(o){pn("Failed to disconnect AudioBufferSourceNode in disconnectSource().",o)}else this.currentSource instanceof HTMLAudioElement&&(this.currentSource.pause(),this.currentSource.src="",this.currentSource.load());if(this.mediaElementSource){try{this.mediaElementSource.disconnect()}catch(o){pn("Failed to disconnect MediaElementAudioSourceNode in disconnectSource().",o)}this.mediaElementSource=null}this.currentSource=null}}setupEventListeners(){this.currentSource&&(this.endedHandler=o=>{this.emit("ended")},this.currentSource instanceof HTMLAudioElement?this.currentSource.addEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.addEventListener("ended",this.endedHandler))}removeAllEventListeners(){!this.currentSource||!this.endedHandler||(this.currentSource instanceof HTMLAudioElement?this.currentSource.removeEventListener("ended",this.endedHandler):this.currentSource instanceof AudioBufferSourceNode&&this.currentSource.removeEventListener("ended",this.endedHandler),this.endedHandler=null)}emit(o){let e=this.eventListeners.get(o);e&&[...e].forEach((t,n)=>{try{t.callback()}catch(i){console.error(`Error in event listener for '${o}':`,i)}t.once&&e.splice(e.indexOf(t),1)})}on(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!1})}off(o,e){let t=this.eventListeners.get(o);if(!t)return;let n=t.findIndex(i=>i.callback===e);n!==-1&&t.splice(n,1)}once(o,e){this.eventListeners.has(o)||this.eventListeners.set(o,[]),this.eventListeners.get(o).push({callback:e,once:!0})}stop(){if(this.currentSource){if(this.currentSource instanceof HTMLAudioElement)this.currentSource.pause(),this.currentSource.currentTime=0;else if(this.currentSource instanceof AudioBufferSourceNode)try{this.currentSource.stop()}catch(o){pn("Failed to stop AudioBufferSourceNode in stop().",o)}}}destroy(){this.disconnectSource(),this.eventListeners.clear()}start(o=0,e=0){this.currentSource instanceof AudioBufferSourceNode?this.currentSource.start(o,e):this.currentSource instanceof HTMLAudioElement&&this.currentSource.play()}pause(){this.currentSource instanceof HTMLAudioElement?this.currentSource.pause():this.currentSource instanceof AudioBufferSourceNode&&this.stop()}},Sa=class{constructor(o,e){this.token=o,this.endVolume=e,this.cancelled=!1,this.finishedInternal=!1,this._finished=new Promise(t=>{this.resolveFinished=t})}get finished(){return this._finished}cancel(){this.cancelled||this.finishedInternal||(this.cancelled=!0,this.resolveFinished())}finish(){this.finishedInternal||(this.finishedInternal=!0,this.token.setVolume(this.endVolume),this.resolveFinished())}isCancelled(){return this.cancelled}isFinished(){return this.finishedInternal}getTargetVolume(){return this.endVolume}},xc=class{constructor(o,e,t={},n){this._isPlaying=!1,this._isPaused=!1,this._isMuted=!1,this.volume=1,this.rate=1,this.contextStartTime=0,this.startOffset=0,this.pauseOffset=0,this.duration=0,this.currentFade=null,this.audioContext=o,this.volume=t.volume??1,this.rate=t.rate??1,this.startOffset=t.startOffset??0,this.duration=t.duration??0,this.outputNode=n??o.destination,this.gainNode=o.createGain(),this.gainNode.gain.value=this.volume,this.gainNode.connect(this.outputNode),this.sourceController=new Cc(o,this.gainNode),this.sourceController.setSource(e);let i=this.startOffset;this.sourceController.start(0,i),this.contextStartTime=this.audioContext.currentTime,this._isPlaying=!0,this.duration>0&&setTimeout(()=>{this._isPlaying&&this.stop()},this.duration*1e3)}emit(o){if(this.sourceController.emit(o),o==="ended"){this._isPlaying=!1;try{this.gainNode.disconnect()}catch(e){pn("Failed to disconnect gain node on natural end.",e)}}}setVolume(o){return this.currentFade&&(this.currentFade.cancel(),this.currentFade=null),o=Math.max(0,Math.min(1,o)),this.volume=o,this._isMuted||(this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=o),this}getVolume(){return this.volume}mute(o){let e=o!==void 0?o:!0;if(this._isMuted=e,this.currentFade&&!this.currentFade.isFinished()&&!this.currentFade.isCancelled()){let t=this.currentFade.getTargetVolume();this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.volume=t,this.gainNode.gain.value=e?0:t,this.currentFade.finish(),this.currentFade=null}else this.gainNode.gain.cancelScheduledValues(this.audioContext.currentTime),this.gainNode.gain.value=e?0:this.volume;return this}unmute(){return this.mute(!1)}isMuted(){return this._isMuted}pause(){if(!this._isPlaying||this._isPaused)return this;let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?(o.pause(),this.pauseOffset=o.currentTime):o instanceof AudioBufferSourceNode&&(this.pauseOffset=this.getCurrentTime(),this.sourceController.stop()),this._isPlaying=!1,this._isPaused=!0,this.emit("pause"),this}resume(){if(!this._isPaused)return this;let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement){let e=o.play();e&&typeof e.catch=="function"&&e.catch(()=>{this._isPlaying=!1,this._isPaused=!0})}else if(o instanceof AudioBufferSourceNode){let e=this.audioContext.createBufferSource();e.buffer=o.buffer,e.playbackRate.value=this.rate,e.loop=o.loop,e.loopStart=o.loopStart,e.loopEnd=o.loopEnd,this.sourceController.refreshSource(e),this.startOffset=this.pauseOffset,this.contextStartTime=this.audioContext.currentTime,this.sourceController.start(0,this.pauseOffset)}return this._isPlaying=!0,this._isPaused=!1,this.emit("resume"),this}isPlaying(){return this._isPlaying}isPaused(){return this._isPaused}stop(o={}){let{fadeDuration:e=0}=o;return e>0?this.fade(this.getVolume(),0,e).finished.then(()=>{this.doStop()}):this.doStop(),this}doStop(){this.sourceController.stop(),this._isPlaying=!1,this._isPaused=!1,this.emit("stop"),this.sourceController.destroy();try{this.gainNode.disconnect()}catch(o){pn("Failed to disconnect gain node on stop().",o)}}setRate(o){o=Math.max(.001,o),this.rate=o;let e=this.sourceController.getSource();return e instanceof HTMLAudioElement?e.playbackRate=o:e instanceof AudioBufferSourceNode&&(e.playbackRate.value=o),this}getRate(){return this.rate}seek(o){o=Math.max(0,o);let e=this.sourceController.getSource();if(e instanceof HTMLAudioElement)e.currentTime=o,this.emit("seek");else if(e instanceof AudioBufferSourceNode){let t=this.getCurrentTime();if(Math.abs(o-t)>.01){if(this._isPlaying){this.sourceController.stop();let n=this.audioContext.createBufferSource();n.buffer=e.buffer,n.playbackRate.value=this.rate,n.loop=e.loop,n.loopStart=e.loopStart,n.loopEnd=e.loopEnd,this.sourceController.refreshSource(n),this.startOffset=this.audioContext.currentTime-o,this.sourceController.start(0,o)}else this._isPaused&&(this.pauseOffset=o);this.emit("seek")}}return this}getCurrentTime(){let o=this.sourceController.getSource();if(o instanceof HTMLAudioElement)return o.currentTime;if(o instanceof AudioBufferSourceNode){if(this._isPaused)return this.pauseOffset;if(this._isPlaying)return(this.audioContext.currentTime-this.contextStartTime)*this.rate+this.startOffset}return 0}getDuration(){let o=this.sourceController.getSource();return o instanceof HTMLAudioElement?o.duration||0:o instanceof AudioBufferSourceNode&&o.buffer?o.buffer.duration:this.duration}fade(o,e,t){if(this.currentFade&&this.currentFade.cancel(),o=Math.max(0,Math.min(1,o)),e=Math.max(0,Math.min(1,e)),t=Math.max(0,t),t===0){this.setVolume(e);let r=new Sa(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new Sa(this,e);this.currentFade=n;let i=this.audioContext.currentTime;return this.gainNode.gain.setValueAtTime(o,i),this.gainNode.gain.linearRampToValueAtTime(e,i+t/1e3),setTimeout(()=>{!n.isCancelled()&&!n.isFinished()&&(this.volume=e,n.finish(),this.currentFade=null)},t),n}on(o,e){return this.sourceController.on(o,e),this}off(o,e){return this.sourceController.off(o,e),this}once(o,e){return this.sourceController.once(o,e),this}},wc=class{constructor(o){this.alive=!0,this.refCount=0,this.audioBuffer=o}addRef(){this.refCount++}releaseRef(){this.refCount>0&&this.refCount--}getRefCount(){return this.refCount}async unload(){this.refCount>0||(this.alive=!1)}async forceUnload(){this.alive=!1,this.refCount=0}isAlive(){return this.alive}raw(){if(!this.alive)throw new Error("CachedAudio has been unloaded.");return this.audioBuffer}},kc=10*1024*1024,Pc=class{constructor(o){this.cache=new Map,this.loadingPromises=new Map,this.audioContext=o}async load(o){let e=this.cache.get(o);if(e&&e.isAlive())return e;let t=this.loadingPromises.get(o);if(t)return t;let n=this.doLoad(o);this.loadingPromises.set(o,n);try{let i=await n;return this.cache.set(o,i),i}finally{this.loadingPromises.delete(o)}}async doLoad(o){let e=await(await fetch(o)).arrayBuffer(),t=await this.audioContext.decodeAudioData(e);return new wc(t)}clear(){for(let o of this.cache.values())o.forceUnload();this.cache.clear(),this.loadingPromises.clear()}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size}}},Ec={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},Aa=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...Ec,...o},Ac(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new Pc(this.audioContext),this.masterChannel=new bc("__master__",this,{volume:this.options.volume},null),this.initialize()}async onceReady(){return this.readyPromise?(await this.readyPromise,this):this}initialize(){this.isReady||(this.readyPromise=this.waitForUnlock())}waitForUnlock(){return typeof document>"u"?(this.isReady=!0,Promise.resolve()):this.audioContext.state==="running"?(this.isReady=!0,Promise.resolve()):new Promise(o=>{let e=()=>{if(this.destroyed){this.clearUnlockHandler(),o();return}this.audioContext.resume().then(()=>{this.audioContext.state==="running"&&(this.clearUnlockHandler(),this.isReady=!0,o())}).catch(t=>{pn("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:l=!1}=e??{},c,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")c=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),c=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),c=p}let d=new xc(this.audioContext,c,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(c instanceof AudioBufferSourceNode?(c.loop=l,l&&s!==void 0&&(c.loopStart=r,c.loopEnd=s)):c instanceof HTMLAudioElement&&(c.loop=l),u){let p=!1,h=()=>{p||(p=!0,u.releaseRef?.())};d.once("ended",h),d.once("stop",h)}return d}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<kc?"full":"stream"}catch(t){return pn("Failed to resolve load mode via HEAD request, falling back to 'stream'.",t),"stream"}}createStreamSource(o){let e=new Audio(o);return e.crossOrigin="anonymous",e}checkChannelLimit(){if(this.registeredChannels.size+1>=this.options.maxChannels)throw new Error(`Maximum number of channels (${this.options.maxChannels}) reached.`)}registerChannel(o){this.registeredChannels.add(o)}unregisterChannel(o){this.registeredChannels.delete(o)}setVolume(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.setVolume(o),this}getVolume(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getVolume()}mute(o){return this.ensureNotDestroyed(),this.ensureReady(),o===void 0?this.masterChannel.mute():this.masterChannel.mute(o),this}unmute(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.unmute(),this}isMuted(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.isMuted()}createChannel(o,e){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.createChannel(o,e)}getChannel(o){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannel(o)}getChannels(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getChannels()}async load(o){return this.ensureNotDestroyed(),this.ensureReady(),this.audioCache.load(o)}async play(o,e){this.ensureNotDestroyed(),this.ensureReady();let t=this.masterChannel.getTokens();for(let n of t)try{n.stop()}catch{}return this.masterChannel.play(o,e)}getTokens(){return this.ensureNotDestroyed(),this.ensureReady(),this.masterChannel.getTokens()}destroy(){this.destroyed||(this.destroyed=!0,this.clearUnlockHandler(),this.audioCache.clear(),this.masterChannel.remove(),this.registeredChannels.clear(),this.audioContext.close().catch(o=>{pn("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var de=class de{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new Aa({maxChannels:de.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=de.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,de.BusRampTimeConstant),r.setValueAtTime(s,a+de.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${tt.sound}" instead.`)),this.channels.get(tt.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=de.defaultFade(e)){let n=new S;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=de.clipRegionOf(e),a=await i.play(r,{volume:0,...de.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,s);let l=e.state.muted??!1;a.mute(l),e.state.muted=l,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(c=>{a.once("ended",()=>c())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t=de.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new E(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=await n.play(i,{volume:0,...de.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(s,r);let a=e.state.muted??!1;return s.mute(a),e.state.muted=a,this.state.set(e,{token:s,cachedAudio:i,originalVolume:t.end}),t.duration>0?s.fade(0,t.end,t.duration):s.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,s}catch(n){throw this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,n),n}}stop(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.token.stop(),this.state.delete(e),n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.token.stop(),this.state.delete(e),n.resolve()}),n}setVolume(e,t,n=0){let i=new S;if(!this.state.has(e))return i.resolve(),i;let r=this.state.get(e);return r.originalVolume=t,n===0?(r.token.setVolume(t),e.state.volume=t,i.resolve()):r.token.fade(r.token.getVolume(),t,n).finished.then(()=>{e.state.volume=t,i.resolve()}),i}mute(e,t=!0){let n=new S;return e.state.muted=t,this.state.has(e)?(this.state.get(e).token.mute(t),n.resolve(),n):(n.resolve(),n)}pause(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition=i.token.getCurrentTime(),i.token.pause(),e.state.paused=!0,n.resolve()):i.token.fade(i.token.getVolume(),0,t).finished.then(()=>{i.pausePosition=i.token.getCurrentTime(),i.token.pause(),i.token.setVolume(i.originalVolume),e.state.paused=!0,n.resolve()}),n}resume(e,t=0){let n=new S;if(!this.state.has(e))return n.resolve(),n;let i=this.state.get(e);return t===0?(i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),e.state.paused=!1,n.resolve()):(i.token.setVolume(0),i.pausePosition!==void 0&&i.token.seek(i.pausePosition),i.token.resume(),i.token.fade(0,i.originalVolume,t).finished.then(()=>{e.state.paused=!1,n.resolve()})),n}seek(e,t){if(!this.state.has(e))return S.resolve(void 0);let n=this.state.get(e),i=de.clampToRegion(t,de.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),S.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,l=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=l<i?l:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,S.resolve(void 0)):S.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime()}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...de.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(de.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let l=e.state.muted??!1;a.mute(l),e.state.muted=l,e.state.paused?a.pause():t.isPlaying||a.stop()}catch(n){this.gameState.logger.error("AudioManager",`Failed to restore sound (src: "${e.config.src}")`,n)}})}isManaged(e){return this.state.has(e)}preload(e){return this.ready.then(()=>this.sound.load(e.config.src)).then(()=>{}).catch(t=>{this.gameState.logger.weakWarn("AudioManager",`Failed to preload sound (src: "${e.config.src}")`,t)})}reset(){this.state.forEach(e=>{e.token.stop()}),this.state.clear(),this.globalVolume=1,this.isReady&&this.sound.setVolume(1),this.isReady&&this.busTree&&this.busTree.getNodes().forEach(e=>{this.applyBusVolume(this.channels.get(e.id),this.mixer.getEffectiveVolume(e.id),!1)})}setBusVolume(e,t){this.mixer.setVolume(e,t)}getBusVolume(e){return this.mixer.getVolume(e)}getBuses(){return this.mixer.list()}setGroupVolume(e,t){this.setBusVolume(e,t)}getGroupVolume(e){return this.getBusVolume(e)}setGlobalVolume(e){this.globalVolume=e,this.isReady&&this.sound.setVolume(e)}getGlobalVolume(){return this.globalVolume}destroy(){this.reset(),this.busSubscription?.cancel(),this.busSubscription=null,this.sound.destroy()}};de.MaxChannels=1024,de.BusRampTimeConstant=.02,de.BusRampSettle=de.BusRampTimeConstant*5;var so=de;import*as Nc from"html-to-image";var ao=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new Y}addNotification(e){this.notifications.push(e),this.flush()}removeNotification(e){this.notifications=this.notifications.filter(t=>t!==e),this.flush()}clearNotifications(){this.notifications=[],this.flush()}consume(e){let t=new S,n=new ke(t);return t.registerSkipController(new V(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};function lo(o,e,t){let n={},i={};Object.keys(e).forEach(s=>{let a=s;a==="style"&&e.style?Object.assign(n,e.style):e[a]!==void 0&&a!=="key"&&(i[a]=e[a])}),Object.keys(n).length>0&&Object.assign(o.style,n);let r=t?t(i):i;for(let[s,a]of Object.entries(r))o.getAttribute(s)!==a&&o.setAttribute(s,a)}var Dc=4e3,wa={zIndex:0,visibility:"visible"},Lc={...wa,zIndex:1},Ca={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function co(){return{zIndex:"auto",visibility:"visible",opacity:1,transform:"none",translate:"none",filter:"none",clipPath:"none",maskImage:"none",WebkitMaskImage:"none",maskSize:"auto",WebkitMaskSize:"auto",maskRepeat:"repeat",WebkitMaskRepeat:"repeat"}}function Rc(){return{...co(),visibility:"hidden"}}var uo=class{constructor(e){this.gameState=e;this.sceneElements=new Map;this.overlayHost=null;this.running=null}registerScene(e,t){t?this.sceneElements.set(e.getId(),t):this.sceneElements.delete(e.getId())}registerOverlayHost(e){this.overlayHost=e}reset(){this.running?.controller.complete(),this.running=null}skip(){this.running&&(this.gameState.logger.debug("StageTransition","Transition skipped"),this.running.controller.complete())}apply(e,t,n){this.running?.controller.complete();let i=e;typeof i._setDetached=="function"&&i._setDetached(!0);let r=e.createTask(this.gameState),s=e.requestAnimations(r.animations),a=new S().registerSkipController(new V(s.cancel)),l=new ke(a),c=[],u=r.resolve.map(h=>{if(typeof h=="function"){let m=this.createOverlay();return c.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(h.key==="target"?t.to:t.from).getId(),role:h.key}}),d={task:r,controller:s,roles:t,targets:u,overlays:c,cancelLoadGate:()=>{},stale:!1};this.running=d,s.onUpdate(h=>this.applyFrame(d,h)),s.onComplete(()=>{this.settle(d,[[t.to,co()],[t.from,Rc()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(d,[[t.from,co()],[t.to,co()]]),l.abort()}),this.applyFrame(d,r.animations.map(h=>h.start));let p=this.waitForSceneReady(t.to);return d.cancelLoadGate=p.cancel,p.promise.then(()=>{d.stale||s.start()}),l}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?r.element:this.sceneElements.get(r.sceneId)??null;if(!s)return;let a=typeof n=="function"?n:n.resolver,l=r.kind==="overlay"?Ca:r.role==="target"?Lc:wa,c=K({style:l},a(...t));lo(s,c,Ic)})}settle(e,t){e.stale=!0,e.cancelLoadGate(),e.overlays.forEach(n=>n.remove()),e.overlays.length=0,t.forEach(([n,i])=>{let r=this.sceneElements.get(n.getId());r&&Object.assign(r.style,i)}),this.running===e&&(this.running=null)}createOverlay(){let e=document.createElement("div");return e.setAttribute("data-element-type","stage-transition-overlay"),Object.assign(e.style,Ca),this.overlayHost?.appendChild(e),e}waitForSceneReady(e){let t=this.sceneElements.get(e.getId());if(!t)return{promise:Promise.resolve(),cancel:()=>{}};let n=()=>{},i=new Promise(s=>{n=this.gameState.schedule(()=>{this.gameState.logger.weakWarn("StageTransition","Timed out waiting for the incoming scene to load"),s()},Dc)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(Mc)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},xa=["src","width","height"];function Ic(o){if(!xa.some(t=>t in o))return o;let e={...o};return xa.forEach(t=>delete e[t]),e}function Mc(o){return o.getAttribute("src")?typeof o.decode=="function"?o.decode().then(()=>{},()=>{}):o.complete?Promise.resolve():new Promise(e=>{let t=()=>{o.removeEventListener("load",t),o.removeEventListener("error",t),e()};o.addEventListener("load",t),o.addEventListener("error",t)}):Promise.resolve()}var po=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=$i(6),{action:r,timeline:s,stackModel:a}=e,l=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:l,stackModel:a}),this.history.length>this.maxHistorySize){let c=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(c))}return{id:i}}has(e){return this.history.some(t=>t.id===e)}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var mo=class o{constructor(e){this.history=[];this.cursor=-1;this.resumingAtCursor=!1;this.actionHistoryMgr=e,this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){let t=this.history[this.cursor];if(this.resumingAtCursor&&t&&t.action===e.action)return this.history[this.cursor]={...e,token:t.token},this.resumingAtCursor=!1,this;this.resumingAtCursor=!1;let n=this.history[this.cursor+1];return n&&n.action===e.action?this.history[this.cursor+1]={...e,token:n.token}:(this.history.length=this.cursor+1,this.history.push(e)),this.cursor++,this}getHistory(){return this.history.slice(0,this.cursor+1)}getFuture(){return this.history.slice(this.cursor+1)}getCursor(){return this.cursor}getAt(e){return this.history[e]??null}indexOfToken(e){return this.history.findIndex(t=>t.token===e)}setCursor(e){return this.cursor=Math.max(-1,Math.min(e,this.history.length-1)),this.resumingAtCursor=!0,this}canUndo(){return this.cursor>0}canRedo(){return this.cursor<this.history.length-1}getByToken(e){return this.history.find(t=>t.token===e)??null}serialize(){return this.history.slice(0,this.cursor+1).map(e=>o.toSerialized(e))}serializeAll(){return this.history.map(e=>o.toSerialized(e))}load(e,t){this.history=[];for(let n of e){let i=n.actionId!=null?t.get(n.actionId):void 0;i&&this.history.push({token:n.token??$i(6),action:i,element:n.element,isPending:n.isPending,snapshot:n.snapshot})}this.cursor=this.history.length-1}reset(){this.history=[],this.cursor=-1,this.resumingAtCursor=!1}static toSerialized(e){return{token:e.token,actionId:e.action.getId(),element:e.element,isPending:e.isPending,snapshot:e.snapshot??null}}updateByToken(e,t){let n=this.history.find(i=>i.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(i=>i.id)),n=this.history.slice(0,this.cursor+1).filter(i=>t.has(i.token)).length;this.history=this.history.filter(i=>!t.has(i.token)),this.cursor=Math.max(-1,Math.min(this.cursor-n,this.history.length-1))}};var bn=class extends ${executeAction(e,t){let n=new S().registerSkipController(new V(()=>{l.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,l=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.reset()},e.gameHistory.updateByToken(c,p=>{p&&p.element.type==="menu"&&(p.element.selected=u.evaluated,p.isPending=!1)})}),{id:c}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{l.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:c,action:this,element:{type:"menu",text:l.prompt,selected:null},isPending:!0,snapshot:e.getLiveGame().captureGameState()}),n}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(l=>l.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};bn.ActionTypes=zs;var An=class An extends ce{constructor(t,n={}){super();this.choices=[];this.prompt=me.isSentence(t)?t:t===null?null:new me(t),this.config=K(An.defaultConfig,n)}static prompt(t,n={}){return new An(t!==void 0?t:null,n)}static choose(t,n){return new An(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return me.isSentence(t)&&n?i.choices.push({prompt:me.toSentence(t),action:this.narrativeToActions(n),config:{}}):(te.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:me.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:me.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?j.from(t.config.disabled):void 0,hidden:t.config?.hidden?j.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),i}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new He("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.hideIf` before `menu.choose`");return n.config.hidden=j.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new He("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.disableIf` before `menu.choose`");return n.config.disabled=j.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:j.not(j.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:j.not(j.from(t))}})}fromChained(t){return[new bn(this.chain(),bn.ActionTypes.action,new k().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?_t.say(n).getActions():We.toActions([n])))}constructNodes(t,n,i){for(let r=0;r<t.length;r++){let s=t[r].contentNode,a=t[r+1]?.contentNode;a&&s.setChild(a),r===this.choices.length-1&&n&&s.setChild(n),r===0&&i&&i.setChild(s)}return t}constructChoices(){return this.choices.map(t=>({action:this.constructNodes(t.action),prompt:t.prompt,config:t.config??{}}))}};An.defaultConfig={},An.targetAction=bn;var vr=An;var vt={shutter:0,shutterColor:"#000",vignette:0,vignetteColor:"#000",vignetteInner:"44%",vignetteOuter:"78%"};function Sr(o){return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(1,o))}function ci(o,e){return typeof o=="string"&&o.length>0?o:e}function ka(o){let e=Sr(o.shutter);return{backgroundColor:ci(o.shutterColor,vt.shutterColor),clipPath:`inset(0 0 ${100-50*e}% 0)`}}function Pa(o){let e=Sr(o.shutter);return{backgroundColor:ci(o.shutterColor,vt.shutterColor),clipPath:`inset(${100-50*e}% 0 0 0)`}}function Ea(o){let e=ci(o.vignetteInner,vt.vignetteInner),t=ci(o.vignetteOuter,vt.vignetteOuter),n=`radial-gradient(circle at center, transparent ${e}, black ${t})`;return{backgroundColor:ci(o.vignetteColor,vt.vignetteColor),opacity:Sr(o.vignette),maskImage:n,WebkitMaskImage:n,maskSize:"100% 100%",WebkitMaskSize:"100% 100%",maskPosition:"center",WebkitMaskPosition:"center",maskRepeat:"no-repeat",WebkitMaskRepeat:"no-repeat",maskMode:"alpha",WebkitMaskMode:"alpha"}}var ut=class ut extends ze{static get DefaultUserConfig(){return ut._defaultUserConfig??(ut._defaultUserConfig=new B({...ee.DefaultTransformState.getDefaultConfig(),opacity:1,...vt}))}constructor(e={}){super();let t=ut.DefaultUserConfig.create(e),n=ut.DefaultConfig.create();this.userConfig=t,this.config=n.get(),this.transformState=this.getInitialTransformState()}pan(e,t,n){return this.pos(e,t,n)}darken(e,t,n){let i=Math.max(0,Math.min(1,e));return this.filter(`brightness(${1-i})`,{duration:t,ease:n})}shutter(e,t,n){return this.lens({shutter:ut.clampLens(e)},{duration:t,ease:n})}vignette(e,t,n){return this.lens({vignette:ut.clampLens(e)},{duration:t,ease:n})}lens(e,t){return this.transform(new J(e,t))}resetCamera(e,t){return this.transform(new J([{props:{filter:"none"},options:{duration:0}},{props:{position:new at("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,shutter:vt.shutter,vignette:vt.vignette},options:{duration:e,ease:t}},{props:{shutterColor:vt.shutterColor,vignetteColor:vt.vignetteColor,vignetteInner:vt.vignetteInner,vignetteOuter:vt.vignetteOuter},options:{duration:0}}]))}static clampLens(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}bringToFront(){throw new E(`A camera cannot be brought to front. It is not an element inside a layer, it is what the layers are viewed through, so it has nothing to be in front of \u2014 waiting for it to be added to the stage will not help. Use a camera transform such as Camera.zoom or Camera.pan to change what is in view. (camera: ${this.config.name})`)}reset(){return super.reset(),this.transformState.resetTo(this.getInitialTransformState().get()),this}toData(){return{transformState:this.transformState.serialize(),loop:this._serializeLoop()}}fromData(e){return this.transformState.resetTo(ee.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}copy(){return new ut(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(ut.DefaultUserConfig.keys());return new ee(ut.DefaultUserConfig.create(e.get()).get())}};ut._defaultUserConfig=null,ut.DefaultConfig=new B({name:"(camera)"});var ui=ut;var dn=class dn extends Gn{constructor(t,n={}){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.elementBaseline=null;this.name=t;let{camera:i,...r}=n;this.config=K(dn.defaultConfig,r),this._camera=i??new ui}static empty(){return new dn("empty").entry(new yt("empty"))}get camera(){return this._camera}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let i=new Hn(t,n);return this.registerPersistent(i),i}registerService(t,n){return this.services.set(t,n),this}getService(t){let n=this.services.get(t);if(!n)throw new He(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return ea(this.stringify(t))}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,i)=>{if(!n.serialize||typeof n.serialize!="function")return;let r=n.serialize();if(r!==null){{if(r instanceof Promise)throw new ie(`Service ${i} serialize method should not return a promise`);if(!rr(r))throw new ie(`Service ${i} serialize method should return a pure object.
|
|
28
28
|
A pure object should:
|
|
29
29
|
1. be an object literal
|
|
30
30
|
2. not have any prototype
|
|
31
31
|
3. no circular reference
|
|
32
32
|
4. sub objects should also be pure objects or serializable data
|
|
33
33
|
Return null if nothing needs to be saved. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description
|
|
34
|
-
Returned value ${r} violates the above rules`)}t[i]=r}}),t}deserializeServices(t){this.services.forEach((n,i)=>{!n.deserialize||typeof n.deserialize!="function"||t[i]&&n.deserialize(t[i])})}getScene(t,n=!1,i){if(
|
|
35
|
-
Use video.show() to add the video to the game`);let i=this.callee,r=new S,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new
|
|
36
|
-
Use vfx.show() to add the vfx to the game`);let i=this.callee,r=new S,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Vfx Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new F(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VfxAction")}};Jt.ActionTypes=qt;var co=Jt;var On=class On extends ce{constructor(e){super();let t=On.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ne("Vfx must have a src")}preload(){return this.chain(this.createAction(qt.preload,[]))}show(e){return this.chain(this.createAction(qt.show,[e]))}hide(e){return this.chain(this.createAction(qt.hide,[e]))}pause(){return this.chain(this.createAction(qt.pause,[]))}resume(){return this.chain(this.createAction(qt.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(qt.setRate,[e]))}toData(){return{state:{display:this.state.display,paused:this.state.paused}}}fromData(e){let{state:t}=e;return this.state={display:t.display,paused:t.paused},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return On.DefaultVfxState.create().get()}createAction(e,t){return new co(this.chain(),e,w.create(t))}};On.DefaultVfxConfig=new K({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),On.DefaultVfxState=new K({display:!1,paused:!1});var hr=On;var ue=class ue{constructor(e,t){this.state={sounds:[],videos:[],vfx:[],srcManagers:[],elements:[]};this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1};this._suppressNextNvlTyping=!1;this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new $n;this.htmlToImage=Tc;this.pageRouter=null;this.stageClickBuffer=null;this.advanceSuspensions=new Set;this.nvlAdvanceWaiters=new Map;this.advDialogState=null;this._fastForwarding=!1;this.stage=t,this.game=e,this.events=new X,this.logger=new Zi(e,"NarraLeaf-React"),this.audioManager=new _i(this),this.guard=new $i(e.config.app.guard).observe(this),this.timelines=new ji(this.guard),this.notificationMgr=new eo(this,[]),this.idManager=new Ii,this.actionHistory=new oo(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new ro(this.actionHistory),this.stageTransition=new io(this),this.events.on(ue.EventTypes["event:state.player.skip"],()=>{this.game.config.allowSkipSceneTransition&&this.stageTransition.skip()})}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}addVfx(e){return this.state.vfx.push(e),this}removeVfx(e){let t=this.state.vfx.indexOf(e);return t===-1?(this.logger.weakWarn("Vfx not found when removing",e.getId()),this):(this.state.vfx.splice(t,1),this)}isVfxAdded(e){return this.state.vfx.includes(e)}getVfx(){return this.state.vfx}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let i of n.layers.values())if(i.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=ft.isScene(e)?e:e.entryScene;if(!t)throw new E("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(ue.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){return this.state.elements[this.state.elements.length-1]?.scene||null}getCurrentScene(){return this.state.elements[0]?.scene||null}isFastForwarding(){return this._fastForwarding}setFastForwarding(e){this._fastForwarding=e}hasActiveMenu(){let e=this.getLastScene();return e?(this.findElementByScene(e)?.menus.length??0)>0:!1}findCurrentPortraitForCharacter(e){let t=(e.config.portraits||[]).map(lr);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let l=s[a];for(let c=l.length-1;c>=0;c--){let u=l[c],d=r.get(u);if(d&&this.isDisplayableVisible(u))return d}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(we.getCtx({gameState:this}));this.game.getLiveGame().events.emit(Ht.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:te.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let l=r.indexOf(a);l!==-1&&r.splice(l,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let l=r.indexOf(a);l!==-1&&r.splice(l,1)},text:te.getText(s)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let i=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!i)throw this.sceneNotFound();let r=e.prompt?.evaluate(we.getCtx({gameState:this}))||null,s=this.createWaitableAction({...e,words:r},a=>{i.splice(i.indexOf(s),1),t&&t(a),this.game.getLiveGame().events.emit(Ht.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return i.push(s),{cancel:()=>{let a=i.indexOf(s);a!==-1&&i.splice(a,1)},prompt:r?te.getText(r):null}}enterNvlMode(e){let t=this.idManager.generateId();return this.nvlState={active:!0,visible:!0,sessionId:t,dialogs:[],options:e||null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.events.emit(ue.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!0,e?.showTransition),this.emitNvlStateChange(),this}exitNvlMode(e){let t=e?.hideTransition||this.nvlState.options?.hideTransition;return this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(ue.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],e),this.emitNvlStateChange(),this}removeNvlDialog(e){let t=this.nvlState.dialogs.findIndex(r=>r.id===e);if(t===-1)return this;let n=[...this.nvlState.dialogs],[i]=n.splice(t,1);return this.nvlState.dialogs=n,this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],i),this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState()),this.emitNvlStateChange(),this}getNvlDialogs(){return this.nvlState.dialogs}isNvlMode(){return this.nvlState.active}getNvlState(){return this.nvlState}createNvlSnapshot(){return{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,dialogs:this.nvlState.dialogs.map(e=>({...e})),options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,isTyping:this.nvlState.isTyping}}createPresentationSnapshot(){return{scenes:this.state.elements.map(({scene:e})=>ae.createSceneSnapshot(e,this)),nvlState:this.createNvlSnapshot()}}restoreNvlSnapshot(e){let t=e.activeDialogId&&e.dialogs.some(n=>n.id===e.activeDialogId)?e.activeDialogId:null;return this.nvlState={active:e.active,visible:e.visible,sessionId:e.sessionId,dialogs:e.dialogs.map(n=>({...n})),options:e.options?{...e.options}:null,activeDialogId:t,phase:t?"awaitAdvance":"idle",pendingAdvance:!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active?(this.events.emit(ue.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(ue.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{ae.restoreSceneSnapshot(t,this)}),this.restoreNvlSnapshot(e.nvlState),this}clearNvlDialogs(){return this.nvlState.dialogs=[],this.emitNvlStateChange(),this}setNvlActiveDialog(e,t){return this.nvlState.activeDialogId=e,this.nvlState.phase=e?t?"typing":"awaitAdvance":"idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),this}setNvlTyping(e){return this.nvlState.phase=e?"typing":this.nvlState.activeDialogId?"awaitAdvance":"idle",this.syncNvlDerivedState(),this.emitNvlStateChange(),this}getNvlDialog(e){return this.nvlState.dialogs.find(t=>t.id===e)||null}getActiveNvlDialogForAction(e){if(!this.nvlState.activeDialogId)return null;let t=this.getNvlDialog(this.nvlState.activeDialogId);return!t||t.actionId!==e?null:t}getLatestNvlDialogForAction(e){for(let t=this.nvlState.dialogs.length-1;t>=0;t--){let n=this.nvlState.dialogs[t];if(n.actionId===e)return n}return null}allocateNvlDialogId(e){let t=-1;for(let n of this.nvlState.dialogs){if(n.actionId!==e)continue;let i=n.id.startsWith(`${e}:`)?Number.parseInt(n.id.slice(e.length+1),10):Number.NaN;Number.isNaN(i)||(t=Math.max(t,i))}return`${e}:${t+1}`}ensureNvlDialog(e){let t=this.getNvlDialog(e.id);return t?(t.character=e.character,t.sentence=e.sentence,t.text=e.text,this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],t),this.emitNvlStateChange(),{created:!1,entry:t}):(this.appendNvlDialog(e),{created:!0,entry:e})}activateNvlDialog(e,t="typing",n=!0){return n&&this.nvlState.activeDialogId===e&&this.nvlState.phase!=="idle"||(this.nvlState.activeDialogId=e,this.nvlState.phase=t,this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}waitForNvlAdvance(e,t){return this.nvlAdvanceWaiters.set(e,t),{cancel:()=>{this.nvlAdvanceWaiters.get(e)===t&&this.nvlAdvanceWaiters.delete(e)}}}requestNvlAdvance(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?"ignore":this.nvlState.phase==="typing"?"typing":this.nvlState.phase==="awaitAdvance"?(this.resolveNvlAdvance(e),"advance"):"ignore"}requestNvlSkip(e){return this.requestNvlAdvance(e)}completeNvlTyping(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?!1:(this.nvlState.phase="awaitAdvance",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.events.emit(ue.EventTypes["event:state.nvl.dialogComplete"],e),this.emitNvlStateChange(),!0)}settleNvlDialog(e){return this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}suppressNextNvlTyping(){return this._suppressNextNvlTyping=!0,this}consumeNvlTypingSuppression(){return this._suppressNextNvlTyping?(this._suppressNextNvlTyping=!1,!0):!1}beginAdvDialog(e,t){return this.advDialogState={dialogId:e,actionId:t,ended:!1},this.events.emit(ue.EventTypes["event:state.dialog.change"]),this}completeAdvDialogTyping(e){return!e||!this.advDialogState||this.advDialogState.dialogId!==e?this:(this.advDialogState.ended||(this.advDialogState.ended=!0,this.events.emit(ue.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(ue.EventTypes["event:state.dialog.change"])),this}getAdvDialogState(){return this.advDialogState}recordStageClick(){return this.stageClickBuffer={timestamp:Date.now()},this}suspendAdvance(){let e=Symbol("advance-suspension");return this.advanceSuspensions.add(e),()=>{this.advanceSuspensions.delete(e)}}isAdvanceSuspended(){return this.advanceSuspensions.size>0}consumeStageClick(e=200){if(!this.stageClickBuffer)return!1;let{timestamp:t}=this.stageClickBuffer,n=Date.now()-t;return this.stageClickBuffer=null,n>=0&&n<=e}createDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i);if(!r)throw this.sceneNotFound();let s=r.layers.get(n||i.config.defaultDisplayableLayer);if(!s)throw this.layerNotFound();return s.push(e),this}disposeDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i)?.layers.get(n||i.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();let s=r.indexOf(e);if(s===-1)throw new E(`Displayables not found when disposing. (disposing: ${e.getId()})`);return r.splice(s,1),this}forceReset(){[...this.state.elements].forEach(({scene:t})=>{this.offSrcManager(t.srcManager),this.removeScene(t),t.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.state.vfx=[],this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return ba.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new E("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=ke.proxy(S.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof Qe&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(Z.immediate({}),()=>{});t.attachChild(s),r.updateStyleSync(),"flush"in r&&r.flush()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new Fe("State already mounted");if(!e)throw new Fe("Invalid state key");return this.exposedState.set(e,t),this.events.emit(ue.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new E("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let i=this.events.on(ue.EventTypes["event.state.onExpose"],(r,s)=>{r===e&&(t(s),i.cancel())});return i}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(i=>i.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()]),vfx:this.state.vfx.map(e=>[e.getId(),e.toData()]),nvlState:{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,dialogIds:this.nvlState.dialogs.map(e=>e.id),dialogs:this.nvlState.dialogs.map(e=>({id:e.id,actionId:e.actionId,text:e.text,characterId:e.character?e.character.getId():null}))}}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:i,audio:r,videos:s}=e;if(i.forEach(({sceneId:a,elements:l})=>{this.logger.debug("Loading scene: "+a);let c=t.get(a);if(!c)throw new E("Scene not found, id: "+a+`
|
|
34
|
+
Returned value ${r} violates the above rules`)}t[i]=r}}),t}deserializeServices(t){this.services.forEach((n,i)=>{!n.deserialize||typeof n.deserialize!="function"||t[i]&&n.deserialize(t[i])})}getScene(t,n=!1,i){if(yt.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||ie,[`Scene with name ${t} not found`]);return r}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this.captureElementBaseline(),this}captureElementBaseline(){let t=new Map;this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).forEach(n=>{let i=n.toData();i&&t.set(n.getId(),JSON.stringify(i))}),this.elementBaseline=t}getAllElementStates(){let t=this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]),n=this.elementBaseline,i=[];for(let r of t){if(n&&!r.isDirty())continue;let s=r.toData();s&&(n&&JSON.stringify(s)===n.get(r.getId())||i.push({id:r.getId(),data:s}))}return i}findUnmarkedElements(){let t=this.elementBaseline;return t?this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).filter(n=>{if(n.isDirty())return!1;let i=n.toData();return!!i&&JSON.stringify(i)!==t.get(n.getId())}):[]}constructSceneRoots(t){let n=new Set,i=[],r=0;for(t.constructSceneRoot(this),i.push(t.getSceneRoot());i.length;){if(r++,r>dn.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${dn.MAX_DEPTH})`);let s=i.shift();if(yt.isScene(s.callee)){if(n.has(s.callee))continue;s.callee.isSceneRootConstructed()||s.callee.constructSceneRoot(this),n.add(s.callee)}let a=s.getFutureActions(this,{allowFutureScene:!0});i.push(...a)}return this}initPersistent(t){return this.persistent.forEach(n=>{n.init(t)}),this}getInversionConfig(){let{origin:t}=this.config;return{invertY:t==="bottom left"||t==="bottom right",invertX:t==="bottom right"||t==="top right"}}runStaticCheck(t){return new fo(t).run(this)}};dn.defaultConfig={origin:"bottom left"},dn.MAX_DEPTH=32767;var pi=dn;var ho=class extends ${executeAction(e,t){let[n,i]=this.contentNode.getContent(),r=this.callee.triggerAction(we.getCtx({gameState:e}),n,i);return S.isAwaitable(r)?S.forward(r,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var Tr=class extends ce{constructor(){super(...arguments);this._handlers={}}on(t,n){return this._registerActionHandler(t,n),this}trigger(t,...n){let i=this.chain();return i.chain(this._createAction(i,t,n))}triggerAction(t,n,i){let r=this._handlers[n];if(!r){t.gameState.logger.warn(`(in User-Defined Service) Trying to trigger action ${n} before it's registered, please use "service.on" to register the action`);return}if(Js(r)){let s=[],a=new S().registerSkipController(new V(()=>{for(let c of s)c?.()}));return r({...t,onAbort:c=>{s.push(c)}},...i).then(()=>a.resolve()),a}r({...t,onAbort:()=>{}},...i)}_registerActionHandler(t,n){this._handlers[t]=n}_createAction(t,n,i){return new ho(t,"service:action",new k().setContent([n,i]))}},br=class extends Tr{},di=class extends br{};var Dt=class Dt extends ${executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(Dt,"video:preload"))return e.isVideoAdded(i)?S.resolve(super.executeAction(e,t)):(e.addVideo(i),e.stage.update(),e.actionHistory.push(r,()=>{e.isVideoAdded(i)&&(e.removeVideo(i),e.stage.update())}),S.resolve(super.executeAction(e,t)));if(n.is(Dt,"video:play"))return this.changeStateAsync(e,s=>s.play(),t);if(n.is(Dt,"video:pause"))return this.changeState(e,s=>s.pause(),t);if(n.is(Dt,"video:stop"))return this.changeState(e,s=>s.stop(),t);if(n.is(Dt,"video:seek"))return this.changeState(e,s=>s.seek(n.contentNode.getContent()[0]),t);if(n.is(Dt,"video:show")){let s=i.state.display;return e.isVideoAdded(i)||(e.addVideo(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,a=>{i.state.display=a},[s]),this.changeState(e,a=>a.show(),t)}else if(n.is(Dt,"video:hide")){let s=i.state.display;return this.changeState(e,a=>{i.state.display=!1,e.actionHistory.push(r,l=>{i.state.display=l},[s]),a.hide(),e.removeVideo(i),e.stage.update()},t)}else if(n.is(Dt,"video:resume"))return this.changeState(e,s=>s.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new E(`Video is being used before it is added to the game
|
|
35
|
+
Use video.show() to add the video to the game`);let i=this.callee,r=new S,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new V(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};Dt.ActionTypes=wt;var go=Dt;var Un=class Un extends ce{constructor(e){super();let t=Un.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ie("Video must have a src")}preload(){return this.chain(this.createAction(wt.preload,[]))}show(){return this.chain(this.createAction(wt.show,[]))}hide(){return this.chain(this.createAction(wt.hide,[]))}play(){return this.chain(this.createAction(wt.play,[]))}pause(){return this.chain(this.createAction(wt.pause,[]))}resume(){return this.chain(this.createAction(wt.resume,[]))}stop(){return this.chain(this.createAction(wt.stop,[]))}seek(e){return this.chain(this.createAction(wt.seek,[e]))}toData(){return{state:{display:this.state.display}}}fromData(e){let{state:t}=e;return this.state={display:t.display},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return Un.DefaultVideoState.create().get()}createAction(e,t){return new go(this.chain(),e,k.create(t))}};Un.DefaultVideoConfig=new B({src:"",muted:!1}),Un.DefaultVideoState=new B({display:!1});var Ar=Un;var Zt=class Zt extends ${executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(Zt,"vfx:preload"))return e.isVfxAdded(i)?S.resolve(super.executeAction(e,t)):(e.addVfx(i),e.stage.update(),e.actionHistory.push(r,()=>{e.isVfxAdded(i)&&(e.removeVfx(i),e.stage.update())}),S.resolve(super.executeAction(e,t)));if(n.is(Zt,"vfx:show")){let[s]=n.contentNode.getContent(),a=i.state.display;return e.isVfxAdded(i)||(e.addVfx(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,l=>{i.state.display=l},[a]),this.changeStateAsync(e,l=>l.show(s),t)}else if(n.is(Zt,"vfx:hide")){if(!e.isVfxAdded(i)||!i.state.display)return e.logger.weakWarn("NarraLeaf-React: Vfx","Hiding a Vfx that is not shown, ignored. (src: "+i.config.src+")"),S.resolve(super.executeAction(e,t));let[s]=n.contentNode.getContent(),a=i.state.display;return this.changeStateAsync(e,async l=>{await l.hide(s),i.state.display=!1,e.actionHistory.push(r,c=>{i.state.display=c},[a])},t)}else{if(n.is(Zt,"vfx:pause"))return this.changeState(e,s=>{i.state.paused=!0,s.pause()},t);if(n.is(Zt,"vfx:resume"))return this.changeState(e,s=>{i.state.paused=!1,s.resume()},t);if(n.is(Zt,"vfx:setRate"))return this.changeState(e,s=>s.setRate(n.contentNode.getContent()[0]),t)}throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVfxAdded(this.callee))throw new E(`Vfx is being used before it is added to the game
|
|
36
|
+
Use vfx.show() to add the vfx to the game`);let i=this.callee,r=new S,s=e.getExposedStateAsync(i,async a=>{e.logger.debug("Vfx Component state exposed",a),await t(a),r.resolve(super.executeAction(e,n))});return r.registerSkipController(new V(s.cancel)),r}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VfxAction")}};Zt.ActionTypes=Xt;var yo=Zt;var Wn=class Wn extends ce{constructor(e){super();let t=Wn.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ie("Vfx must have a src")}preload(){return this.chain(this.createAction(Xt.preload,[]))}show(e){return this.chain(this.createAction(Xt.show,[e]))}hide(e){return this.chain(this.createAction(Xt.hide,[e]))}pause(){return this.chain(this.createAction(Xt.pause,[]))}resume(){return this.chain(this.createAction(Xt.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(Xt.setRate,[e]))}toData(){return{state:{display:this.state.display,paused:this.state.paused}}}fromData(e){let{state:t}=e;return this.state={display:t.display,paused:t.paused},this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return Wn.DefaultVfxState.create().get()}createAction(e,t){return new yo(this.chain(),e,k.create(t))}};Wn.DefaultVfxConfig=new B({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),Wn.DefaultVfxState=new B({display:!1,paused:!1});var Cr=Wn;var ue=class ue{constructor(e,t){this.state={sounds:[],videos:[],vfx:[],srcManagers:[],elements:[]};this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1};this._suppressNextNvlTyping=!1;this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new Qn;this.htmlToImage=Nc;this.pageRouter=null;this.stageClickBuffer=null;this.advanceSuspensions=new Set;this.nvlAdvanceWaiters=new Map;this.advDialogState=null;this._fastForwarding=!1;this.stage=t,this.game=e,this.events=new Y,this.logger=new ro(e,"NarraLeaf-React"),this.audioManager=new so(this),this.guard=new _i(e.config.app.guard).observe(this),this.timelines=new Zi(this.guard),this.notificationMgr=new ao(this,[]),this.idManager=new Ui,this.actionHistory=new po(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new mo(this.actionHistory),this.stageTransition=new uo(this),this.events.on(ue.EventTypes["event:state.player.skip"],()=>{this.game.config.allowSkipSceneTransition&&this.stageTransition.skip()})}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}addVfx(e){return this.state.vfx.push(e),this}removeVfx(e){let t=this.state.vfx.indexOf(e);return t===-1?(this.logger.weakWarn("Vfx not found when removing",e.getId()),this):(this.state.vfx.splice(t,1),this)}isVfxAdded(e){return this.state.vfx.includes(e)}getVfx(){return this.state.vfx}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let i of n.layers.values())if(i.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=yt.isScene(e)?e:e.entryScene;if(!t)throw new E("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(ue.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){return this.state.elements[this.state.elements.length-1]?.scene||null}getCurrentScene(){return this.state.elements[0]?.scene||null}isFastForwarding(){return this._fastForwarding}setFastForwarding(e){this._fastForwarding=e}hasActiveMenu(){let e=this.getLastScene();return e?(this.findElementByScene(e)?.menus.length??0)>0:!1}findCurrentPortraitForCharacter(e){let t=(e.config.portraits||[]).map(gr);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let l=s[a];for(let c=l.length-1;c>=0;c--){let u=l[c],d=r.get(u);if(d&&this.isDisplayableVisible(u))return d}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(we.getCtx({gameState:this}));this.game.getLiveGame().events.emit(Ot.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:te.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let l=r.indexOf(a);l!==-1&&r.splice(l,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let l=r.indexOf(a);l!==-1&&r.splice(l,1)},text:te.getText(s)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let i=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!i)throw this.sceneNotFound();let r=e.prompt?.evaluate(we.getCtx({gameState:this}))||null,s=this.createWaitableAction({...e,words:r},a=>{i.splice(i.indexOf(s),1),t&&t(a),this.game.getLiveGame().events.emit(Ot.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return i.push(s),{cancel:()=>{let a=i.indexOf(s);a!==-1&&i.splice(a,1)},prompt:r?te.getText(r):null}}enterNvlMode(e){let t=this.idManager.generateId();return this.nvlState={active:!0,visible:!0,sessionId:t,dialogs:[],options:e||null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.events.emit(ue.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!0,e?.showTransition),this.emitNvlStateChange(),this}exitNvlMode(e){let t=e?.hideTransition||this.nvlState.options?.hideTransition;return this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(ue.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],e),this.emitNvlStateChange(),this}removeNvlDialog(e){let t=this.nvlState.dialogs.findIndex(r=>r.id===e);if(t===-1)return this;let n=[...this.nvlState.dialogs],[i]=n.splice(t,1);return this.nvlState.dialogs=n,this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],i),this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState()),this.emitNvlStateChange(),this}getNvlDialogs(){return this.nvlState.dialogs}isNvlMode(){return this.nvlState.active}getNvlState(){return this.nvlState}createNvlSnapshot(){return{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,dialogs:this.nvlState.dialogs.map(e=>({...e})),options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,isTyping:this.nvlState.isTyping}}createPresentationSnapshot(){return{scenes:this.state.elements.map(({scene:e})=>ae.createSceneSnapshot(e,this)),nvlState:this.createNvlSnapshot()}}restoreNvlSnapshot(e){let t=e.activeDialogId&&e.dialogs.some(n=>n.id===e.activeDialogId)?e.activeDialogId:null;return this.nvlState={active:e.active,visible:e.visible,sessionId:e.sessionId,dialogs:e.dialogs.map(n=>({...n})),options:e.options?{...e.options}:null,activeDialogId:t,phase:t?"awaitAdvance":"idle",pendingAdvance:!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active?(this.events.emit(ue.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(ue.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{ae.restoreSceneSnapshot(t,this)}),this.restoreNvlSnapshot(e.nvlState),this.rebindLoops(),this}rebindLoops(){let[e,t]=this.getLiveGame().constructMaps();return t.forEach(n=>{n instanceof ze&&n._rebindLoop(e)}),this}clearNvlDialogs(){return this.nvlState.dialogs=[],this.emitNvlStateChange(),this}setNvlActiveDialog(e,t){return this.nvlState.activeDialogId=e,this.nvlState.phase=e?t?"typing":"awaitAdvance":"idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),this}setNvlTyping(e){return this.nvlState.phase=e?"typing":this.nvlState.activeDialogId?"awaitAdvance":"idle",this.syncNvlDerivedState(),this.emitNvlStateChange(),this}getNvlDialog(e){return this.nvlState.dialogs.find(t=>t.id===e)||null}getActiveNvlDialogForAction(e){if(!this.nvlState.activeDialogId)return null;let t=this.getNvlDialog(this.nvlState.activeDialogId);return!t||t.actionId!==e?null:t}getLatestNvlDialogForAction(e){for(let t=this.nvlState.dialogs.length-1;t>=0;t--){let n=this.nvlState.dialogs[t];if(n.actionId===e)return n}return null}allocateNvlDialogId(e){let t=-1;for(let n of this.nvlState.dialogs){if(n.actionId!==e)continue;let i=n.id.startsWith(`${e}:`)?Number.parseInt(n.id.slice(e.length+1),10):Number.NaN;Number.isNaN(i)||(t=Math.max(t,i))}return`${e}:${t+1}`}ensureNvlDialog(e){let t=this.getNvlDialog(e.id);return t?(t.character=e.character,t.sentence=e.sentence,t.text=e.text,this.events.emit(ue.EventTypes["event:state.nvl.dialogAppend"],t),this.emitNvlStateChange(),{created:!1,entry:t}):(this.appendNvlDialog(e),{created:!0,entry:e})}activateNvlDialog(e,t="typing",n=!0){return n&&this.nvlState.activeDialogId===e&&this.nvlState.phase!=="idle"||(this.nvlState.activeDialogId=e,this.nvlState.phase=t,this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}waitForNvlAdvance(e,t){return this.nvlAdvanceWaiters.set(e,t),{cancel:()=>{this.nvlAdvanceWaiters.get(e)===t&&this.nvlAdvanceWaiters.delete(e)}}}requestNvlAdvance(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?"ignore":this.nvlState.phase==="typing"?"typing":this.nvlState.phase==="awaitAdvance"?(this.resolveNvlAdvance(e),"advance"):"ignore"}requestNvlSkip(e){return this.requestNvlAdvance(e)}completeNvlTyping(e){return!this.nvlState.active||this.nvlState.activeDialogId!==e?!1:(this.nvlState.phase="awaitAdvance",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.events.emit(ue.EventTypes["event:state.nvl.dialogComplete"],e),this.emitNvlStateChange(),!0)}settleNvlDialog(e){return this.nvlState.activeDialogId===e&&(this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange()),this}suppressNextNvlTyping(){return this._suppressNextNvlTyping=!0,this}consumeNvlTypingSuppression(){return this._suppressNextNvlTyping?(this._suppressNextNvlTyping=!1,!0):!1}beginAdvDialog(e,t){return this.advDialogState={dialogId:e,actionId:t,ended:!1},this.events.emit(ue.EventTypes["event:state.dialog.change"]),this}completeAdvDialogTyping(e){return!e||!this.advDialogState||this.advDialogState.dialogId!==e?this:(this.advDialogState.ended||(this.advDialogState.ended=!0,this.events.emit(ue.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(ue.EventTypes["event:state.dialog.change"])),this}getAdvDialogState(){return this.advDialogState}recordStageClick(){return this.stageClickBuffer={timestamp:Date.now()},this}suspendAdvance(){let e=Symbol("advance-suspension");return this.advanceSuspensions.add(e),()=>{this.advanceSuspensions.delete(e)}}isAdvanceSuspended(){return this.advanceSuspensions.size>0}consumeStageClick(e=200){if(!this.stageClickBuffer)return!1;let{timestamp:t}=this.stageClickBuffer,n=Date.now()-t;return this.stageClickBuffer=null,n>=0&&n<=e}createDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i);if(!r)throw this.sceneNotFound();let s=r.layers.get(n||i.config.defaultDisplayableLayer);if(!s)throw this.layerNotFound();return s.push(e),this}disposeDisplayable(e,t=null,n=null){let i=this.getLastSceneIfNot(t),r=this.findElementByScene(i)?.layers.get(n||i.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();let s=r.indexOf(e);if(s===-1)throw new E(`Displayables not found when disposing. (disposing: ${e.getId()})`);return r.splice(s,1),this}forceReset(){[...this.state.elements].forEach(({scene:t})=>{this.offSrcManager(t.srcManager),this.removeScene(t),t.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.state.vfx=[],this.nvlState={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},this.nvlAdvanceWaiters.clear(),this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return Da.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new E("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=ke.proxy(S.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof ze&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(J.immediate({}),()=>{});t.attachChild(s),r.updateStyleSync(),"flush"in r&&r.flush()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new Oe("State already mounted");if(!e)throw new Oe("Invalid state key");return this.exposedState.set(e,t),this.events.emit(ue.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new E("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let i=this.events.on(ue.EventTypes["event.state.onExpose"],(r,s)=>{r===e&&(t(s),i.cancel())});return i}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(i=>i.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()]),vfx:this.state.vfx.map(e=>[e.getId(),e.toData()]),nvlState:{active:this.nvlState.active,visible:this.nvlState.visible,sessionId:this.nvlState.sessionId,options:this.nvlState.options?{...this.nvlState.options}:null,activeDialogId:this.nvlState.activeDialogId,phase:this.nvlState.phase,pendingAdvance:this.nvlState.pendingAdvance,dialogIds:this.nvlState.dialogs.map(e=>e.id),dialogs:this.nvlState.dialogs.map(e=>({id:e.id,actionId:e.actionId,text:e.text,characterId:e.character?e.character.getId():null}))}}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:i,audio:r,videos:s}=e;if(i.forEach(({sceneId:a,elements:l})=>{this.logger.debug("Loading scene: "+a);let c=t.get(a);if(!c)throw new E("Scene not found, id: "+a+`
|
|
37
37
|
NarraLeaf cannot find the element with the id from the saved game`);let u={scene:c,layers:this.constructLayerMap(l.layers,t),menus:[],texts:[]};this.state.elements.push(u),this.registerSrcManager(c.srcManager),this.getExposedStateAsync(c,d=>{ae.initBackgroundMusic(c,d)})}),this.audioManager.fromData(r,t),this.state.videos=s.map(([a,l])=>{let c=t.get(a);if(!c)throw new E("Video not found, id: "+a+`
|
|
38
|
-
NarraLeaf cannot find the element with the id from the saved game`);return c.fromData(l),c}),this.state.vfx=(e.vfx??[]).flatMap(([a,l])=>{let c=t.get(a);return c?(c.fromData(l),[c]):(this.logger.weakWarn("NarraLeaf-React: Vfx","Vfx not found when loading a saved game, skipped. (id: "+a+")"),[])}),e.nvlState){let a=(e.nvlState.dialogs||[]).map(l=>{let c=l.characterId&&t.get(l.characterId)||null,u=l.text||"";return{id:l.id,actionId:l.actionId||l.id,character:c,sentence:new
|
|
38
|
+
NarraLeaf cannot find the element with the id from the saved game`);return c.fromData(l),c}),this.state.vfx=(e.vfx??[]).flatMap(([a,l])=>{let c=t.get(a);return c?(c.fromData(l),[c]):(this.logger.weakWarn("NarraLeaf-React: Vfx","Vfx not found when loading a saved game, skipped. (id: "+a+")"),[])}),e.nvlState){let a=(e.nvlState.dialogs||[]).map(l=>{let c=l.characterId&&t.get(l.characterId)||null,u=l.text||"";return{id:l.id,actionId:l.actionId||l.id,character:c,sentence:new me(u,{character:c}),text:u}});this.nvlState={active:e.nvlState.active,visible:e.nvlState.visible,sessionId:e.nvlState.sessionId,dialogs:a,options:e.nvlState.options||null,activeDialogId:e.nvlState.activeDialogId||null,phase:e.nvlState.phase||(e.nvlState.activeDialogId?"awaitAdvance":"idle"),pendingAdvance:e.nvlState.pendingAdvance||!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active&&this.events.emit(ue.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.nvlState.visible&&this.events.emit(ue.EventTypes["event:state.nvl.visibilityChange"],!0,this.nvlState.options?.showTransition),this.emitNvlStateChange()}}getLastSceneIfNot(e){let t=e||this.getLastScene();if(!t||!this.sceneExists(t))throw new E('Scene not found, please call "scene.activate()" first.');return t}createElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(i=>[i,i.toData()])]))}}fromElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(([i,r])=>(i.fromData(r),i))])),texts:[],menus:[]}}removeElements(e){let t=this.state.elements.findIndex(n=>n.scene===e);return t===-1?(this.logger.weakWarn("Scene not found when removing elements",e.getId()),this):(this.resetLayers(this.state.elements[t].layers),this.state.elements.splice(t,1),this.logger.debug("GameState","Removing elements",e.getId()),this)}resetLayers(e){let t=this.getLiveGame().story?.camera??null;e.forEach((n,i)=>{i.reset(),n.forEach(r=>{t&&r===t||r.reset()})})}syncNvlDerivedState(){this.nvlState.isTyping=this.nvlState.phase==="typing",this.nvlState.activeDialogId||(this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.nvlState.isTyping=!1)}emitNvlStateChange(){this.syncNvlDerivedState(),this.events.emit(ue.EventTypes["event:state.nvl.change"],this.getNvlState()),this.stage.update()}resolveNvlAdvance(e){let t=this.nvlAdvanceWaiters.get(e);return t?(this.nvlAdvanceWaiters.delete(e),this.nvlState.activeDialogId=null,this.nvlState.phase="idle",this.nvlState.pendingAdvance=!1,this.syncNvlDerivedState(),this.emitNvlStateChange(),t(),!0):!1}isDisplayableVisible(e){return(e.transformState.get().opacity??0)>0}createWaitableAction(e,t){return{action:e,onClick:(i=>{t&&t(i)})}}sceneNotFound(){return new E("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new E("Layer not found, target layer may not be activated. You may forget to add the layer to the scene config")}constructLayerMap(e,t){return new Map(Object.entries(e).map(([n,i])=>{let r=t.get(n);if(!r)throw new E("Layer not found, id: "+n+`
|
|
39
39
|
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+`
|
|
40
40
|
NarraLeaf cannot find the element with the id from the saved game
|
|
41
|
-
This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};ue.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=ue;var
|
|
41
|
+
This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};ue.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=ue;var La=32767,Gc=1e3,Xe=class o{constructor(e,t=void 0){this.liveGame=e;this.__tag=void 0;this.waitingAction=null;this.loopConfig=null;this.loopBodyActions=[];this.loopCondition=null;this.loopStartTime=0;this.loopDebugCheckpoint=0;this.__tag=t,this.stack=new Bi().addPushValidator(n=>{let i=this.stack.peek();if(n===i)throw new Oe("StackModel: Unexpected self-push in stack.");if(o.isCalledActionResult(i)){if(i.wait&&o.isStackModelsAwaiting(i.wait.type,i.wait.stackModels))throw new Oe("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(S.isAwaitable(i)&&!i.isSettled())throw new Oe("StackModel: Unexpected unsettled Awaitable in stack.");if(!o.isCalledActionResult(n)&&!S.isAwaitable(n))throw new Oe("StackModel: Unexpected non-CalledActionResult or Awaitable in stack.");return!0})}static isStackModel(e){return e instanceof o}static createStackModel(e,t,n){let i=new o(e);return i.deserialize(t,n),i}static createCountLoop(e,t,n){let i=new o(e,"loop:count");return i.initLoop({type:"count",counter:0,limit:t,bodyActionIds:n.map(r=>r.getId()),broken:!1},n,null),i}static createConditionLoop(e,t,n,i){let r=new o(e,"loop:condition");return r.initLoop({type:"condition",counter:0,conditionActionId:n,bodyActionIds:i.map(s=>s.getId()),broken:!1},i,t),r}static isCalledActionResult(e){return!!e&&!this.isStackModel(e)&&!S.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?S.any(...t.map(n=>n.execute())):S.all(...t.map(n=>n.execute()))}static isStackModelsAwaiting(e,t){if(t.length===0)throw new Error("StackModel: StackModels are empty.");return e==="any"?t.every(n=>!n.isEmpty()):t.some(n=>!n.isEmpty())}initLoop(e,t,n){this.loopConfig=e,this.loopBodyActions=t,this.loopCondition=n,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=0,this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody()}shouldContinueLoop(e){return!this.loopConfig||this.loopConfig.broken?!1:this.loopConfig.type==="count"?this.loopConfig.counter<(this.loopConfig.limit??0):this.loopCondition?this.loopCondition.evaluate({gameState:e}).value:!1}pushLoopBody(){if(this.loopBodyActions.length!==0)for(let e=this.loopBodyActions.length-1;e>=0;e--)this.stack.push(o.fromAction(this.loopBodyActions[e]))}onIterationComplete(){!this.loopConfig||this.loopConfig.broken||(this.loopConfig.counter++,this.liveGame.game.config.app.debug&&this.checkInfiniteLoop(),this.shouldContinueLoop(this.liveGame.getGameStateForce())&&this.pushLoopBody())}checkInfiniteLoop(){if(!this.loopConfig)return;let e=this.loopConfig.counter;if(e>0&&e%La===0){let t=Date.now()-this.loopStartTime;if(e-this.loopDebugCheckpoint>=La&&t<Gc){let i=new E(`[NarraLeaf] Potential infinite loop detected!
|
|
42
42
|
Loop has executed ${e} iterations in ${t}ms.
|
|
43
43
|
This is likely a bug in your game script. Check your loop conditions.
|
|
44
|
-
Loop type: ${this.loopConfig.type}, broken: ${this.loopConfig.broken}`);throw this.liveGame.getGameStateForce().logger.error("StackModel",i.message),i}this.loopDebugCheckpoint=e,this.loopStartTime=Date.now()}}breakLoop(){if(!this.loopConfig)throw new E("Cannot break: StackModel is not a loop");this.loopConfig.broken=!0,this.stack.clear()}isLoop(){return this.loopConfig!==null}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(S.isAwaitable(e)&&!e.isSettled())return e;if(o.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(o.isStackModelsAwaiting(e.wait.type,n))return n.forEach(i=>i.rollNext()),e}this.waitingAction=null;let t=this.stack.pop();if(S.isAwaitable(t)){if(t.isFailed())throw t.error;let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=null,t=!1,n=new S().registerSkipController(new
|
|
45
|
-
NarraLeaf cannot find the element with the id from the saved game`);
|
|
44
|
+
Loop type: ${this.loopConfig.type}, broken: ${this.loopConfig.broken}`);throw this.liveGame.getGameStateForce().logger.error("StackModel",i.message),i}this.loopDebugCheckpoint=e,this.loopStartTime=Date.now()}}breakLoop(){if(!this.loopConfig)throw new E("Cannot break: StackModel is not a loop");this.loopConfig.broken=!0,this.stack.clear()}isLoop(){return this.loopConfig!==null}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(S.isAwaitable(e)&&!e.isSettled())return e;if(o.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(o.isStackModelsAwaiting(e.wait.type,n))return n.forEach(i=>i.rollNext()),e}this.waitingAction=null;let t=this.stack.pop();if(S.isAwaitable(t)){if(t.isFailed())throw t.error;let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=null,t=!1,n=new S().registerSkipController(new V(()=>{t=!0,e?.abort()}));return(async()=>{let r=0;for(;!t;){if(r++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){if(this.loopConfig&&!this.loopConfig.broken&&(this.onIterationComplete(),!this.stack.isEmpty()))continue;t=!0;break}let s=this.rollNext();if(s){if(S.isAwaitable(s)){if(s.isFailed())throw s.error;if(s.isSettled())continue;if(e=s,await new Promise(a=>{s.onSettled(a)}),s.isFailed())throw s.error;if(s.isAborted()){t=!0;break}}else if(o.isCalledActionResult(s))if(s.wait)e=o.executeStackModelGroup(s.wait.type,s.wait.stackModels),await e;else continue}}})().then(()=>n.resolve()).catch(r=>n.fail(r)),n}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&S.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):o.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getWaitingAwaitable(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&S.isAwaitable(e)&&!e.isSettled()?e:null}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(o.isCalledActionResult(n))return n;if(e)throw new Oe("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}peekTopActionId(){for(let e=this.stack.size()-1;e>=0;e--){let t=this.stack.get(e);if(o.isCalledActionResult(t))return t.node?.action?.getId()??null}return null}peekExecutingActionId(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&o.isCalledActionResult(e)?e.node?.action?.getId()??null:null}snapshot(){let e=[];for(let n=this.stack.size()-1;n>=0;n--){let i=this.stack.get(n);if(!o.isCalledActionResult(i))continue;let r={actionId:i.node?.action?.getId()??null,actionType:i.node?.action?.type??null};i.wait?.stackModels&&(r.branchWaitType=i.wait.type,r.branches=i.wait.stackModels.map(s=>s.snapshot())),e.push(r)}let t={frames:e};return this.__tag&&(t.tag=this.__tag),this.loopConfig&&(t.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,broken:this.loopConfig.broken}),t}executeActions(e){if(!e.node?.action)return null;let t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this}),n=i=>i?S.isAwaitable(i)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",i),this.stack.push(i),i):i.node?.action?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",i),this.stack.push(i),i):null:null;if(Array.isArray(t)){let i=null;for(let r of t){let s=n(r);s&&(i=s)}return i}else{let i=n(t);if(i)return i}return null}isWaiting(){let e=this.stack.peek();return e?S.isAwaitable(e)?!e.isSettled():o.isCalledActionResult(e)&&e.wait?o.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(e=!0){let t=r=>{if(o.isCalledActionResult(r)){let s=r.node?.action?.getId()??null,a=r.node?.action?.type??null;return r.wait?.stackModels?{type:"link",actionType:a,action:s,stacks:r.wait.stackModels.map(l=>l.serialize()),stackWaitType:r.wait.type}:{type:"action",actionType:a,action:s}}return null},n=this.stack.map(t).filter(function(r){return r!==null});if(e&&this.waitingAction){let r=t(this.waitingAction);r&&n.push(r)}let i={items:n};return this.loopConfig&&(i.loop={type:this.loopConfig.type,counter:this.loopConfig.counter,limit:this.loopConfig.limit,conditionActionId:this.loopConfig.conditionActionId,bodyActionIds:this.loopConfig.bodyActionIds,broken:this.loopConfig.broken}),i}reset(){this.stack.forEach(e=>{o.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):S.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear(),this.loopConfig=null,this.loopBodyActions=[],this.loopCondition=null,this.loopStartTime=0,this.loopDebugCheckpoint=0}deserialize(e,t){this.reset();let n=e.items;for(let i of n)if(i.type==="action"){if(!i.action)continue;let{actionType:r,action:s}=i,a=t.get(s);if(!a)throw new Error(`Action not found: ${s}`);this.stack.push({type:r,node:a.contentNode,wait:null})}else if(i.type==="link"){let{actionType:r,action:s,stacks:a,stackWaitType:l}=i;if(l==null)throw new Error(`Missing stackWaitType for link action: ${s}`);this.stack.push({type:r,node:s?t.get(s)?.contentNode??null:null,wait:{type:l,stackModels:a.map(c=>o.createStackModel(this.liveGame,c,t))}})}if(e.loop){let i=e.loop,r=[];for(let a of i.bodyActionIds){let l=t.get(a);if(!l)throw new Error(`Loop body action not found: ${a}`);r.push(l)}let s=null;if(i.type==="condition"&&i.conditionActionId){let a=t.get(i.conditionActionId);if(a){let l=a.contentNode.getContent();Array.isArray(l)&&l.length>=2&&j.isLambda(l[1])&&(s=l[1])}}this.loopConfig={type:i.type,counter:i.counter,limit:i.limit,conditionActionId:i.conditionActionId,bodyActionIds:i.bodyActionIds,broken:i.broken},this.loopBodyActions=r,this.loopCondition=s,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=i.counter}return this}isEmpty(){return this.stack.isEmpty()}push(...e){return this.stack.push(...e),this}};var Me=class Me{constructor(e){this.events=new Y;this.story=null;this.gameLock=new Dn;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.elementAuditCountdown=0;this.lastDialog=null;this.mapCache=null;this._currentActionId=null;this.game=e,this._storable=new ti,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new Ft(Me.GameSpacesKey.game,Me.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.story;if(!e)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");return{name:this.currentSavedGame.name,meta:{version:ma,created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:e.hash()},game:{...this.serializeGameState(),history:this.gameState.gameHistory.serialize()}}}serializeGameState(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");let n=this._storable.toData(),i=e.toData(),r=t.getAllElementStates();this.auditElementDirtyMarks(t);let s=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(l=>l.serialize());return{store:n,stage:i,elementStates:r,stackModel:s,asyncStackModels:a,services:t.serializeServices()}}auditElementDirtyMarks(e){if(!this.game.config.app.debug||this.elementAuditCountdown-- >0)return;this.elementAuditCountdown=Me.ElementAuditInterval;let t=e.findUnmarkedElements();t.length&&(t.forEach(n=>n.markDirty()),this.gameState?.logger.warn("LiveGame.auditElementDirtyMarks",`${t.length} element(s) had state that no longer matches the script but were never marked dirty, so the save just written left them out. They have been marked, so the next save will carry them - but something is writing element state outside the action dispatch: ${t.map(n=>n.getId()).join(", ")}`))}captureGameState(){try{return this.serializeGameState()}catch(e){return this.gameState?.logger.warn("LiveGame.captureGameState",e),null}}deserialize(e){if(!e)throw new Error("No saved game provided when trying to deserialize game state");this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");this.game.hooks.trigger("beforeRestore",[]),t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:i,stage:r,elementStates:s,services:a,stackModel:l,asyncStackModels:c}}=e,[u,d]=this.constructMaps();this.initNamespaces(),this._storable.load(i),d.forEach(p=>p.reset()),s.forEach(({id:p,data:h})=>{t.logger.debug("restore element",p);let f=d.get(p);if(!f)throw new Error("Element not found, id: "+p+`
|
|
45
|
+
NarraLeaf cannot find the element with the id from the saved game`);f.fromData(h),f.markDirty()}),d.forEach(p=>{p instanceof ze&&p._rebindLoop(u)}),this.currentSavedGame=e,t.loadData(r,d),this.stackModel.deserialize(l,u),c.forEach(p=>{let h=Xe.createStackModel(this,p,u);this.asyncStackModels.add(h),t.timelines.attachTimeline(this.executeAsyncStackModel(h))}),n.deserializeServices(a),t.gameHistory.load(e.game.history??[],u),this.game.hooks.trigger("afterRestore",[]),t.events.once(L.EventTypes["event:state.onRender"],()=>{t.schedule(()=>{t.rollLock.unlock(),t.stage.next()},0)}),t.stage.forceUpdate()}getHistory(){return this.assertGameState(),this.gameState.gameHistory.getHistory()}getFuture(){return this.assertGameState(),this.gameState.gameHistory.getFuture()}canUndo(){return this.assertGameState(),this.gameState.gameHistory.canUndo()}canRedo(){return this.assertGameState(),this.gameState.gameHistory.canRedo()}undo(){this.assertGameState();let e=this.gameState.gameHistory;return e.canUndo()?this.restoreToIndex(e.getCursor()-1,"LiveGame.undo"):(this.gameState.logger.warn("LiveGame.undo","No line to step back to"),!1)}redo(){this.assertGameState();let e=this.gameState.gameHistory;return e.canRedo()?this.restoreToIndex(e.getCursor()+1,"LiveGame.redo"):(this.gameState.logger.warn("LiveGame.redo","No line to step forward to"),!1)}restoreToHistory(e){this.assertGameState();let t=this.gameState.gameHistory.indexOfToken(e);return t<0?(this.gameState.logger.warn("LiveGame.restoreToHistory","No history entry for token",e),!1):this.restoreToIndex(t,"LiveGame.restoreToHistory")}restoreToIndex(e,t){this.assertGameState();let n=this.gameState.gameHistory,i=n.getAt(e);if(!i)return this.gameState.logger.warn(t,"No history entry at",e),!1;if(e<n.getCursor()&&this.gameState.actionHistory.has(i.token)){let a=n.getCursor();if(n.setCursor(e),this.undoInPlace(i,t))return this.auditRestoredLine(i,t),!0;n.setCursor(a)}if(!i.snapshot)return this.gameState.logger.warn(t,"History entry has no restore snapshot",i.token),!1;let r=i.token,s={name:this.currentSavedGame?.name??"",meta:this.currentSavedGame?.meta??this.getNewSavedGame().meta,game:{...i.snapshot,history:n.serializeAll()}};return this.deserialize(s),this.gameState.gameHistory.setCursor(this.gameState.gameHistory.indexOfToken(r)),i.action.type===Yt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),!0}undoInPlace(e,t){this.assertGameState();let n=this.gameState.actionHistory;if(!n.has(e.token))return!1;let i=this.gameLock.register().lock();this.stackModel.abortStackTop();let r=n.undoUntil(e.token);if(!r)return this.gameLock.off(i.unlock()),!1;let[s]=this.constructMaps(),{rootStackSnapshot:a,stackModel:l}=r;return r.action.type===Yt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),this.stackModel.deserialize(a,s),l===this.stackModel&&this.stackModel.push(Xe.fromAction(r.action)),this.gameLock.off(i.unlock()),this.gameState.logger.debug(t,"Stepped back in place to",e.token),this.gameState.stage.forceUpdate(),this.gameState.stage.next(),this.gameState.schedule(()=>{this.gameState&&this.gameState.forceAnimation()},0),!0}auditRestoredLine(e,t){if(!this.game.config.app.debug||!e.snapshot)return;let n=JSON.stringify([...e.snapshot.elementStates].sort((r,s)=>r.id.localeCompare(s.id))),i=JSON.stringify([...this.serializeGameState().elementStates].sort((r,s)=>r.id.localeCompare(s.id)));n!==i&&this.gameState?.logger.warn(t,`Stepping back in place did not reproduce the state this line's snapshot describes, so an action's undo does not fully reverse it. Restoring the snapshot would have been correct; this path was not.
|
|
46
46
|
expected: ${n}
|
|
47
|
-
actual: ${i}`)}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=S.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new be({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(L.EventTypes["event:state.player.skip"],!0)}async fastForward(e={}){this.assertGameState();let t=this.gameState,n=e.until??"menu",i=typeof n=="object"?n.actionId:null,r=n==="menu"||i!==null,s=e.maxSteps??t.game.config.maxStackModelLoop,a=e.stepTimeout??Me.FastForwardStepTimeout,l=i!==null?{reachedTarget:!1}:{},c=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let u=0;for(;u++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...l};if(this.stackModel.isEmpty())return{reason:"end",...l};let d=this.stackModel.getWaitingAwaitable();if(d){if(!await Me.settleSuspendedStep(t,d,a))return{reason:"stalled",...l}}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...l}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(c)}}static settleSuspendedStep(e,t,n){return new Promise(i=>{let r=!1,s=null,a,l=d=>{r||(r=!0,s!==null&&(clearTimeout(s),s=null),a?.cancel?.(),i(d))};if(a=t.onSettled(()=>l(!0)),r){a?.cancel?.();return}let c=Date.now()+n,u=()=>{if(!r&&(e.events.emit(L.EventTypes["event:state.player.skip"],!0),!r)){if(Date.now()>=c){l(!1);return}s=setTimeout(u,Me.FastForwardSkipInterval)}};u()})}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(Me.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(Me.EventTypes["event:menu.choose"],e)}onCurrentActionChange(e){return this.events.on(Me.EventTypes["event:action.current"],e)}getCurrentActionId(){return this._currentActionId}getStackSnapshot(){return this.stackModel?{root:this.stackModel.snapshot(),async:Array.from(this.asyncStackModels).map(e=>e.snapshot())}:{root:{frames:[]},async:[]}}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(Xe.fromAction(i)):e.logger.warn("No scene root found");let r=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return r?r.forEach(s=>{e.logger.debug("reset element",s),s.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],i=>{t.set(i.getId(),i),n.set(i.callee.getId(),i.callee)},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let i=this.gameState.playerCurrent;return i?(i.addEventListener(e,t,n),{cancel:()=>i.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new Xe(this);return this.asyncStackModels.add(t),t.push(...e),t}executeAsyncStackModel(e){this.assertGameState();let t=e.execute();return t.onFailed(n=>{this.gameState.logger.error("Async StackModel",n)}),t.onSettled(()=>{this.asyncStackModels.delete(e)}),t}createStackModel(e){let t=new Xe(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");this._currentActionId=t.getId(),this.events.hasListeners(Me.EventTypes["event:action.current"])&&this.events.emit(Me.EventTypes["event:action.current"],{actionId:t.getId(),actionType:t.type}),t.callee?.markDirty();let i=t.executeAction(e,n);return S.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new Fe("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Xe(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new Fe("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let i=t?.contentNode||null,r=[],s=[],a=new Set;for(;(i||s.length)&&!(n&&r.length>=n);){if(i||(i=s.pop().contentNode),[Nt].some(l=>i?.action&&i.action instanceof l)){i=null;continue}if(i.action&&i.action.is(ae,_.jumpTo)){let[l]=i.action.contentNode.getContent(),c=e.getScene(l);if(!c)throw i.action._sceneNotFoundError(i.action.getSceneName(l));if(a.has(c)){i=null;continue}a.add(c),i=c.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(oe,ie.do)){let[l]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=l[0]?.contentNode||null}i?.action&&r.push(i.action),i=i?.getChild()||null}return r}clearMainStack(){if(!this.stackModel)throw new Fe("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new Fe("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:zs(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:{items:[]},asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new E("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new E("Player Element Not Mounted")}};Me.DefaultNamespaces={game:{}},Me.GameSpacesKey={game:"game"},Me.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose","event:action.current":"event:action.current"},Me.ElementAuditInterval=50,Me.FastForwardStepTimeout=1e4,Me.FastForwardSkipInterval=16;var Ht=Me;var ai=class ai{constructor(e){this.events=new X;this.settings={...e},this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(ai.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(ai.EventTypes["event:game.preference.change"],(n,i)=>{typeof e=="string"?e===n&&t&&t(i):e(n,i)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};ai.EventTypes={"event:game.preference.change":"event:game.preference.change"};var li=ai;import"client-only";import pl,{useEffect as gp,useRef as Xr}from"react";import"client-only";import Ca,{useContext as xa,useState as Ac}from"react";var gr=Ca.createContext(null);function wa({children:o,game:e}){"use client";let t=new re({}),[n]=Ac(e||t);return Ca.createElement(gr,{value:n},o)}function R(){let o=xa(gr);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function ka(){return xa(gr)}import Cc,{createContext as xc,useContext as Pa}from"react";var Ea="/",uo=class uo{constructor(e,t=uo.rootPath){this.events=new X;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,l]=s.split("=");a&&(i[decodeURIComponent(a)]=l?decodeURIComponent(l):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let l=a.slice(1);n[l]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new E(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new E(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),i=t.split("/"),r=[];r.push(...n);for(let s=0;s<i.length;s++){let a=i[s];a===""||a==="."||(a===".."?r.length>0&&r.pop():r.push(a))}return this.buildPath(r)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),s=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(s)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),ot(()=>{t()}))})}else ot(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};uo.rootPath=Ea;var un=uo,yr=xc(null);function Da({children:o}){let e=R();return Cc.createElement(yr,{value:{router:e.router}},o)}function Vt(){if(!Pa(yr))throw new Error("useRouter must be used within a RouterProvider");return Pa(yr).router}import Ra from"react";import Rc from"clsx";import wc,{createContext as kc,useContext as Pc,useLayoutEffect as Ec,useReducer as Dc,useState as Lc}from"react";var Zt=class Zt{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new X().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(Zt.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(Zt.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(Zt.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(Zt.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(Zt.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(Zt.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};Zt.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var vr=Zt,Sr=kc(null);function La({children:o}){"use client";let[e]=Lc(()=>new vr);return wc.createElement(Sr,{value:{ratio:e}},o)}function ye(){let o=Pc(Sr),[,e]=Dc(n=>n+1,0);if(!Sr||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return Ec(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function Ft({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=ye(),s=r.getStyle();return Ra.createElement("div",{className:Rc("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},Ra.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import Ic,{useEffect as Mc}from"react";function pn(o){let e=R(),[t,n]=Ic.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return Mc(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import Tr from"react";import po from"react";import Ia from"clsx";function mo({children:o,className:e,style:t,...n}){let{ratio:i}=ye(),r=R();return po.createElement(Ft,{className:Ia("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${i.state.scale})`,transformOrigin:"left top",width:r.config.width,height:r.config.height,pointerEvents:"none"},"data-element-type":"full",...n},po.createElement("div",{className:"absolute inset-0 w-full h-full"},po.createElement("div",{className:"inset-0 w-full h-full"},po.createElement("div",{className:Ia("pointer-events-auto-rest",e),style:t},o))))}function Nc({children:o,className:e,style:t}){return Tr.createElement(Tr.Fragment,null,Tr.createElement(mo,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import Ma from"clsx";import Na from"react";function fo({className:o,children:e,...t}){let{ratio:n}=ye();return Na.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:Ma("w-full h-full")},Na.createElement("div",{className:Ma("z-20",o),...t},e))}import St,{useState as Ga}from"react";import{motion as Gc}from"motion/react";function ho({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let l=R(),[c,u]=Ga(!1);if(!l.config.app.inspector)return St.createElement(r,{...a,ref:s},o);let d={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:c?1e3:"auto"}};return St.createElement(r,{...d,ref:s},n&&c&&St.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function Hc({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=R(),[a,l]=Ga(!1);if(!s.config.app.inspector)return St.createElement(i,{...r});let c={...r,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return St.createElement("div",null,St.createElement(i,{...c}),t&&a&&St.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function Oc(o){return St.createElement(ho,{...o,as:"div"})}function Vc(o){return St.createElement(ho,{...o,as:"span"})}function Fc(o){return St.createElement(Hc,{...o,as:"img"})}function Uc(o){return St.createElement(ho,{...o,as:"button"})}function Wc(o){return St.createElement(ho,{...o,as:Gc.div,ref:o.ref,layout:o.layout})}var Bc={Div:Oc,Span:Vc,Button:Uc,Img:Fc,mDiv:Wc},Ut=Bc;import bo from"clsx";import Ue,{useEffect as An,useRef as Wa,useState as Er}from"react";import{useEffect as Kc,useState as zc}from"react";function le(o){let[e,t]=zc(0);Kc(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import Ha from"react";var Tn=Ha.createContext(null);function Et(){let o=Ha.useContext(Tn);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}import go,{useCallback as $c,useLayoutEffect as ci,useMemo as Oa,useRef as Va}from"react";import{useIsPresent as jc}from"motion/react";var Dt=class Dt{constructor(e){this.events=new X;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.voiceWaitDisposer=null;this.config=e,this._state="pending",this.autoForwardScheduler=new Li,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}isActive(){return this._active}setActive(e){return this._active=e,e||this.cancelAutoForward(),this}requestComplete(){this._active&&(this.state==="ended"?this.safeEmit(Dt.Events.complete):this.safeEmit(Dt.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Dt.Events.forceSkip)))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(Dt.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",this.config.gameState.completeAdvDialogTyping(this.config.action.id),e.getPreference(re.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(Dt.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.releaseVoiceWait(),this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(Dt.Events.onFlush),this}onFlush(e){return this.events.on(Dt.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;if(!this._active||!e.getPreference(re.Preferences.autoForward)||this.state!=="ended")return;this.releaseVoiceWait();let t=this.getPlayingVoiceToken();if(!t){this.scheduleAutoForwardDelay();return}let n=()=>{this.releaseVoiceWait(),this.scheduleAutoForwardDelay()};t.once("ended",n),t.once("stop",n),this.voiceWaitDisposer=()=>{t.off("ended",n),t.off("stop",n)}}scheduleAutoForwardDelay(){let e=this.config.gameState.game.preference;!this._active||!e.getPreference(re.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(Dt.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(re.Preferences.gameSpeed))}getPlayingVoiceToken(){let e=this.config.action.sentence;if(!e)return null;try{let t=tt.getVoice(this.config.gameState,e);if(!t)return null;let n=this.config.gameState.audioManager.getToken(t);return n&&n.isPlaying()?n:null}catch{return null}}releaseVoiceWait(){let e=this.voiceWaitDisposer;this.voiceWaitDisposer=null,e?.()}};Dt.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Ne=Dt;function ui({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=jc(),s=i&&r,a=Va(!1),l=Va(o),c=l.current!==o,u=Oa(()=>o.sentence?.evaluate(we.getCtx({gameState:n})),[o.sentence,n]),d=Oa(()=>new Ne({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:c}),[o,n,t,u]),p=n.game.config.dialog,f=$c(h=>{!s||a.current||(a.current=!0,e?.(h))},[s,e]);return ci(()=>{a.current=!1},[d]),ci(()=>{l.current=o},[o]),ci(()=>(d.setActive(s),()=>{d.setActive(!1)}),[d,s]),ci(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",d),d.events.on(Ne.Events.complete,h=>{n.logger.log("NarraLeaf-React: Say","Complete",d.isIdle()),s&&(d.isIdle()||h?f(!1):d.setIdle(!0))}).cancel),[d,f,n,s]),ci(()=>{let h=A=>{s&&(A?(d.setIdle(!0),d.forceSkip()):d.isIdle()?f(!0):d.forceSkip())},m=n.events.on(L.EventTypes["event:state.player.skip"],h),v=n.events.on(L.EventTypes["event:state.player.stageClick"],()=>h(!1));return()=>{m.cancel(),v.cancel()}},[d,f,n,s]),go.createElement(go.Fragment,null,go.createElement(Tn,{value:d},go.createElement(p,null)))}import{useEffect as yo,useState as Qc}from"react";import{useEffect as qc,useState as Yc}from"react";function bn(o){let e=R(),[t,n]=Yc(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return qc(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var Vn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Vn||{});function vo({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=R(),[s]=bn("nextAction"),[a]=Qc(()=>{let l=o.firedTextEvents??(o.firedTextEvents=new Set);return new Ne({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e,firedTextEvents:l})});return yo(()=>{if(!n)return;let l=()=>{e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()},c=()=>{e.requestNvlSkip(o.id)==="typing"&&a.forceSkip()},u=e.events.on(L.EventTypes["event:state.player.stageClick"],l),d=e.events.on(L.EventTypes["event:state.player.skip"],c);return()=>{u.cancel(),d.cancel()}},[a,o.id,e,n]),yo(()=>{if(!n)return;let l=u=>{if(u.repeat||!r.keyMap.match("nextAction",u.key))return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()};if(r.config.useWindowListener){let u=r.getLiveGame().onWindowEvent("keydown",l);return()=>{u.cancel()}}let c=r.getLiveGame().onPlayerEvent("keydown",l);return()=>{c.cancel()}},[a,o.id,r,e,n,s]),yo(()=>{let l=a.events.on(Ne.Events.complete,c=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!c&&a.setIdle(!0))});return()=>{l.cancel()}},[a,o.id,e,n]),yo(()=>{let l=a.events.on(Ne.Events.simulateClick,()=>{if(!n)return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()});return()=>{l.cancel()}},[a,n]),a}function Xc(o,e){let{expression:t,sound:n}=o.config;if(t){let{image:i,appearance:r}=t;i._setAppearanceSync(r),e.stage.update();let s=e.getExposedState(i);s&&(I.isLayeredSrc(i)?s.flush():s.updateStyleSync())}n&&e.audioManager.play(n,{end:n.state.volume,duration:0})}function So(o,e,t){e.has(o)||(e.add(o),Xc(o,t))}function Fa(o,e,t){let n=[];for(let i of o)if(i.isTextEvent()){let r=i.text;e.has(r)||n.push(r),So(r,e,t)}return n}var Fn=new Map,br=new Set;function Jc(o,e){return Fn.set(o,e),br.delete(o),()=>{Fn.get(o)===e&&Fn.delete(o)}}function Zc(o){Fn.delete(o)}function _c(o){return Fn.get(o)??null}function Ar(o){if(!o)return null;if(typeof o!="string")return o;let e=Fn.get(o);return e||(br.has(o)||(br.add(o),console.warn(`NarraLeaf-React: no word renderer is registered as "${o}"; the word is rendered as plain text. Call registerWordRenderer before the line plays.`)),null)}import Cr from"react";var eu=2;function To(o){return o==="vertical-rl"||o==="vertical-lr"}function tu(o){return o===!1?0:typeof o=="number"?Number.isFinite(o)?Math.max(0,Math.round(o)):0:eu}function wr(o,e){return To(o)?{writingMode:o,textOrientation:e??"mixed"}:o?{writingMode:o}:{}}var xr=/[0-9A-Za-z]+(?:[.:\-/][0-9A-Za-z]+)*/g;function nu(o,e){if(e<=0)return[{text:o,combineUpright:!1}];let t=[],n=0;xr.lastIndex=0;for(let i=xr.exec(o);i;i=xr.exec(o))i[0].length>e||(i.index>n&&t.push({text:o.slice(n,i.index),combineUpright:!1}),t.push({text:i[0],combineUpright:!0}),n=i.index+i[0].length);return(n<o.length||t.length===0)&&t.push({text:o.slice(n),combineUpright:!1}),t}function kr(){return{wordBreak:"normal",lineBreak:"strict",overflowWrap:"break-word"}}function Pr(o,e,t){if(!e)return o;let n=tu(t);if(n<=0)return o;let i=nu(o,n);return i.some(r=>r.combineUpright)?i.map((r,s)=>r.combineUpright?Cr.createElement("span",{key:s,style:{textCombineUpright:"all"}},r.text):Cr.createElement(Cr.Fragment,{key:s},r.text)):o}function*Lr(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if(ze.isPause(n.text)){yield ze.from(n.text);continue}if(st.isTextEvent(n.text)){yield n.text;continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
|
|
47
|
+
actual: ${i}`)}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=S.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new ve({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(L.EventTypes["event:state.player.skip"],!0)}async fastForward(e={}){this.assertGameState();let t=this.gameState,n=e.until??"menu",i=typeof n=="object"?n.actionId:null,r=n==="menu"||i!==null,s=e.maxSteps??t.game.config.maxStackModelLoop,a=e.stepTimeout??Me.FastForwardStepTimeout,l=i!==null?{reachedTarget:!1}:{},c=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let u=0;for(;u++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...l};if(this.stackModel.isEmpty())return{reason:"end",...l};let d=this.stackModel.getWaitingAwaitable();if(d){if(!await Me.settleSuspendedStep(t,d,a))return{reason:"stalled",...l}}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...l}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(c)}}static settleSuspendedStep(e,t,n){return new Promise(i=>{let r=!1,s=null,a,l=d=>{r||(r=!0,s!==null&&(clearTimeout(s),s=null),a?.cancel?.(),i(d))};if(a=t.onSettled(()=>l(!0)),r){a?.cancel?.();return}let c=Date.now()+n,u=()=>{if(!r&&(e.events.emit(L.EventTypes["event:state.player.skip"],!0),!r)){if(Date.now()>=c){l(!1);return}s=setTimeout(u,Me.FastForwardSkipInterval)}};u()})}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(Me.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(Me.EventTypes["event:menu.choose"],e)}onCurrentActionChange(e){return this.events.on(Me.EventTypes["event:action.current"],e)}getCurrentActionId(){return this._currentActionId}getStackSnapshot(){return this.stackModel?{root:this.stackModel.snapshot(),async:Array.from(this.asyncStackModels).map(e=>e.snapshot())}:{root:{frames:[]},async:[]}}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(Xe.fromAction(i)):e.logger.warn("No scene root found");let r=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return r?r.forEach(s=>{e.logger.debug("reset element",s),s.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],i=>{t.set(i.getId(),i),n.set(i.callee.getId(),i.callee)},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let i=this.gameState.playerCurrent;return i?(i.addEventListener(e,t,n),{cancel:()=>i.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new Xe(this);return this.asyncStackModels.add(t),t.push(...e),t}executeAsyncStackModel(e){this.assertGameState();let t=e.execute();return t.onFailed(n=>{this.gameState.logger.error("Async StackModel",n)}),t.onSettled(()=>{this.asyncStackModels.delete(e)}),t}createStackModel(e){let t=new Xe(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");this._currentActionId=t.getId(),this.events.hasListeners(Me.EventTypes["event:action.current"])&&this.events.emit(Me.EventTypes["event:action.current"],{actionId:t.getId(),actionType:t.type}),t.callee?.markDirty();let i=t.executeAction(e,n);return S.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new Oe("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Xe(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new Oe("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let i=t?.contentNode||null,r=[],s=[],a=new Set;for(;(i||s.length)&&!(n&&r.length>=n);){if(i||(i=s.pop().contentNode),[Ht].some(l=>i?.action&&i.action instanceof l)){i=null;continue}if(i.action&&i.action.is(ae,_.jumpTo)){let[l]=i.action.contentNode.getContent(),c=e.getScene(l);if(!c)throw i.action._sceneNotFoundError(i.action.getSceneName(l));if(a.has(c)){i=null;continue}a.add(c),i=c.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(re,oe.do)){let[l]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=l[0]?.contentNode||null}i?.action&&r.push(i.action),i=i?.getChild()||null}return r}clearMainStack(){if(!this.stackModel)throw new Oe("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new Oe("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:_s(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:{items:[]},asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new E("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new E("Player Element Not Mounted")}};Me.DefaultNamespaces={game:{}},Me.GameSpacesKey={game:"game"},Me.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose","event:action.current":"event:action.current"},Me.ElementAuditInterval=50,Me.FastForwardStepTimeout=1e4,Me.FastForwardSkipInterval=16;var Ot=Me;var mi=class mi{constructor(e){this.events=new Y;this.settings={...e},this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(mi.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(mi.EventTypes["event:game.preference.change"],(n,i)=>{typeof e=="string"?e===n&&t&&t(i):e(n,i)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};mi.EventTypes={"event:game.preference.change":"event:game.preference.change"};var fi=mi;import"client-only";import wl,{useEffect as Fp,useRef as os}from"react";import"client-only";import Ra,{useContext as Ia,useState as Hc}from"react";var xr=Ra.createContext(null);function Ma({children:o,game:e}){"use client";let t=new se({}),[n]=Hc(e||t);return Ra.createElement(xr,{value:n},o)}function I(){let o=Ia(xr);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function Na(){return Ia(xr)}import Fc,{createContext as Oc,useContext as Ga}from"react";var Ha="/",vo=class vo{constructor(e,t=vo.rootPath){this.events=new Y;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,l]=s.split("=");a&&(i[decodeURIComponent(a)]=l?decodeURIComponent(l):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let l=a.slice(1);n[l]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new E(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new E(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),i=t.split("/"),r=[];r.push(...n);for(let s=0;s<i.length;s++){let a=i[s];a===""||a==="."||(a===".."?r.length>0&&r.pop():r.push(a))}return this.buildPath(r)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),s=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(s)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),st(()=>{t()}))})}else st(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};vo.rootPath=Ha;var mn=vo,wr=Oc(null);function Fa({children:o}){let e=I();return Fc.createElement(wr,{value:{router:e.router}},o)}function Ut(){if(!Ga(wr))throw new Error("useRouter must be used within a RouterProvider");return Ga(wr).router}import Va from"react";import $c from"clsx";import Vc,{createContext as Uc,useContext as Wc,useLayoutEffect as Bc,useReducer as zc,useState as Kc}from"react";var en=class en{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new Y().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(en.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(en.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(en.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(en.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(en.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(en.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};en.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var kr=en,Pr=Uc(null);function Oa({children:o}){"use client";let[e]=Kc(()=>new kr);return Vc.createElement(Pr,{value:{ratio:e}},o)}function he(){let o=Wc(Pr),[,e]=zc(n=>n+1,0);if(!Pr||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return Bc(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function Wt({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=he(),s=r.getStyle();return Va.createElement("div",{className:$c("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},Va.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import jc,{useEffect as qc}from"react";function fn(o){let e=I(),[t,n]=jc.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return qc(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import Er from"react";import So from"react";import Ua from"clsx";function To({children:o,className:e,style:t,...n}){let{ratio:i}=he(),r=I();return So.createElement(Wt,{className:Ua("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${i.state.scale})`,transformOrigin:"left top",width:r.config.width,height:r.config.height,pointerEvents:"none"},"data-element-type":"full",...n},So.createElement("div",{className:"absolute inset-0 w-full h-full"},So.createElement("div",{className:"inset-0 w-full h-full"},So.createElement("div",{className:Ua("pointer-events-auto-rest",e),style:t},o))))}function Yc({children:o,className:e,style:t}){return Er.createElement(Er.Fragment,null,Er.createElement(To,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import Wa from"clsx";import Ba from"react";function bo({className:o,children:e,...t}){let{ratio:n}=he();return Ba.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:Wa("w-full h-full")},Ba.createElement("div",{className:Wa("z-20",o),...t},e))}import At,{useState as za}from"react";import{motion as Xc}from"motion/react";function Ao({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let l=I(),[c,u]=za(!1);if(!l.config.app.inspector)return At.createElement(r,{...a,ref:s},o);let d={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:c?1e3:"auto"}};return At.createElement(r,{...d,ref:s},n&&c&&At.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function Qc({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=I(),[a,l]=za(!1);if(!s.config.app.inspector)return At.createElement(i,{...r});let c={...r,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return At.createElement("div",null,At.createElement(i,{...c}),t&&a&&At.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function Jc(o){return At.createElement(Ao,{...o,as:"div"})}function _c(o){return At.createElement(Ao,{...o,as:"span"})}function Zc(o){return At.createElement(Qc,{...o,as:"img"})}function eu(o){return At.createElement(Ao,{...o,as:"button"})}function tu(o){return At.createElement(Ao,{...o,as:Xc.div,ref:o.ref,layout:o.layout})}var nu={Div:Jc,Span:_c,Button:eu,Img:Zc,mDiv:tu},Bt=nu;import vi from"clsx";import ge,{useEffect as wn,useMemo as Cu,useRef as nl,useState as Hr}from"react";import{useEffect as iu,useState as ou}from"react";function le(o){let[e,t]=ou(0);iu(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import Ka from"react";var Cn=Ka.createContext(null);function Lt(){let o=Ka.useContext(Cn);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}import Co,{useCallback as ru,useLayoutEffect as hi,useMemo as $a,useRef as ja}from"react";import{useIsPresent as su}from"motion/react";var Rt=class Rt{constructor(e){this.events=new Y;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.voiceWaitDisposer=null;this.config=e,this._state="pending",this.autoForwardScheduler=new Oi,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}isActive(){return this._active}setActive(e){return this._active=e,e||this.cancelAutoForward(),this}requestComplete(){this._active&&(this.state==="ended"?this.safeEmit(Rt.Events.complete):this.safeEmit(Rt.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Rt.Events.forceSkip)))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners(Rt.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",this.config.gameState.completeAdvDialogTyping(this.config.action.id),e.getPreference(se.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(Rt.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.releaseVoiceWait(),this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit(Rt.Events.onFlush),this}onFlush(e){return this.events.on(Rt.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;if(!this._active||!e.getPreference(se.Preferences.autoForward)||this.state!=="ended")return;this.releaseVoiceWait();let t=this.getPlayingVoiceToken();if(!t){this.scheduleAutoForwardDelay();return}let n=()=>{this.releaseVoiceWait(),this.scheduleAutoForwardDelay()};t.once("ended",n),t.once("stop",n),this.voiceWaitDisposer=()=>{t.off("ended",n),t.off("stop",n)}}scheduleAutoForwardDelay(){let e=this.config.gameState.game.preference;!this._active||!e.getPreference(se.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(Rt.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(se.Preferences.gameSpeed))}getPlayingVoiceToken(){let e=this.config.action.sentence;if(!e)return null;try{let t=nt.getVoice(this.config.gameState,e);if(!t)return null;let n=this.config.gameState.audioManager.getToken(t);return n&&n.isPlaying()?n:null}catch{return null}}releaseVoiceWait(){let e=this.voiceWaitDisposer;this.voiceWaitDisposer=null,e?.()}};Rt.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Ne=Rt;function gi({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=su(),s=i&&r,a=ja(!1),l=ja(o),c=l.current!==o,u=$a(()=>o.sentence?.evaluate(we.getCtx({gameState:n})),[o.sentence,n]),d=$a(()=>new Ne({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:c}),[o,n,t,u]),p=n.game.config.dialog,h=ru(f=>{!s||a.current||(a.current=!0,e?.(f))},[s,e]);return hi(()=>{a.current=!1},[d]),hi(()=>{l.current=o},[o]),hi(()=>(d.setActive(s),()=>{d.setActive(!1)}),[d,s]),hi(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",d),d.events.on(Ne.Events.complete,f=>{n.logger.log("NarraLeaf-React: Say","Complete",d.isIdle()),s&&(d.isIdle()||f?h(!1):d.setIdle(!0))}).cancel),[d,h,n,s]),hi(()=>{let f=C=>{s&&(C?(d.setIdle(!0),d.forceSkip()):d.isIdle()?h(!0):d.forceSkip())},m=n.events.on(L.EventTypes["event:state.player.skip"],f),v=n.events.on(L.EventTypes["event:state.player.stageClick"],()=>f(!1));return()=>{m.cancel(),v.cancel()}},[d,h,n,s]),Co.createElement(Co.Fragment,null,Co.createElement(Cn,{value:d},Co.createElement(p,null)))}import{useEffect as xo,useState as cu}from"react";import{useEffect as au,useState as lu}from"react";function xn(o){let e=I(),[t,n]=lu(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return au(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var Bn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Bn||{});function wo({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=I(),[s]=xn("nextAction"),[a]=cu(()=>{let l=o.firedTextEvents??(o.firedTextEvents=new Set);return new Ne({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e,firedTextEvents:l})});return xo(()=>{if(!n)return;let l=()=>{e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()},c=()=>{e.requestNvlSkip(o.id)==="typing"&&a.forceSkip()},u=e.events.on(L.EventTypes["event:state.player.stageClick"],l),d=e.events.on(L.EventTypes["event:state.player.skip"],c);return()=>{u.cancel(),d.cancel()}},[a,o.id,e,n]),xo(()=>{if(!n)return;let l=u=>{if(u.repeat||!r.keyMap.match("nextAction",u.key))return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()};if(r.config.useWindowListener){let u=r.getLiveGame().onWindowEvent("keydown",l);return()=>{u.cancel()}}let c=r.getLiveGame().onPlayerEvent("keydown",l);return()=>{c.cancel()}},[a,o.id,r,e,n,s]),xo(()=>{let l=a.events.on(Ne.Events.complete,c=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!c&&a.setIdle(!0))});return()=>{l.cancel()}},[a,o.id,e,n]),xo(()=>{let l=a.events.on(Ne.Events.simulateClick,()=>{if(!n)return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()});return()=>{l.cancel()}},[a,n]),a}function uu(o,e){let{expression:t,sound:n}=o.config;if(t){let{image:i,appearance:r}=t;i._setAppearanceSync(r),e.stage.update();let s=e.getExposedState(i);s&&(G.isLayeredSrc(i)?s.flush():s.updateStyleSync())}n&&e.audioManager.play(n,{end:n.state.volume,duration:0})}function ko(o,e,t){e.has(o)||(e.add(o),uu(o,t))}function qa(o,e,t){let n=[];for(let i of o)if(i.isTextEvent()){let r=i.text;e.has(r)||n.push(r),ko(r,e,t)}return n}var zn=new Map,Dr=new Set;function pu(o,e){return zn.set(o,e),Dr.delete(o),()=>{zn.get(o)===e&&zn.delete(o)}}function du(o){zn.delete(o)}function mu(o){return zn.get(o)??null}function Lr(o){if(!o)return null;if(typeof o!="string")return o;let e=zn.get(o);return e||(Dr.has(o)||(Dr.add(o),console.warn(`NarraLeaf-React: no word renderer is registered as "${o}"; the word is rendered as plain text. Call registerWordRenderer before the line plays.`)),null)}import{useCallback as fu,useLayoutEffect as hu,useRef as Po,useState as gu}from"react";var Ya=.5,yu=.005,vu=12,Su=.05,Qa=12,Ja="--nl-auto-fit-scale";function Rr(o,e){return e===1?o:o==null||o===""?void 0:`calc(${typeof o=="number"?`${o}px`:String(o)} * ${e})`}var _a=`var(${Ja}, 1)`;function Za(o){return o===1?void 0:`${o*100}%`}function Xa(o,e){let t=getComputedStyle(o);return e?o.clientWidth-parseFloat(t.paddingLeft||"0")-parseFloat(t.paddingRight||"0"):o.clientHeight-parseFloat(t.paddingTop||"0")-parseFloat(t.paddingBottom||"0")}function el({enabled:o,minFontSize:e,vertical:t,signature:n}){let i=Po(null),r=Po(null),[s,a]=gu(1),l=Po(1),c=Po(0);l.current=s;let u=fu(()=>{let d=i.current,p=r.current,h=d?.parentElement;if(!d||!p||!h)return;let f=Xa(h,t);if(!Number.isFinite(f)||f<=0)return;c.current=f;let v=(parseFloat(getComputedStyle(d).fontSize)||0)/(l.current||1);if(v<=0)return;let C=Math.min(1,Math.max(Su,e/v)),g=T=>(p.style.fontSize=`${v*T}px`,p.style.setProperty(Ja,String(T)),(t?p.offsetWidth:p.offsetHeight)<=f+Ya),y;if(g(1))y=1;else if(C>=1||!g(C))y=C;else{let T=C,A=1;for(let w=0;w<vu&&A-T>yu;w++){let b=(T+A)/2;g(b)?T=b:A=b}y=T}a(T=>Math.abs(T-y)<.001?T:y)},[e,t]);return hu(()=>{if(!o){a(1);return}u();let d=i.current?.parentElement;if(!d)return;let p=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{Math.abs(Xa(d,t)-c.current)>Ya&&u()});p?.observe(d);let h=!1;return document.fonts?.ready.then(()=>{h||u()}),()=>{h=!0,p?.disconnect()}},[o,u,n,t]),{containerRef:i,mirrorRef:r,scale:s}}import Ir from"react";var Tu=2;function yi(o){return o==="vertical-rl"||o==="vertical-lr"}function bu(o){return o===!1?0:typeof o=="number"?Number.isFinite(o)?Math.max(0,Math.round(o)):0:Tu}function Nr(o,e){return yi(o)?{writingMode:o,textOrientation:e??"mixed"}:o?{writingMode:o}:{}}var Mr=/[0-9A-Za-z]+(?:[.:\-/][0-9A-Za-z]+)*/g;function Au(o,e){if(e<=0)return[{text:o,combineUpright:!1}];let t=[],n=0;Mr.lastIndex=0;for(let i=Mr.exec(o);i;i=Mr.exec(o))i[0].length>e||(i.index>n&&t.push({text:o.slice(n,i.index),combineUpright:!1}),t.push({text:i[0],combineUpright:!0}),n=i.index+i[0].length);return(n<o.length||t.length===0)&&t.push({text:o.slice(n),combineUpright:!1}),t}function Eo(){return{wordBreak:"normal",lineBreak:"strict",overflowWrap:"break-word"}}function Gr(o,e,t){if(!e)return o;let n=bu(t);if(n<=0)return o;let i=Au(o,n);return i.some(r=>r.combineUpright)?i.map((r,s)=>r.combineUpright?Ir.createElement("span",{key:s,style:{textCombineUpright:"all"}},r.text):Ir.createElement(Ir.Fragment,{key:s},r.text)):o}function*Or(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if(Ke.isPause(n.text)){yield Ke.from(n.text);continue}if(lt.isTextEvent(n.text)){yield n.text;continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
|
|
48
48
|
`?yield`
|
|
49
|
-
`:yield{text:r,full:n.text,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function
|
|
49
|
+
`:yield{text:r,full:n.text,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function Do(o){let e=Or(o),t=[];for(let n of e){if(Ke.isPause(n)||lt.isTextEvent(n))continue;let i=t[t.length-1];if(i&&i!==`
|
|
50
|
+
`&&n!==`
|
|
51
|
+
`&&i.tag===n.tag){t[t.length-1]={...n,text:i.text+n.text,config:n.config};continue}t.push(n)}return t}function il(o,e){o(t=>{let n=t[t.length-1];return n&&n!==`
|
|
50
52
|
`&&e!==`
|
|
51
|
-
`&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function
|
|
52
|
-
`?
|
|
53
|
-
`&&
|
|
54
|
-
`)return
|
|
55
|
-
|
|
56
|
-
`)return Ue.createElement("br",{key:D});let B=At(G);return Ue.createElement("span",{key:D,style:{...B,...kr()},className:bo("inline-block",G.config.className)},Ue.createElement(za,{word:G,vertical:vt,tateChuYoko:g,done:!1,style:B,renderer:Ar(G.config.render)}))};return Ue.createElement("div",{...T,className:bo("whitespace-pre-wrap",u),style:{...$t,...wr(v,A),...d}},yt.map(H))}function $a(o){return Ue.createElement(Rr,{...o,key:o.dialog?.config.action.id})}function au({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=vo({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Ue.createElement(Rr,{...r,dialog:s,key:s.config.action.id})}function lu(o){let e=Et();return Ue.createElement(Rr,{...o,dialog:e,key:e.config.action.id})}function dn(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Ue.createElement(au,{...o}):Ue.createElement(lu,{...o})}var cu=dn;import xo,{useEffect as uu,useLayoutEffect as pu,useMemo as qa,useRef as du,useState as mu}from"react";import Co from"react";var Ir=Co.createContext(null);function Mr(){let o=Co.useContext(Ir);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var Nr=Co.createContext(null);function ja(){let o=Co.useContext(Nr);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function wo({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let l=du(null),{register:c,unregister:u,getIndex:d}=ja(),[p,f]=mu(-1),{choose:h,evaluated:m,gameState:v}=Mr(),A=p===-1?null:m[p],g=qa(()=>we.getCtx({gameState:v}),[v]),{hidden:y,disabled:T}=qa(()=>{if(!A)return{hidden:!1,disabled:!1};let b=A.config.hidden?.evaluate(g)?.value??!1,x=!b&&(A.config.disabled?.evaluate(g)?.value??!1);return{hidden:b,disabled:x}},[A,g]);pu(()=>{if(!l.current)return;let b=l;c(b);let x=d(b);return f(x),l.current.dataset.index=x.toString(),()=>u(b)},[c,u,d]),uu(()=>{if(!t)return;let b=x=>{x.key.toLowerCase()===t.toLowerCase()&&!x.ctrlKey&&!x.metaKey&&(x.preventDefault(),x.stopPropagation(),C())};return window.addEventListener("keydown",b,!0),()=>{window.removeEventListener("keydown",b,!0)}},[t]);function C(){if(p===-1||!m[p]||y||T)return;let b=m[p];h({...b,evaluated:te.getText(b.words||[])})}let k=A&&!y;return xo.createElement(xo.Fragment,null,xo.createElement("button",{className:o,style:{...e,display:k?e?.display??void 0:"none"},onClick:C,ref:l,disabled:T},k&&xo.createElement($a,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Ne({useTypeEffect:!1,action:{sentence:A.prompt,words:A.words,character:null},gameState:v,evaluatedWords:A.words})})))}import ko from"react";import{AnimatePresence as fu}from"motion/react";function Po({children:o,...e}){let t=fu;return ko.createElement(ko.Fragment,null,ko.createElement("div",{...e},ko.createElement(t,null,o)))}import Ya from"react";function _t({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=Ya.useContext(Tn),l=e??o?.character??a?.config.action.character??null,c=n??l?.config.color,u=i??t??l?.state.name;return Ya.createElement("div",{...s,style:{color:c?Pn(c):void 0,...r}},u)}import yu from"clsx";import vu from"react";import Gr,{createContext as hu,useContext as gu,useState as Qa}from"react";var Cn=class Cn{constructor(){this.preloaded=[];this.events=new X}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(Cn.EventTypes["event:preloaded.add"],e),this.events.emit(Cn.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(Cn.EventTypes["event:preloaded.remove"],e),this.events.emit(Cn.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Re.getSrc(e)}};Cn.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=Cn;var Eo=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 Us(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,f)=>{i=p,r={...r,...f}}]);let s=new AbortController,a=s.signal,l=[],u={promise:o.getImage(i,a,r).then(async p=>{if(this.preloadTasks.delete(t),p){this.add(t,p);let f=await o.decodeImage(p);f&&n?.retainDecoded&&this.src.get(t)===p&&this.decoded.set(t,f)}}).catch(p=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),l.forEach(f=>f(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=>(l.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 Hr=hu(null);function Xa({children:o}){let e=R(),[t]=Qa(()=>new $e),[n]=Qa(()=>new Eo(e));return Gr.createElement(Gr.Fragment,null,Gr.createElement(Hr,{value:{preloaded:t,cacheManager:n}},o))}function Wt(){if(!Hr)throw new Error("usePreloaded must be used within a PreloadedProvider");return gu(Hr)}function Ja(){let o=Et(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return bu(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?I.getSrcURL(s):null,l=s&&I.isTagSrc(s)?[...s.state.currentSrc]:null,c=ca({character:n,sentence:i,portrait:s,currentSrc:a,tags:l,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=Tu(c.source);return{visible:!!u,src:u,character:c.character,portrait:c.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function Su({className:o,style:e,alt:t,...n}){let i=Ja(),{cacheManager:r}=Wt();if(!i.visible||!i.src)return null;let s=r.get(i.src)||i.src;return vu.createElement("img",{...n,"data-element-type":"dialog-avatar",className:yu("dialog-avatar",o),src:s,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function Tu(o){return o?P.srcToURL(o):null}function bu(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var Or=Su;import{useEffect as Au}from"react";function Cu(){let o=Et(),[e]=le(o.deps),t=te.getText(o.config.evaluatedWords);return Au(()=>o.events.on(Ne.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 Do,useEffect as Vr,useMemo as xu,useRef as wu,useState as Za}from"react";function ku(){let o=Et(),[e]=le(o.deps),[t,n]=Za(!0),[i,r]=Za(!0),s=wu(null),a=o.config.gameState,l=o.config.action.sentence,c=l?.config.voiceId??null;Vr(()=>o.events.on(Ne.Events.onFlush,()=>{e()}).cancel,[o]);let u=xu(()=>{if(!l)return null;try{return tt.getVoice(a,l)}catch{return null}},[a,l,c,l?.config.voice]);Vr(()=>{s.current=null,r(!0)},[l]),Vr(()=>{let m=!1,v=null,A=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),A=()=>y(),g=()=>y(),v.once("ended",A),v.once("stop",g));let T=a.events.on(L.EventTypes["event:state.player.lineEnd"],()=>{y()});return()=>{m=!0,T.cancel(),v&&A&&v.off("ended",A),v&&g&&v.off("stop",g)}},[a,u]);let d=Do(async m=>{let v=m??u;if(!v)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let A=v instanceof URL?be.voice(v.toString()):typeof v=="string"?be.voice(v):v,g=await a.getLiveGame().playSound(A);s.current=g;let y=()=>{r(!0)};return g.once("ended",y),g.once("stop",y),g},[a,u]),p=Do(()=>u,[u]),f=Do(()=>c,[c]),h=Do(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:d,getVoice:p,getVoiceId:f,getVoiceSrc:h}}import Fr,{createContext as Vu,useContext as Fu,useEffect as tl,useRef as Uu}from"react";import{useState as Pu}from"react";function Lo(o){let[e]=Pu(o);return e}import{AnimatePresence as Eu}from"motion/react";var Ro=Eu;import fi,{createContext as Mu,useContext as Nu,useEffect as Gu,useRef as Hu}from"react";import{useEffect as pi,useLayoutEffect as Du}from"react";function Lu(){let o=Vt(),[e]=le();return pi(()=>o.onChange(e).cancel,[]),o.getPathname()}function Ru(){let{router:o,path:e}=mi(),[t]=le();return pi(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function Iu(){let o=Vt(),[e]=le();return pi(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Io(o,e){let t=Vt();Du(()=>t.onUpdate(()=>o(t)).cancel,e),pi(()=>{o(t)},[])}function di(){let o=Vt(),[e]=le();return pi(()=>o.onChange(e).cancel,[]),e}var _a=Mu(null);function hi({children:o,path:e,consumedBy:t}){let i={router:Vt(),path:e,consumedBy:t};return fi.createElement(_a,{value:i},o)}function mi(){let o=Nu(_a);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.
|
|
57
|
-
This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function Ou({children:o,name:e,propagate:t}){let n=R(),[i]=le(),{path:r,router:s,consumedBy:a}=mi(),l=s.joinPath(r,e),c=Lo(()=>s.createToken(l+"@layout")),u=s.getCurrentPath(),d=Hu(!1),p=h=>{d.current=h,i()},f=s.matchPath(u,l);if(di(),Io(h=>{let m=h.matchPath(h.getCurrentPath(),l);if(d.current&&!m){if(!o){p(!1);return}h.registerUnmountingPath(c)}m&&h.isPathsUnmounting()&&h.unregisterUnmountingPath(c),m&&!d.current&&!h.isTransitioning()&&p(!0)},[f,o]),Gu(()=>{if(!f)return;let h=s.mount(l);return()=>{h.cancel()}},[l,s,f]),a)throw new E("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return fi.createElement(hi,{path:l},fi.createElement(Ro,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(c),p(!1)}},f&&d.current&&o))}function el({children:o}){return di(),fi.createElement(hi,{path:un.rootPath},fi.createElement(mo,{"data-layout-path":un.rootPath,key:un.rootPath},o))}var Ur=Vu(null);function Wu(){return Fu(Ur)}function Bu({children:o,name:e}){let[t]=le(),{path:n,router:i,consumedBy:r}=mi(),s=Wu(),a=s?.name??e,l=a??n+"@default",c=a?i.joinPath(n,a):n,u=Lo(()=>i.createToken(c+"@page")),d=i.getCurrentPath(),p=!a,f=Uu(!1),h=g=>{f.current=g,t()},m=p&&i.exactMatch(d,n)||i.exactMatch(d,c);if(r&&r!==l)throw new E("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");di(),Io(g=>{let y=p&&g.exactMatch(g.getCurrentPath(),n)||g.exactMatch(g.getCurrentPath(),c);if(f.current&&!y){if(!o){h(!1);return}g.registerUnmountingPath(u)}y&&g.isPathsUnmounting()&&g.unregisterUnmountingPath(u),y&&!f.current&&!g.isTransitioning()&&h(!0)},[m,o]),tl(()=>{if(!m)return;let g=p?i.mountDefaultHandler(c):i.mount(c);return i.emitOnPageMount(),()=>{g.cancel()}},[c,m]),tl(()=>()=>{i.unregisterUnmountingPath(u),h(!1)},[]);let v=Fr.createElement(hi,{path:n,consumedBy:l},Fr.createElement(Ro,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),h(!1)}},m&&f.current&&o));return(g=>s?Fr.createElement(Ur,{value:{name:null}},g):g)(v)}import Wr,{useCallback as Ku,useEffect as Br,useImperativeHandle as zu,useMemo as nl,useRef as Kr,useState as $u}from"react";var ju=50,qu={position:"relative",width:"100%",height:"100%",overflow:"hidden"},il={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function Yu(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function ol(o,e){return e==null?o:Math.max(o,e)}function Qu(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 rl=Wr.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:l,dataAttributes:c,onUpdate:u,children:d},p){let f=Kr(null),[h,m]=$u({...il,width:"0px",height:"0px"}),v=Kr(u),A=Kr(null);Br(()=>{v.current=u},[u]);let g=Ku(()=>{let C=f.current;if(!C)return;let k=C.clientWidth,b=C.clientHeight;if(k<=0||b<=0||e<=0)return;let x=Qu(k,b,e),O=ol(x.width,n),Q=ol(x.height,i),W=A.current;(!W||W.width!==O||W.height!==Q)&&(A.current={width:O,height:Q},m({...il,width:`${O}px`,height:`${Q}px`}));let ve=t>0?O/t:1;v.current?.({width:O,height:Q,scale:ve,containerWidth:k,containerHeight:b})},[e,t,n,i]),y=nl(()=>Vs(g,typeof r=="number"?r:ju),[g,r]);Br(()=>{g()},[g]),Br(()=>{let C=new ResizeObserver(()=>{y()});f.current&&C.observe(f.current);let k=()=>{y()};return window.addEventListener("resize",k),()=>{C.disconnect(),window.removeEventListener("resize",k)}},[y]),zu(p,()=>({requestUpdate:g}),[g]);let T=nl(()=>Yu(c),[c]);return Wr.createElement("div",{id:l,ref:f,style:qu,...T},Wr.createElement("div",{className:s,style:{...h,...a}},d))}),sl=rl;function Xu(){return R().getLiveGame()}import jr from"react";import Ju,{createContext as Zu,useContext as _u,useEffect as ep,useState as al}from"react";var tp={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},ll=Zu({state:tp,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function Bt(){return _u(ll)}function zr(){let{dialogs:o}=Bt();return o}function np(){let{isActive:o}=Bt();return o}function ip(){let{isVisible:o}=Bt();return o}function $r({children:o}){let t=R().getLiveGame().getGameState(),[n,i]=al(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=al(null);ep(()=>{let l=h=>({...h,dialogs:[...h.dialogs]}),c=t.events.on(L.EventTypes["event:state.nvl.enter"],(h,m)=>{i(l(t.getNvlState())),s(m?.showTransition||null)}),u=t.events.on(L.EventTypes["event:state.nvl.exit"],()=>{i(l(t.getNvlState()))}),d=t.events.on(L.EventTypes["event:state.nvl.dialogAppend"],()=>{i(l(t.getNvlState()))}),p=t.events.on(L.EventTypes["event:state.nvl.visibilityChange"],(h,m)=>{i(l(t.getNvlState())),s(m||null)}),f=t.events.on(L.EventTypes["event:state.nvl.change"],h=>{i(l(h))});return()=>{c.cancel(),u.cancel(),d.cancel(),p.cancel(),f.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return Ju.createElement(ll.Provider,{value:a},o)}import{AnimatePresence as op,motion as rp}from"motion/react";import sp from"clsx";function qr({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=Bt(),{ratio:r}=ye(),s=R(),a=i?.duration?i.duration/1e3:.3;return jr.createElement(op,null,n&&jr.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},jr.createElement(rp.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:sp("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 xn from"react";function Yr({renderDialogItem:o,dialogs:e}){return xn.createElement(qr,{className:"bg-black/80 text-white p-16 inset-8"},xn.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?xn.createElement(_t,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=xn.createElement(dn,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return xn.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}):xn.createElement(xn.Fragment,null,r,s))})))}import gt,{useMemo as ap}from"react";import cl from"clsx";function lp({children:o,className:e,style:t,renderDialogItem:n}){let i=zr(),{state:r}=Bt();return gt.createElement("div",{"data-element-type":"nvl-dialog-list",className:cl("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>gt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},gt.createElement(cp,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?gt.createElement(_t,{className:"nvl-character-name font-bold mr-2"}):null,texts:gt.createElement(dn,{className:"nvl-dialog-text"})}):o?gt.Children.map(o,l=>gt.isValidElement(l)?gt.cloneElement(l,{entry:s,index:a}):l):gt.createElement(ul,{entry:s,index:a})))))}function ul({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??gt.createElement(dn,{className:"nvl-dialog-text"});return gt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:cl("nvl-dialog-item",t),style:n},r&>.createElement(_t,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function cp({entry:o,children:e}){let n=R().getLiveGame().getGameState(),i=ap(()=>o.sentence.evaluate(we.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",l=vo({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return gt.createElement(Tn,{value:l},e)}import Mo from"react";import{createPortal as up}from"react-dom";var Qr=Mo.createContext(null),pp={Portal:()=>null,measure:()=>null,container:null};function dp(){let o=Mo.useContext(Qr);return Mo.useMemo(()=>{if(!o)return pp;let e=t=>{let n=o.offsetWidth;return!n||!t.width?1:t.width/n};return{container:o,Portal:({children:t})=>up(Mo.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,l=r.width/i,c=r.height/i;return{left:s,top:a,width:l,height:c,right:s+l,bottom:a+c}}}},[o])}import{useEffect as mp}from"react";function fp(o){let e=R();mp(()=>{if(!o)return;let t=e.getLiveGame().getGameState();if(t)return t.suspendAdvance()},[o,e])}function dl({state:o}){let e=R(),t=Vt(),n=Xr(null),i=Xr(null),r=Xr(!1),[s]=pn(re.Preferences.skipDelay),[a]=pn(re.Preferences.skipInterval),[l]=bn("skipAction");return gp(()=>{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=f=>{if(!o.isAdvanceSuspended()&&e.keyMap.match("skipAction",f.key)&&e.preference.getPreference(re.Preferences.skip)&&!r.current){o.logger.verbose("KeyEventAnnouncer","Skipping");let h=()=>{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?h():i.current=setTimeout(h,s)}},p=f=>{e.keyMap.match("skipAction",f.key)&&u()};if(e.config.useWindowListener){let f=e.getLiveGame().onWindowEvent("keydown",d).cancel,h=e.getLiveGame().onWindowEvent("keyup",p).cancel;return()=>{u(),f(),h()}}else{let f=e.getLiveGame().onPlayerEvent("keydown",d).cancel,h=e.getLiveGame().onPlayerEvent("keyup",p).cancel;return()=>{u(),f(),h()}}},[t,s,a,l]),pl.createElement(pl.Fragment,null)}import ml,{useEffect as yp}from"react";function vp(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var fl=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],Sp=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]','[data-element-type="interactive-word"]','[data-element-type="dialog-overlay"]'];function Tp(o,e){return!o||e&&fl.some(t=>!!o.closest(t))?!1:[...Sp,...fl].some(t=>!!o.closest(t))}function hl(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 gl({state:o}){let e=R();return yp(()=>{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)||!hl(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!hl(i,s))||vp(r)||Tp(r,o.isNvlMode())||o.isAdvanceSuspended()||(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]),ml.createElement(ml.Fragment,null)}import{useEffect as yl}from"react";function Jr({gameState:o}){let e=o.audioManager,[t,n]=pn("globalVolume");return yl(()=>{n(e.getGlobalVolume())},[]),yl(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as No,useRef as bp}from"react";function vl(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 Sl({state:o}){let{preloaded:e,cacheManager:t}=Wt(),n=R(),i=bp(new Set),[r]=le(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),l=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,c=n.getLiveGame().story;function u(){o.logger.debug(s,"Preload unmounted"),e.events.emit($e.EventTypes["event:preloaded.unmount"])}return No(()=>o.events.on(L.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),No(()=>{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")),!c||!a)return c?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=vl(a),f=new kn(n.config.preloadConcurrency,0),h=new kn(n.config.preloadConcurrency,n.config.preloadDelay),m=o.logger.group(s,!0),v=!1;o.logger.debug(s,"preloading:",p,a);let A=(g,y,T,C)=>{y.forEach((k,b)=>{if(t.has(k)||t.isPreloading(k)){o.logger.debug(s,`Image already loaded (${T} ${b+1}/${y.length})`,k);return}g.addTask(()=>new Promise(x=>{t.preload(o,k,{retainDecoded:C}).onFinished(()=>{o.logger.debug(s,`Image loaded (${T} ${b+1}/${y.length})`,k),x()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${T} ${b+1}/${y.length})`,k),x()})}))})};A(f,p.critical,"first scene",!0),A(h,p.lookAhead,"look-ahead",!1);for(let g of p.criticalAudio)o.audioManager.preload(g);return m.end(),f.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 h.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,c]),No(()=>{i.current.clear()},[a]),No(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!c){o.logger.weakWarn(s,"Story not found, skipping preload");return}let d=performance.now(),p=n.getLiveGame().getAllPredictableActions(c,l,n.config.maxPreloadActions).map(g=>Re.getPreloadableSrc(c,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 h=Re.catSrc([...i.current,...p]),m=new kn(n.config.preloadConcurrency,n.config.preloadDelay),v=[],A=o.logger.group(s);o.logger.debug(s,"preloading:",h);for(let g of h.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 (${h.image.indexOf(g)+1}/${h.image.length})`,y);continue}m.addTask(()=>new Promise(T=>{t.preload(o,y).onFinished(()=>{o.logger.debug(s,`Image loaded (${h.image.indexOf(g)+1}/${h.image.length})`,y),T()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${h.image.indexOf(g)+1}/${h.image.length})`,y),T()})}))}}A.end(),m.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(v)})},[l,c]),null}import gi from"react";import Ho from"react";import Zr,{useEffect as _r,useLayoutEffect as es,useRef as Go,useState as ts}from"react";function Kt({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:l,companionRefs:c}){let[u,d]=ts(null),[p,f]=ts(null),h=Go(null),m=Zr.useRef(null),[v]=ts(()=>new Ri("displayable.refGroup")),A=Go(v.next()),g=Go(At()),T=R().getLiveGame().getGameState(),C=typeof a=="function"?a(u):a,[k]=le([p,u,g]);_r(()=>T.events.depends([T.events.on(L.EventTypes["event:state.player.skip"],$t)]).cancel,[p,u,g]),es(()=>{if(Q(),!u)return;if(g.current.some(([N])=>!N.current))throw new E("Displayable: Trying to access transition groups before they are mounted");let{controller:H,task:G}=u,D=N=>{g.current.forEach(([Ee],$)=>{let se=G.resolve[$],me=typeof se=="function"?se:se.resolver;if(!me)throw new E(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${$}])`);let De=me(...N),We=j(C[$]||C[C.length-1]||{},De);ve(Ee,l?l(We):We)})},B=H.onUpdate(D);D(G.animations.map(N=>N.start));let he=!1;return Promise.all(g.current.map(([N])=>{let Ee=N.current;return Ee?.waitForLoad?Ee.waitForLoad():Promise.resolve()})).then(()=>{he||H.start()}),()=>{he=!0,B.cancel()}},[u]),_r(()=>{if(!m.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),es(()=>{let H=e.toStyle(T,i);return Object.assign(m.current.style,H),O(),T.logger.debug("Displayable","Initial style applied",m.current,H),je(),()=>{Se()}},[]);let b=Go(()=>{});b.current=()=>{u||!m.current||(Q(),!(p||h.current)&&(Object.assign(m.current.style,e.toStyle(T,i)),O()))},es(()=>{h.current&&!o._getLoop()&&Se(),b.current()});let{ratio:x}=ye();_r(()=>x.onUpdate(()=>{b.current(),requestAnimationFrame(()=>b.current())}),[x]);function O(){if(c)for(let{ref:H,project:G}of c)H.current&&Object.assign(H.current.style,G(e.get()))}function Q(){let H=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(([G])=>!G.current)||g.current.forEach(([G],D)=>{ve(G,H[D]||H[H.length-1]||{})})}function W(H){T.logger.debug("Displayable","Transform applied",e.toStyle(T,i),m.current),k(),r?.(H)}function ve(H,G){if(!H.current)throw new E("Displayable: Trying to assign properties to unmounted element");to(H.current,G,l)}function Se(){h.current&&(h.current.stop(),h.current=null,T.logger.debug("Displayable","Loop stopped",o))}function je(){let H=o._getLoop();if(!H){Se();return}h.current||Ge(H.transform,H.options)}function Ge(H,G){p&&(p.abort(),f(null)),Se(),m.current&&(h.current=H.startLoop(e,{gameState:T,ref:m,overwrites:i,companionRefs:c},G))}function yt(H,G){return ct(new Z({},{duration:H?.duration??0,ease:H?.ease??"linear"}),G)}function ct(H,G){p&&(p.abort(),f(null)),Se();let D=H.animate(e,{gameState:T,ref:m,overwrites:i,companionRefs:c}),B=new ke(D);return T.timelines.attachTimeline(B),D.onSkipControllerRegister(he=>{he.onAbort(()=>{B.abort(),f(null)})}),f(D),D.then(()=>{f(null),W(H),G(),je()}),B}function pe(H,G){u&&u.controller.complete();let D=H.createTask(T),B=H.requestAnimations(D.animations),he=new S().registerSkipController(new F(B.cancel)),N=new ke(he);he.skipController.onAbort(()=>{B.cancel()}),B.onCanceled(()=>{N.abort(),d(null),T.logger.debug("Displayable","Transition cancelled",H)}),B.onComplete(()=>{vt(),d(null),s?.(H),G(),he.resolve()}),T.timelines.attachTimeline(N),d({task:D,controller:B,transition:H,resolve:G});let Ee;if(g.current=D.resolve.map($=>{let se=Zr.createRef(),me=typeof $=="function"?void 0:$.key;if(!me)return[se,v.next()];if(me==="target")return Ee=v.next(),[se,Ee];if(me==="current")return[se,A.current];throw new E("Displayable: Invalid key type")}),!Ee)throw new E("Displayable: No target key found");return A.current=Ee,N}function it(H){return T.logger.debug("initDisplayable",o),ct(Z.immediate(e.get()),H)}function $t(){t&&p&&(p.abort(),f(null),T.logger.debug("transform skipped")),n&&u&&(u.controller.complete(),T.logger.debug("transition skipped"))}function At(){return[[Zr.createRef(),A.current]]}function vt(){g.current.forEach(([H])=>{H.current=null}),g.current=At()}return{transformRef:m,transitionRefs:g.current,transitionTask:u,initDisplayable:it,applyTransform:ct,applyTransition:pe,applyLoop:Ge,stopLoop:yt,updateStyleSync:Q,flush:k,deps:[p,u,g]}}import{useEffect as Ap}from"react";function Tt(o,e,t=[]){let i=R().getLiveGame().getGameState();return Ap(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function ns({state:o,text:e}){let{ratio:t}=ye(),[n]=le(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyLoop:l,stopLoop:c,applyTransition:u,updateStyleSync:d,deps:p}=Kt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:f=>({width:"fit-content",transform:Z.propToCSSTransform(o,f,{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 Tt(e,{initDisplayable:s,applyTransform:a,applyLoop:l,stopLoop:c,applyTransition:u,flush:n,updateStyleSync:d},[...p]),Ho.createElement(Ut.Div,{"data-element-type":"text"},Ho.createElement(Ut.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([f,h])=>Ho.createElement("span",{key:h,ref:f,className:e.config.className},Ho.createElement("span",null,e.state.text)))))}import Lt,{forwardRef as xp,useCallback as bl,useImperativeHandle as wp,useRef as Fo,useState as Al}from"react";import Oo,{useEffect as is,useRef as Un,forwardRef as Cp}from"react";var Tl=Cp(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=Un(null),{ratio:a}=ye(),[l,c]=Oo.useState(0),[u,d]=Oo.useState(0),p=Un(null),f=Un(null),h=R(),m=Un(!1),v=Un(null),A=Un(null);Oo.useImperativeHandle(r,()=>s.current,[]),is(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>{let C=()=>{let k=s.current;return!k||typeof k.decode!="function"?Promise.resolve():k.decode().catch(()=>{})};return m.current?C():(v.current||(v.current=new Promise(k=>{A.current=k})),v.current.then(C))},configurable:!0}})},[]),is(()=>(g(),a.onUpdate(g)),[o]),is(()=>{let C=new MutationObserver(k=>{k.forEach(b=>{b.type==="attributes"&&b.attributeName==="src"&&s.current&&g()})});return s.current&&C.observe(s.current,{attributes:!0}),()=>{C.disconnect()}},[o]);function g(){if(s.current&&s.current.naturalWidth){let C,k,b;if(s.current.naturalWidth*s.current.naturalHeight===1)C=a.state.width,k=a.state.height,b=`${C} / ${k}`;else{let W=t?h.config.width/s.current.naturalWidth:1;C=s.current.naturalWidth*a.state.scale*W,k=s.current.naturalHeight*a.state.scale*W,b="auto"}let x=p.current,O=!x||x.w!==C||x.h!==k||x.ar!==b,Q=!!o&&f.current!==o;if(!O&&!Q)return;O&&(p.current={w:C,h:k,ar:b},c(C),d(k),s.current.style.aspectRatio=b),o&&(f.current=o,o(C,k))}}function y(){g(),m.current=!0,A.current&&(A.current(),A.current=null,v.current=null),e&&e()}function T(){m.current=!0,A.current&&(A.current(),A.current=null,v.current=null)}return Oo.createElement("img",{ref:s,onLoad:y,onError:T,width:l,height:u,alt:"",src:n,style:i})});Tl.displayName="AspectScaleImage";var Vo=Tl;import Cl from"clsx";import{motion as kp}from"motion/react";var Pp={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},xl=xp(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=Fo(null),a=Fo([]),l=o.findIndex(c=>c!==null);return wp(r,()=>Object.assign(s.current,{isLoaded:()=>a.current.every(c=>!c?.isLoaded||c.isLoaded()),waitForLoad:()=>Promise.all(a.current.map(c=>c?.waitForLoad?c.waitForLoad():Promise.resolve())).then(()=>{})}),[]),Lt.createElement("div",{ref:s},o.map((c,u)=>c===null?null:Lt.createElement(Vo,{key:"layer-"+u,ref:d=>{a.current[u]=d},src:t(c),style:Pp,autoFit:e,onSizeChanged:u===l?n:void 0,onLoad:u===l?i:void 0})))});xl.displayName="LayerStack";function Ep(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 Dp(o){return I.isStaticSrc(o)?o.state.currentSrc:I.getSrcURL(o)??void 0}var Lp={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function Rp({image:o,state:e}){let[t]=Al(()=>new X),[n,i]=Al([]),{cacheManager:r}=Wt(),s=Fo([]),a=Fo(null),l=I.isLayeredSrc(o)?I.getSrcURLs(o):null;function c(b){return!P.isDataURI(b)&&!r.has(b)&&!r.isPreloading(b)&&!s.current.includes(b)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${b}".
|
|
53
|
+
`&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function xu(o,e,t){return t||(o!==void 0?me.formatStaticWord(o):e?e.text.flatMap(n=>typeof n.text=="function"?[]:new te(n.text,n.config)):[])}function wu(o,e,t){let n=Math.max(0,e??t);return typeof o=="object"?{enabled:o.enabled??!0,delay:Math.max(0,o.delay??n)}:{enabled:o??!0,delay:n}}function tl(o,e){let t=Math.max(.01,o),n=Math.max(.01,e);return 1e3/(t*n)}function Lo(o){return o===void 0?void 0:Rn(o)}function ol(o){return typeof o.tag2=="number"?o.tag2>=o.full.length-1:o.text.length>=o.full.length}function Fr({word:o,vertical:e,tateChuYoko:t,done:n,style:i,renderer:r}){let s=o.config.ruby?ge.createElement("ruby",{className:"align-bottom inline-block"},ge.createElement("rt",{className:"block text-center"},o.config.ruby),Gr(o.text,e,t)):Gr(o.text,e,t);return r?ge.createElement(r,{text:o.text,fullText:o.full,revealed:ol(o),done:n,style:i,config:o.config,data:o.config.data},s):s}function ku(o,e){return!!e&&ol(o)}function Vr({defaultColor:o,className:e,style:t,dialog:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,writingMode:l,textOrientation:c,tateChuYoko:u,autoFit:d,autoFitMinFontSize:p,...h}){let f=I(),m=f.getLiveGame().getGameState(),v=nl(null),[C,g]=Hr(()=>n&&!n.config.useTypeEffect?Do(n.config.evaluatedWords):[]),[y,T]=le();if(!n)throw new Error("Dialog state is required");wn(()=>{if(!(!n.config.action.sentence||v.current))return m.logger.info("Initializing the sentence",n,v.current),m.schedule(({onCleanup:Z})=>{if(!n.config.useTypeEffect){qa(n.config.evaluatedWords,n.config.firedTextEvents??new Set,m),n.dispatchComplete();return}g([]),v.current=q(),y(),v.current.onComplete(()=>{n.dispatchComplete()}),Z(()=>{v.current?.timeline?.abort()})},0)},[]),wn(()=>n.events.depends([n.events.on(Ne.Events.requestComplete,()=>{v.current?.interact()}),n.events.on(Ne.Events.forceSkip,()=>{n.isEnded()||v.current?.forceSkip()})]).cancel,[n,T]),wn(()=>n.onFlush(()=>{y()}).cancel,[n]),wn(()=>f.preference.events.depends([f.preference.onPreferenceChange(se.Preferences.gameSpeed,()=>{v.current?.update()}),f.preference.onPreferenceChange(se.Preferences.autoForward,()=>{v.current?.update()}),f.preference.onPreferenceChange(se.Preferences.cps,()=>{v.current?.update()})]).cancel,[]);let A=!!d,{containerRef:w,mirrorRef:b,scale:x}=el({enabled:A,minFontSize:p??Qa,vertical:yi(l),signature:[n.config.action.id,i,r,a,l,c,String(u)].join(" ")}),F=Cu(()=>A?Do(n.config.evaluatedWords):[],[A,n]);function q(){let Z=new S,De=new ke(Z).setGuard(m.guard),Ae=new Set,N=n.config.firedTextEvents??new Set,R=new Set,D=new Set,W=Or(n.config.evaluatedWords),ne=null,M=[],fe=[],Ce=()=>{M.forEach(Ue=>Ue()),M.length=0},ot=()=>{if(fe.length!==0)return{done:!1,value:fe.shift()};let{done:Ue,value:Je}=W.next();return{done:Ue,value:Je}},Ve=Ue=>{let Je=rn=>{Ue(rn),R.delete(Je)};return R.add(Je),{cancel:()=>{R.delete(Je)}}},En=Ue=>{il(g,Ue)},Yn=(Ue=!1)=>{let Je=!1;for(;!Je;){let{done:rn,value:_e}=ot();if(rn){Je=!0;break}if(Ke.isPause(_e)){if(Ue)continue;Je=!0,fe.push(_e);break}else lt.isTextEvent(_e)?ko(_e,N,m):_e===`
|
|
54
|
+
`?g(rt=>[...rt,_e]):typeof _e=="object"&&"text"in _e&&!Ae.has(_e)&&(Ae.add(_e),En(_e))}ne&&!ne.isSettled()?ne.abort():(D.forEach(rn=>rn()),Z.resolve())};return m.schedule(async Ue=>{let Je=!1,rn=!1;for(;!Je;){let{done:_e,value:rt}=ot();if(_e){Je=rn=!0;break}if(lt.isTextEvent(rt)){ko(rt,N,m);continue}let Ii=new S;if(m.timelines.attachTimeline(Ii),Ii.registerSkipController(new V(()=>{Ce(),Je=!0,Ue.retry()})),Ii.onSettled(()=>{Ce()}),ne=Ii,Ke.isPause(rt)){let Mi=Ke.from(rt),Ni=f.preference.getPreference(se.Preferences.gameSpeed);if(Mi.config.duration){let Gi=Mi.config.duration/Ni;await Ki(Gi)}else{let Gi=f.preference.getPreference(se.Preferences.autoForward),Hi=S.race([S.create(mc=>{let fc=Ve(hc=>{hc(),mc.resolve()});M.push(()=>fc.cancel())}),...Gi?[S.delay(f.config.autoForwardDefaultPause/Ni)]:[]]);m.timelines.attachTimeline(Hi),await S.wait(Hi)}}else{if(rt!==`
|
|
55
|
+
`&&Ae.has(rt))continue;Ae.add(rt),En(rt);let{gameSpeed:Mi,cps:Ni}=f.preference.getPreferences(),Hi=1e3/((typeof rt=="object"&&"cps"in rt&&rt.cps!==void 0?rt.cps:Ni)*Mi);await Ki(Hi)}}rn&&(D.forEach(_e=>_e()),Z.resolve())},0),{getToken:()=>Z,interact:()=>{let Ue=!1;R.forEach(Je=>Je(()=>Ue=!0)),!Ue&&Yn()},update:()=>{ne&&ne.abort()},forceSkip:()=>{Yn(!0)},timeline:De,onComplete:Ue=>(D.add(Ue),{cancel:()=>{D.delete(Ue)}})}}let Q=n.config.action.sentence;if(!Q)return null;let Ee=s??"bold",je=Q.config.fontSize??i,Tt={fontWeight:Q.config.bold?Ee:r,fontSize:Rr(je,x)??Za(x),color:Lo(Q.config.color??o),fontFamily:Q.config.fontFamily??a,fontStyle:Q.config.italic?"italic":void 0},pt=(Z,De=x)=>({fontWeight:Z.config.bold||Q.config.bold?Ee:r,fontSize:Rr(Z.config.fontSize??je,De),color:Lo(Z.config.color??Q.config.color??o),fontFamily:Z.config.fontFamily??Q.config.fontFamily??a,fontStyle:Z.config.italic??Q.config.italic?"italic":void 0}),qt=yi(l),dt=n.isEnded(),be=(Z,De)=>{if(Z===`
|
|
56
|
+
`)return ge.createElement("br",{key:De});let Ae=pt(Z),N=Lr(Z.config.render),R=ku(Z,N);return ge.createElement(Bt.Span,{tag:`say.word.${De}`,key:De,"data-element-type":R?"interactive-word":void 0,onClick:R?D=>D.stopPropagation():void 0,style:{...Ae,...Eo(),...Jn(f.config.app.debug,{outline:"1px dashed red"})},className:vi("inline-block",Z.config.className)},ge.createElement(Fr,{word:Z,vertical:qt,tateChuYoko:u,done:dt,style:Ae,renderer:N}))},bt=(Z,De)=>{if(Z===`
|
|
57
|
+
`)return ge.createElement("br",{key:De});let Ae=pt(Z,_a);return ge.createElement("span",{key:De,style:{...Ae,...Eo()},className:vi("inline-block",Z.config.className)},ge.createElement(Fr,{word:Z,vertical:qt,tateChuYoko:u,done:!1,style:Ae,renderer:null}))};return ge.createElement("div",{...h,ref:w,className:vi("whitespace-pre-wrap",e),style:{...Jn(A,{position:"relative"}),...Tt,...Nr(l,c),...t}},C.map(be),A?ge.createElement("div",{ref:b,"aria-hidden":!0,style:{position:"absolute",...qt?{top:0,bottom:0,left:0,width:"auto"}:{left:0,right:0,top:0,height:"auto"},padding:"inherit",boxSizing:"border-box",visibility:"hidden",pointerEvents:"none"}},F.map(bt)):null)}function Pu({text:o,sentence:e,words:t,useTypeEffect:n=!0,loop:i=!0,restartDelay:r,cps:s,gameSpeed:a,pauseDuration:l,defaultColor:c,className:u,style:d,fontSize:p,fontWeight:h,fontWeightBold:f,fontFamily:m,writingMode:v,textOrientation:C,tateChuYoko:g,onCompleted:y,...T}){let A=Na(),[,w]=Hr(0),b=A?.config??se.DefaultConfig,x=A?.preference.getPreferences()??se.DefaultPreference,F=s??x.cps,q=a??x.gameSpeed,Q=l??b.autoForwardDefaultPause,Ee=r??b.autoForwardDefaultPause,je=ge.useMemo(()=>xu(o,e,t),[o,e,t]),Tt=ge.useMemo(()=>wu(i,r,Ee),[i,r,Ee]),pt=nl(y),[qt,dt]=Hr(()=>n?[]:Do(je));wn(()=>{if(A)return A.preference.onPreferenceChange(()=>{w(R=>R+1)}).cancel},[A]),wn(()=>{pt.current=y},[y]),wn(()=>{let R=!1,D=[],W=Math.max(.01,q),ne=Ce=>new Promise(ot=>{let Ve=setTimeout(ot,Math.max(0,Ce));D.push(Ve)}),M=()=>{R||pt.current?.()};return n?je.length===0?(dt([]),()=>{R=!0}):((async()=>{do{let Ce=Or(je);for(dt([]);!R;){let{done:ot,value:Ve}=Ce.next();if(ot)break;if(Ke.isPause(Ve)){let En=Ke.from(Ve);await ne((En.config.duration??Q)/W)}else{if(lt.isTextEvent(Ve))continue;il(dt,Ve),Ve===`
|
|
58
|
+
`?await ne(tl(F,q)):await ne(tl(Ve.cps??F,q))}}if(R)return;M(),Tt.enabled&&await ne(Tt.delay)}while(!R&&Tt.enabled)})(),()=>{R=!0,D.forEach(Ce=>clearTimeout(Ce))}):(dt(Do(je)),M(),()=>{R=!0})},[je,n,Tt,F,q,Q]);let be=e?.config,bt=f??"bold",Z={fontWeight:be?.bold?bt:h,fontSize:be?.fontSize??p,color:Lo(be?.color??c),fontFamily:be?.fontFamily??m,fontStyle:be?.italic?"italic":void 0},De=R=>({fontWeight:R.config.bold||be?.bold?bt:h,fontSize:R.config.fontSize??be?.fontSize??p,color:Lo(R.config.color??be?.color??c),fontFamily:R.config.fontFamily??be?.fontFamily??m,fontStyle:R.config.italic??be?.italic?"italic":void 0}),Ae=yi(v),N=(R,D)=>{if(R===`
|
|
59
|
+
`)return ge.createElement("br",{key:D});let W=De(R);return ge.createElement("span",{key:D,style:{...W,...Eo()},className:vi("inline-block",R.config.className)},ge.createElement(Fr,{word:R,vertical:Ae,tateChuYoko:g,done:!1,style:W,renderer:Lr(R.config.render)}))};return ge.createElement("div",{...T,className:vi("whitespace-pre-wrap",u),style:{...Z,...Nr(v,C),...d}},qt.map(N))}function rl(o){return ge.createElement(Vr,{...o,key:o.dialog?.config.action.id})}function Eu({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 ge.createElement(Vr,{...r,dialog:s,key:s.config.action.id})}function Du(o){let e=Lt();return ge.createElement(Vr,{...o,dialog:e,key:e.config.action.id})}function hn(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?ge.createElement(Eu,{...o}):ge.createElement(Du,{...o})}var Lu=hn;import Io,{useEffect as Ru,useLayoutEffect as Iu,useMemo as al,useRef as Mu,useState as Nu}from"react";import Ro from"react";var Ur=Ro.createContext(null);function Wr(){let o=Ro.useContext(Ur);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var Br=Ro.createContext(null);function sl(){let o=Ro.useContext(Br);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function Mo({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let l=Mu(null),{register:c,unregister:u,getIndex:d}=sl(),[p,h]=Nu(-1),{choose:f,evaluated:m,gameState:v}=Wr(),C=p===-1?null:m[p],g=al(()=>we.getCtx({gameState:v}),[v]),{hidden:y,disabled:T}=al(()=>{if(!C)return{hidden:!1,disabled:!1};let b=C.config.hidden?.evaluate(g)?.value??!1,x=!b&&(C.config.disabled?.evaluate(g)?.value??!1);return{hidden:b,disabled:x}},[C,g]);Iu(()=>{if(!l.current)return;let b=l;c(b);let x=d(b);return h(x),l.current.dataset.index=x.toString(),()=>u(b)},[c,u,d]),Ru(()=>{if(!t)return;let b=x=>{x.key.toLowerCase()===t.toLowerCase()&&!x.ctrlKey&&!x.metaKey&&(x.preventDefault(),x.stopPropagation(),A())};return window.addEventListener("keydown",b,!0),()=>{window.removeEventListener("keydown",b,!0)}},[t]);function A(){if(p===-1||!m[p]||y||T)return;let b=m[p];f({...b,evaluated:te.getText(b.words||[])})}let w=C&&!y;return Io.createElement(Io.Fragment,null,Io.createElement("button",{className:o,style:{...e,display:w?e?.display??void 0:"none"},onClick:A,ref:l,disabled:T},w&&Io.createElement(rl,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Ne({useTypeEffect:!1,action:{sentence:C.prompt,words:C.words,character:null},gameState:v,evaluatedWords:C.words})})))}import No from"react";import{AnimatePresence as Gu}from"motion/react";function Go({children:o,...e}){let t=Gu;return No.createElement(No.Fragment,null,No.createElement("div",{...e},No.createElement(t,null,o)))}import ll from"react";function tn({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=ll.useContext(Cn),l=e??o?.character??a?.config.action.character??null,c=n??l?.config.color,u=i??t??l?.state.name;return ll.createElement("div",{...s,style:{color:c?Rn(c):void 0,...r}},u)}import Ou from"clsx";import Vu from"react";import zr,{createContext as Hu,useContext as Fu,useState as cl}from"react";var kn=class kn{constructor(){this.preloaded=[];this.events=new Y}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 Ho=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 Ys(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,l=[],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}`),l.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=>(l.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 Kr=Hu(null);function ul({children:o}){let e=I(),[t]=cl(()=>new $e),[n]=cl(()=>new Ho(e));return zr.createElement(zr.Fragment,null,zr.createElement(Kr,{value:{preloaded:t,cacheManager:n}},o))}function zt(){if(!Kr)throw new Error("usePreloaded must be used within a PreloadedProvider");return Fu(Kr)}function pl(){let o=Lt(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return Bu(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?G.getSrcURL(s):null,l=s&&G.isTagSrc(s)?[...s.state.currentSrc]:null,c=ya({character:n,sentence:i,portrait:s,currentSrc:a,tags:l,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=Wu(c.source);return{visible:!!u,src:u,character:c.character,portrait:c.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function Uu({className:o,style:e,alt:t,...n}){let i=pl(),{cacheManager:r}=zt();if(!i.visible||!i.src)return null;let s=r.get(i.src)||i.src;return Vu.createElement("img",{...n,"data-element-type":"dialog-avatar",className:Ou("dialog-avatar",o),src:s,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function Wu(o){return o?P.srcToURL(o):null}function Bu(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var $r=Uu;import{useEffect as zu}from"react";function Ku(){let o=Lt(),[e]=le(o.deps),t=te.getText(o.config.evaluatedWords);return zu(()=>o.events.on(Ne.Events.onFlush,()=>{e()}).cancel,[o]),{done:o.isEnded(),text:t,isNarrator:o.config.action.character===null||o.config.action.character.state.name==="",metadata:o.config.action.sentence?.getMetadata()}}import{useCallback as Fo,useEffect as jr,useMemo as $u,useRef as ju,useState as dl}from"react";function qu(){let o=Lt(),[e]=le(o.deps),[t,n]=dl(!0),[i,r]=dl(!0),s=ju(null),a=o.config.gameState,l=o.config.action.sentence,c=l?.config.voiceId??null;jr(()=>o.events.on(Ne.Events.onFlush,()=>{e()}).cancel,[o]);let u=$u(()=>{if(!l)return null;try{return nt.getVoice(a,l)}catch{return null}},[a,l,c,l?.config.voice]);jr(()=>{s.current=null,r(!0)},[l]),jr(()=>{let m=!1,v=null,C=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),C=()=>y(),g=()=>y(),v.once("ended",C),v.once("stop",g));let T=a.events.on(L.EventTypes["event:state.player.lineEnd"],()=>{y()});return()=>{m=!0,T.cancel(),v&&C&&v.off("ended",C),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 C=v instanceof URL?ve.voice(v.toString()):typeof v=="string"?ve.voice(v):v,g=await a.getLiveGame().playSound(C);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(()=>c,[c]),f=Fo(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:d,getVoice:p,getVoiceId:h,getVoiceSrc:f}}import qr,{createContext as rp,useContext as sp,useEffect as hl,useRef as ap}from"react";import{useState as Yu}from"react";function Oo(o){let[e]=Yu(o);return e}import{AnimatePresence as Xu}from"motion/react";var Vo=Xu;import Ai,{createContext as ep,useContext as tp,useEffect as np,useRef as ip}from"react";import{useEffect as Si,useLayoutEffect as Qu}from"react";function Ju(){let o=Ut(),[e]=le();return Si(()=>o.onChange(e).cancel,[]),o.getPathname()}function _u(){let{router:o,path:e}=bi(),[t]=le();return Si(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function Zu(){let o=Ut(),[e]=le();return Si(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Uo(o,e){let t=Ut();Qu(()=>t.onUpdate(()=>o(t)).cancel,e),Si(()=>{o(t)},[])}function Ti(){let o=Ut(),[e]=le();return Si(()=>o.onChange(e).cancel,[]),e}var ml=ep(null);function Ci({children:o,path:e,consumedBy:t}){let i={router:Ut(),path:e,consumedBy:t};return Ai.createElement(ml,{value:i},o)}function bi(){let o=tp(ml);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.
|
|
60
|
+
This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function op({children:o,name:e,propagate:t}){let n=I(),[i]=le(),{path:r,router:s,consumedBy:a}=bi(),l=s.joinPath(r,e),c=Oo(()=>s.createToken(l+"@layout")),u=s.getCurrentPath(),d=ip(!1),p=f=>{d.current=f,i()},h=s.matchPath(u,l);if(Ti(),Uo(f=>{let m=f.matchPath(f.getCurrentPath(),l);if(d.current&&!m){if(!o){p(!1);return}f.registerUnmountingPath(c)}m&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(c),m&&!d.current&&!f.isTransitioning()&&p(!0)},[h,o]),np(()=>{if(!h)return;let f=s.mount(l);return()=>{f.cancel()}},[l,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 Ai.createElement(Ci,{path:l},Ai.createElement(Vo,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(c),p(!1)}},h&&d.current&&o))}function fl({children:o}){return Ti(),Ai.createElement(Ci,{path:mn.rootPath},Ai.createElement(To,{"data-layout-path":mn.rootPath,key:mn.rootPath},o))}var Yr=rp(null);function lp(){return sp(Yr)}function cp({children:o,name:e}){let[t]=le(),{path:n,router:i,consumedBy:r}=bi(),s=lp(),a=s?.name??e,l=a??n+"@default",c=a?i.joinPath(n,a):n,u=Oo(()=>i.createToken(c+"@page")),d=i.getCurrentPath(),p=!a,h=ap(!1),f=g=>{h.current=g,t()},m=p&&i.exactMatch(d,n)||i.exactMatch(d,c);if(r&&r!==l)throw new E("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");Ti(),Uo(g=>{let y=p&&g.exactMatch(g.getCurrentPath(),n)||g.exactMatch(g.getCurrentPath(),c);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]),hl(()=>{if(!m)return;let g=p?i.mountDefaultHandler(c):i.mount(c);return i.emitOnPageMount(),()=>{g.cancel()}},[c,m]),hl(()=>()=>{i.unregisterUnmountingPath(u),f(!1)},[]);let v=qr.createElement(Ci,{path:n,consumedBy:l},qr.createElement(Vo,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),f(!1)}},m&&h.current&&o));return(g=>s?qr.createElement(Yr,{value:{name:null}},g):g)(v)}import Xr,{useCallback as up,useEffect as Qr,useImperativeHandle as pp,useMemo as gl,useRef as Jr,useState as dp}from"react";var mp=50,fp={position:"relative",width:"100%",height:"100%",overflow:"hidden"},yl={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function hp(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function vl(o,e){return e==null?o:Math.max(o,e)}function gp(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 Sl=Xr.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:l,dataAttributes:c,onUpdate:u,children:d},p){let h=Jr(null),[f,m]=dp({...yl,width:"0px",height:"0px"}),v=Jr(u),C=Jr(null);Qr(()=>{v.current=u},[u]);let g=up(()=>{let A=h.current;if(!A)return;let w=A.clientWidth,b=A.clientHeight;if(w<=0||b<=0||e<=0)return;let x=gp(w,b,e),F=vl(x.width,n),q=vl(x.height,i),Q=C.current;(!Q||Q.width!==F||Q.height!==q)&&(C.current={width:F,height:q},m({...yl,width:`${F}px`,height:`${q}px`}));let Ee=t>0?F/t:1;v.current?.({width:F,height:q,scale:Ee,containerWidth:w,containerHeight:b})},[e,t,n,i]),y=gl(()=>js(g,typeof r=="number"?r:mp),[g,r]);Qr(()=>{g()},[g]),Qr(()=>{let A=new ResizeObserver(()=>{y()});h.current&&A.observe(h.current);let w=()=>{y()};return window.addEventListener("resize",w),()=>{A.disconnect(),window.removeEventListener("resize",w)}},[y]),pp(p,()=>({requestUpdate:g}),[g]);let T=gl(()=>hp(c),[c]);return Xr.createElement("div",{id:l,ref:h,style:fp,...T},Xr.createElement("div",{className:s,style:{...f,...a}},d))}),Tl=Sl;function yp(){return I().getLiveGame()}import es from"react";import vp,{createContext as Sp,useContext as Tp,useEffect as bp,useState as bl}from"react";var Ap={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},Al=Sp({state:Ap,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function Kt(){return Tp(Al)}function _r(){let{dialogs:o}=Kt();return o}function Cp(){let{isActive:o}=Kt();return o}function xp(){let{isVisible:o}=Kt();return o}function Zr({children:o}){let t=I().getLiveGame().getGameState(),[n,i]=bl(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=bl(null);bp(()=>{let l=f=>({...f,dialogs:[...f.dialogs]}),c=t.events.on(L.EventTypes["event:state.nvl.enter"],(f,m)=>{i(l(t.getNvlState())),s(m?.showTransition||null)}),u=t.events.on(L.EventTypes["event:state.nvl.exit"],()=>{i(l(t.getNvlState()))}),d=t.events.on(L.EventTypes["event:state.nvl.dialogAppend"],()=>{i(l(t.getNvlState()))}),p=t.events.on(L.EventTypes["event:state.nvl.visibilityChange"],(f,m)=>{i(l(t.getNvlState())),s(m||null)}),h=t.events.on(L.EventTypes["event:state.nvl.change"],f=>{i(l(f))});return()=>{c.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 vp.createElement(Al.Provider,{value:a},o)}import{AnimatePresence as wp,motion as kp}from"motion/react";import Pp from"clsx";function ts({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=Kt(),{ratio:r}=he(),s=I(),a=i?.duration?i.duration/1e3:.3;return es.createElement(wp,null,n&&es.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},es.createElement(kp.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:Pp("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 ns({renderDialogItem:o,dialogs:e}){return Pn.createElement(ts,{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(tn,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=Pn.createElement(hn,{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 St,{useMemo as Ep}from"react";import Cl from"clsx";function Dp({children:o,className:e,style:t,renderDialogItem:n}){let i=_r(),{state:r}=Kt();return St.createElement("div",{"data-element-type":"nvl-dialog-list",className:Cl("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>St.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},St.createElement(Lp,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?St.createElement(tn,{className:"nvl-character-name font-bold mr-2"}):null,texts:St.createElement(hn,{className:"nvl-dialog-text"})}):o?St.Children.map(o,l=>St.isValidElement(l)?St.cloneElement(l,{entry:s,index:a}):l):St.createElement(xl,{entry:s,index:a})))))}function xl({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??St.createElement(hn,{className:"nvl-dialog-text"});return St.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:Cl("nvl-dialog-item",t),style:n},r&&St.createElement(tn,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function Lp({entry:o,children:e}){let n=I().getLiveGame().getGameState(),i=Ep(()=>o.sentence.evaluate(we.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",l=wo({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return St.createElement(Cn,{value:l},e)}import Wo from"react";import{createPortal as Rp}from"react-dom";var is=Wo.createContext(null),Ip={Portal:()=>null,measure:()=>null,container:null};function Mp(){let o=Wo.useContext(is);return Wo.useMemo(()=>{if(!o)return Ip;let e=t=>{let n=o.offsetWidth;return!n||!t.width?1:t.width/n};return{container:o,Portal:({children:t})=>Rp(Wo.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,l=r.width/i,c=r.height/i;return{left:s,top:a,width:l,height:c,right:s+l,bottom:a+c}}}},[o])}import{useEffect as Np}from"react";function Gp(o){let e=I();Np(()=>{if(!o)return;let t=e.getLiveGame().getGameState();if(t)return t.suspendAdvance()},[o,e])}function kl({state:o}){let e=I(),t=Ut(),n=os(null),i=os(null),r=os(!1),[s]=fn(se.Preferences.skipDelay),[a]=fn(se.Preferences.skipInterval),[l]=xn("skipAction");return Fp(()=>{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(se.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,l]),wl.createElement(wl.Fragment,null)}import Pl,{useEffect as Op}from"react";function Vp(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var El=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],Up=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]','[data-element-type="interactive-word"]','[data-element-type="dialog-overlay"]'];function Wp(o,e){return!o||e&&El.some(t=>!!o.closest(t))?!1:[...Up,...El].some(t=>!!o.closest(t))}function Dl(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 Ll({state:o}){let e=I();return Op(()=>{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)||!Dl(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!Dl(i,s))||Vp(r)||Wp(r,o.isNvlMode())||o.isAdvanceSuspended()||(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]),Pl.createElement(Pl.Fragment,null)}import{useEffect as Rl}from"react";function rs({gameState:o}){let e=o.audioManager,[t,n]=fn("globalVolume");return Rl(()=>{n(e.getGlobalVolume())},[]),Rl(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as Bo,useRef as Bp}from"react";function Il(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 Ml({state:o}){let{preloaded:e,cacheManager:t}=zt(),n=I(),i=Bp(new Set),[r]=le(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),l=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,c=n.getLiveGame().story;function u(){o.logger.debug(s,"Preload unmounted"),e.events.emit($e.EventTypes["event:preloaded.unmount"])}return Bo(()=>o.events.on(L.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),Bo(()=>{if(typeof fetch>"u")return e.events.emit($e.EventTypes["event:preloaded.complete"]),e.events.emit($e.EventTypes["event:preloaded.ready"]),o.logger.warn(s,"Fetch is not supported in this environment, skipping preload"),u;if(!n.config.preloadAllImages)return e.events.emit($e.EventTypes["event:preloaded.complete"]),e.events.emit($e.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),u;if(n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(s,"Cache cleared")),!c||!a)return c?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=Il(a),h=new Ln(n.config.preloadConcurrency,0),f=new Ln(n.config.preloadConcurrency,n.config.preloadDelay),m=o.logger.group(s,!0),v=!1;o.logger.debug(s,"preloading:",p,a);let C=(g,y,T,A)=>{y.forEach((w,b)=>{if(t.has(w)||t.isPreloading(w)){o.logger.debug(s,`Image already loaded (${T} ${b+1}/${y.length})`,w);return}g.addTask(()=>new Promise(x=>{t.preload(o,w,{retainDecoded:A}).onFinished(()=>{o.logger.debug(s,`Image loaded (${T} ${b+1}/${y.length})`,w),x()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${T} ${b+1}/${y.length})`,w),x()})}))})};C(h,p.critical,"first scene",!0),C(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,c]),Bo(()=>{i.current.clear()},[a]),Bo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!c){o.logger.weakWarn(s,"Story not found, skipping preload");return}let d=performance.now(),p=n.getLiveGame().getAllPredictableActions(c,l,n.config.maxPreloadActions).map(g=>Re.getPreloadableSrc(c,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 Ln(n.config.preloadConcurrency,n.config.preloadDelay),v=[],C=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(T=>{t.preload(o,y).onFinished(()=>{o.logger.debug(s,`Image loaded (${f.image.indexOf(g)+1}/${f.image.length})`,y),T()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${f.image.indexOf(g)+1}/${f.image.length})`,y),T()})}))}}C.end(),m.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(v)})},[l,c]),null}import xi from"react";import Ko from"react";import ss,{useEffect as as,useLayoutEffect as ls,useRef as zo,useState as cs}from"react";function $t({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:l,companionRefs:c}){let[u,d]=cs(null),[p,h]=cs(null),f=zo(null),m=ss.useRef(null),[v]=cs(()=>new Vi("displayable.refGroup")),C=zo(v.next()),g=zo(De()),T=I().getLiveGame().getGameState(),A=typeof a=="function"?a(u):a,[w]=le([p,u,g]);as(()=>T.events.depends([T.events.on(L.EventTypes["event:state.player.skip"],Z)]).cancel,[p,u,g]),ls(()=>{if(q(),!u)return;if(g.current.some(([M])=>!M.current))throw new E("Displayable: Trying to access transition groups before they are mounted");let{controller:N,task:R}=u,D=M=>{g.current.forEach(([fe],Ce)=>{let ot=R.resolve[Ce],Ve=typeof ot=="function"?ot:ot.resolver;if(!Ve)throw new E(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${Ce}])`);let En=Ve(...M),Yn=K(A[Ce]||A[A.length-1]||{},En);Ee(fe,l?l(Yn):Yn)})},W=N.onUpdate(D);D(R.animations.map(M=>M.start));let ne=!1;return Promise.all(g.current.map(([M])=>{let fe=M.current;return fe?.waitForLoad?fe.waitForLoad():Promise.resolve()})).then(()=>{ne||N.start()}),()=>{ne=!0,W.cancel()}},[u]),as(()=>{if(!m.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),ls(()=>{let N=e.toStyle(T,i);return Object.assign(m.current.style,N),F(),T.logger.debug("Displayable","Initial style applied",m.current,N),Tt(),()=>{je()}},[]);let b=zo(()=>{});b.current=()=>{u||!m.current||(q(),!(p||f.current)&&(Object.assign(m.current.style,e.toStyle(T,i)),F()))},ls(()=>{f.current&&!o._getLoop()&&je(),b.current()});let{ratio:x}=he();as(()=>x.onUpdate(()=>{b.current(),requestAnimationFrame(()=>b.current())}),[x]);function F(){if(c)for(let{ref:N,project:R}of c)N.current&&Object.assign(N.current.style,R(e.get()))}function q(){let N=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(([R])=>!R.current)||g.current.forEach(([R],D)=>{Ee(R,N[D]||N[N.length-1]||{})})}function Q(N){T.logger.debug("Displayable","Transform applied",e.toStyle(T,i),m.current),w(),r?.(N)}function Ee(N,R){if(!N.current)throw new E("Displayable: Trying to assign properties to unmounted element");lo(N.current,R,l)}function je(){f.current&&(f.current.stop(),f.current=null,T.logger.debug("Displayable","Loop stopped",o))}function Tt(){let N=o._getLoop();if(!N){je();return}f.current||pt(N.transform,N.options)}function pt(N,R){p&&(p.abort(),h(null)),je(),m.current&&(f.current=N.startLoop(e,{gameState:T,ref:m,overwrites:i,companionRefs:c},R))}function qt(N,R){return dt(new J({},{duration:N?.duration??0,ease:N?.ease??"linear"}),R)}function dt(N,R){p&&(p.abort(),h(null)),je();let D=N.animate(e,{gameState:T,ref:m,overwrites:i,companionRefs:c}),W=new ke(D);return T.timelines.attachTimeline(W),D.onSkipControllerRegister(ne=>{ne.onAbort(()=>{W.abort(),h(null)})}),h(D),D.then(()=>{h(null),Q(N),R(),Tt()}),W}function be(N,R){u&&u.controller.complete();let D=N.createTask(T),W=N.requestAnimations(D.animations),ne=new S().registerSkipController(new V(W.cancel)),M=new ke(ne);ne.skipController.onAbort(()=>{W.cancel()}),W.onCanceled(()=>{M.abort(),d(null),T.logger.debug("Displayable","Transition cancelled",N)}),W.onComplete(()=>{Ae(),d(null),s?.(N),R(),ne.resolve()}),T.timelines.attachTimeline(M),d({task:D,controller:W,transition:N,resolve:R});let fe;if(g.current=D.resolve.map(Ce=>{let ot=ss.createRef(),Ve=typeof Ce=="function"?void 0:Ce.key;if(!Ve)return[ot,v.next()];if(Ve==="target")return fe=v.next(),[ot,fe];if(Ve==="current")return[ot,C.current];throw new E("Displayable: Invalid key type")}),!fe)throw new E("Displayable: No target key found");return C.current=fe,M}function bt(N){return T.logger.debug("initDisplayable",o),dt(J.immediate(e.get()),N)}function Z(){t&&p&&(p.abort(),h(null),T.logger.debug("transform skipped")),n&&u&&(u.controller.complete(),T.logger.debug("transition skipped"))}function De(){return[[ss.createRef(),C.current]]}function Ae(){g.current.forEach(([N])=>{N.current=null}),g.current=De()}return{transformRef:m,transitionRefs:g.current,transitionTask:u,initDisplayable:bt,applyTransform:dt,applyTransition:be,applyLoop:pt,stopLoop:qt,updateStyleSync:q,flush:w,deps:[p,u,g]}}import{useEffect as zp}from"react";function Ct(o,e,t=[]){let i=I().getLiveGame().getGameState();return zp(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function us({state:o,text:e}){let{ratio:t}=he(),[n]=le(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyLoop:l,stopLoop:c,applyTransition:u,updateStyleSync:d,deps:p}=$t({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:h=>({width:"fit-content",transform:J.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 Ct(e,{initDisplayable:s,applyTransform:a,applyLoop:l,stopLoop:c,applyTransition:u,flush:n,updateStyleSync:d},[...p]),Ko.createElement(Bt.Div,{"data-element-type":"text"},Ko.createElement(Bt.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([h,f])=>Ko.createElement("span",{key:f,ref:h,className:e.config.className},Ko.createElement("span",null,e.state.text)))))}import It,{forwardRef as $p,useCallback as Gl,useImperativeHandle as jp,useRef as qo,useState as Hl}from"react";import $o,{useEffect as ps,useRef as Kn,forwardRef as Kp}from"react";var Nl=Kp(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=Kn(null),{ratio:a}=he(),[l,c]=$o.useState(0),[u,d]=$o.useState(0),p=Kn(null),h=Kn(null),f=I(),m=Kn(!1),v=Kn(null),C=Kn(null);$o.useImperativeHandle(r,()=>s.current,[]),ps(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>{let A=()=>{let w=s.current;return!w||typeof w.decode!="function"?Promise.resolve():w.decode().catch(()=>{})};return m.current?A():(v.current||(v.current=new Promise(w=>{C.current=w})),v.current.then(A))},configurable:!0}})},[]),ps(()=>(g(),a.onUpdate(g)),[o]),ps(()=>{let A=new MutationObserver(w=>{w.forEach(b=>{b.type==="attributes"&&b.attributeName==="src"&&s.current&&g()})});return s.current&&A.observe(s.current,{attributes:!0}),()=>{A.disconnect()}},[o]);function g(){if(s.current&&s.current.naturalWidth){let A,w,b;if(s.current.naturalWidth*s.current.naturalHeight===1)A=a.state.width,w=a.state.height,b=`${A} / ${w}`;else{let Q=t?f.config.width/s.current.naturalWidth:1;A=s.current.naturalWidth*a.state.scale*Q,w=s.current.naturalHeight*a.state.scale*Q,b="auto"}let x=p.current,F=!x||x.w!==A||x.h!==w||x.ar!==b,q=!!o&&h.current!==o;if(!F&&!q)return;F&&(p.current={w:A,h:w,ar:b},c(A),d(w),s.current.style.aspectRatio=b),o&&(h.current=o,o(A,w))}}function y(){g(),m.current=!0,C.current&&(C.current(),C.current=null,v.current=null),e&&e()}function T(){m.current=!0,C.current&&(C.current(),C.current=null,v.current=null)}return $o.createElement("img",{ref:s,onLoad:y,onError:T,width:l,height:u,alt:"",src:n,style:i})});Nl.displayName="AspectScaleImage";var jo=Nl;import Fl from"clsx";import{motion as qp}from"motion/react";var Yp={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},Ol=$p(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=qo(null),a=qo([]),l=o.findIndex(c=>c!==null);return jp(r,()=>Object.assign(s.current,{isLoaded:()=>a.current.every(c=>!c?.isLoaded||c.isLoaded()),waitForLoad:()=>Promise.all(a.current.map(c=>c?.waitForLoad?c.waitForLoad():Promise.resolve())).then(()=>{})}),[]),It.createElement("div",{ref:s},o.map((c,u)=>c===null?null:It.createElement(jo,{key:"layer-"+u,ref:d=>{a.current[u]=d},src:t(c),style:Yp,autoFit:e,onSizeChanged:u===l?n:void 0,onLoad:u===l?i:void 0})))});Ol.displayName="LayerStack";function Xp(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 Qp(o){return G.isStaticSrc(o)?o.state.currentSrc:G.getSrcURL(o)??void 0}var Jp={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function _p({image:o,state:e}){let[t]=Hl(()=>new Y),[n,i]=Hl([]),{cacheManager:r}=zt(),s=qo([]),a=qo(null),l=G.isLayeredSrc(o)?G.getSrcURLs(o):null;function c(b){return!P.isDataURI(b)&&!r.has(b)&&!r.isPreloading(b)&&!s.current.includes(b)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${b}".
|
|
58
61
|
This may be caused by complicated image action behavior that cannot be predicted.
|
|
59
|
-
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(b)),r.get(b)||b}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:f,applyTransition:h,applyTransform:m,applyLoop:v,stopLoop:A,updateStyleSync:g,flush:y,deps:T}=Kt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:b=>{if(l)return(b?b.task.resolve:[null]).map(Q=>Q&&typeof Q=="function"?{style:Lp}:{style:Ep(o.state.darkness)});let x=b?b.transition._getCurrentSrc():Dp(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):I.DefaultImagePlaceholder},{style:{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none",filter:"brightness(1)"}}]},propOverwrite:b=>b.src?{...b,src:c(b.src)}:b});Tt(o,{createWearable:b=>{i(x=>[...x,b])},disposeWearable:b=>{i(x=>x.filter(O=>O.getId()!==b.getId()))},initDisplayable:f,applyTransform:m,applyLoop:v,stopLoop:A,applyTransition:h,events:t,updateStyleSync:g,flush:y},[...T]);let C=bl((b,x)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${b}px`,height:`${x}px`}))},[t]),k=bl(()=>{t.emit("event:image.onLoad")},[t]);return Lt.createElement(kp.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},Lt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},l?d.map(([b,x],O)=>{let Q=p?p.task.resolve[O]:null;if(Q&&typeof Q=="function")return Lt.createElement(Vo,{key:x,ref:b,autoFit:o.config.autoFit});let W=Q?Q.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():l;return Lt.createElement(xl,{key:x,ref:b,src:W||l,autoFit:o.config.autoFit,resolveSrc:c,onSizeChanged:O===0?C:void 0,onLoad:O===0?k:void 0})}):d.map(([b,x],O)=>Lt.createElement(Vo,{key:x,ref:b,autoFit:o.config.autoFit,onSizeChanged:O===0?C:void 0,onLoad:O===0?k:void 0})),Lt.createElement("div",{className:Cl("w-full h-full top-0 left-0 absolute")},n.map(b=>Lt.createElement("div",{className:Cl("w-full h-full relative"),key:"wearable-"+b.getId()},Lt.createElement(wl,{image:b,state:e}))))))}var wl=Lt.memo(Rp),kl=wl;import Wo,{useEffect as El,useMemo as Hp,useRef as os}from"react";var Ip=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,Mp=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function Pl(o,e){if(typeof e!="string"||!e.length)return o;if(Ip.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=Np(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+Gp(r+e.replace(/\\/g,"/"))}function Np(o){let e=Mp.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function Gp(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 Uo=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 rs({state:o,puppet:e}){let[t]=le(),{cacheManager:n}=Wt(),i=os(null),r=Hp(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=os(r);s.current=r;let{transformRef:a,transitionRefs:l,initDisplayable:c,applyTransform:u,applyLoop:d,stopLoop:p,applyTransition:f,updateStyleSync:h,deps:m}=Kt({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`}}]});Tt(e,{initDisplayable:c,applyTransform:u,applyLoop:d,stopLoop:p,applyTransition:f,updateStyleSync:h,flush:t},[...m]),El(()=>{let g=i.current;if(!g)return;let y=o.game,T=e.config.backend,C=y.getPuppetBackend(T);if(!C)return e._setStatus("missing-backend"),y.getPuppetBackendRegistry().reportMissing(T,x=>{o.logger.warn("Puppet",x)}),()=>{e._setStatus("unmounted")};let k;try{k=C.mount(g,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:A,resolveSibling:x=>A(Pl(e.config.src,x)),warn:(x,O)=>{o.logger.warn("Puppet",x,O)}})}catch(x){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${T}" threw while mounting "${e.config.src}"`,x),()=>{e._setStatus("unmounted")}}let b=!1;return e._attachInstance(k),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!b&&typeof k.ready=="function"?k.ready():void 0).then(()=>{b||e._setStatus("ready")}).catch(x=>{b||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${T}" failed to load "${e.config.src}"`,x))}),()=>{b=!0,e._attachInstance(null),e._setStatus("unmounted");try{k.dispose()}catch(x){o.logger.error("Puppet",`Backend "${T}" threw while disposing`,x)}}},[]);let v=os(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(T){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,T)}},[r]);function A(g){return P.isDataURI(g)?g:n.get(g)||g}return Wo.createElement(Ut.Div,{"data-element-type":"puppet"},Wo.createElement(Ut.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},l.map(([g,y])=>Wo.createElement("div",{key:y,ref:g,className:e.config.className},Wo.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function ss({state:o,displayable:e}){return gi.createElement(gi.Fragment,null,e.map(t=>{if(t instanceof yn)return gi.createElement(ns,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof I)return gi.createElement(kl,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof kt)return gi.createElement(rs,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Bo,{useEffect as Op}from"react";import{motion as Vp}from"motion/react";function Dl({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:l,stopLoop:c,updateStyleSync:u,deps:d}=Kt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return Tt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:l,stopLoop:c,updateStyleSync:u},[...d]),Op(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Bo.createElement(Bo.Fragment,null,Bo.createElement(Vp.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,f])=>Bo.createElement("div",{className:"relative w-full h-full",ref:p,key:f},t))))}async function Ll(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 Fp from"clsx";import{useEffect as as,useRef as Up}from"react";import ls from"react";function cs({state:o,className:e,elements:t}){let{scene:n,layers:i}=t,r=Up(null);return as(()=>(o.stageTransition.registerScene(n,r.current),()=>{o.stageTransition.registerScene(n,null)}),[]),as(()=>n.events.depends([n.events.on(ft.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),as(()=>(n.events.emit(ft.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(ft.EventTypes["event:scene.unmount"]),o.events.emit(L.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),Tt(n,{setBackgroundMusic(s,a){return Ll(o,n,s,a)}}),ls.createElement("div",{className:Fp(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])=>ls.createElement(Dl,{state:o,layer:s,key:s.getId()},ls.createElement(ss,{state:o,displayable:a}))))}import{AnimatePresence as zp}from"motion/react";import{useEffect as $p,useReducer as jp,useRef as yi}from"react";import Wp from"clsx";import zt,{useCallback as us,useMemo as Bp,useRef as Kp}from"react";function ps({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=R(),a=Kp([]),l=us(h=>(a.current.push(h),a.current.indexOf(h)),[]),c=us(h=>{let m=a.current.indexOf(h);m!==-1&&a.current.splice(m,1)},[]),u=us(h=>a.current.indexOf(h),[]),d=s.config.menu,p=Bp(()=>e.map(h=>({...h,words:h.prompt.evaluate(we.getCtx({gameState:n}))})),[]);function f(h){t(h)}return zt.createElement(zt.Fragment,null,zt.createElement(Ir,{value:{evaluated:p,choose:f,gameState:n}},zt.createElement(Nr,{value:{register:l,unregister:c,getIndex:u}},zt.createElement(Ft,{className:"absolute"},r&&o&&zt.createElement(ui,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),zt.createElement(Ut.Div,{color:"green",border:"dashed",className:Wp("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},zt.createElement(d,{items:p.map((h,m)=>m)})))))}function Rl({items:o}){return zt.createElement(fo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>zt.createElement(wo,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import qp from"clsx";import vi from"react";var Yp=120;function ds({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=yi(!1),a=yi({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),l=yi([]),c=yi(null),u=yi(null),[,d]=jp(m=>m+1,0),p=()=>{u.current&&(clearTimeout(u.current),u.current=null)},f=()=>{let m=c.current;if(!m)return;let v=a.current;m.forEach(({slot:A,presenceKey:g})=>{v.slotKeys.get(A)===g&&v.slotKeys.delete(A),v.exitingKeys.add(g)}),c.current=null,u.current=null,l.current=[],d()};$p(()=>()=>{p()},[]);let h=(()=>{let m=a.current,v=i.length>0?i.map(({action:y,onClick:T},C)=>({action:y,slot:C,useTypeEffect:!s.current,onFinished:k=>{k!==void 0&&(s.current=k),T(),o.events.emit(L.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((y,T)=>{if(!y.action.prompt||!y.action.words)return[];let C=m.menuPromptIds.get(y);return C||(C=`menu-prompt-${n.getId()}-${m.nextKey++}`,m.menuPromptIds.set(y,C)),[{action:{sentence:y.action.prompt,words:y.action.words,character:null,id:C},slot:T,useTypeEffect:!1}]});if(v.length===0)return!c.current&&l.current.length>0&&(c.current=l.current.map(y=>({...y,active:!1}))),c.current&&!u.current&&(u.current=setTimeout(f,Yp)),c.current??[];p(),c.current=null;let A=new Set(v.map(({slot:y})=>y));for(let[y,T]of Array.from(m.slotKeys))A.has(y)||(m.exitingKeys.add(T),m.slotKeys.delete(y));let g=v.map(({slot:y,...T})=>{let C=m.slotKeys.get(y);return(!C||m.exitingKeys.has(C))&&(C=`say-${n.getId()}-${m.nextKey++}`,m.slotKeys.set(y,C)),{...T,presenceKey:C,slot:y,active:!0}});return l.current=g,g})();return vi.createElement("div",{className:qp(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs"},vi.createElement(zp,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{a.current.exitingKeys.clear()}},h.map(({action:m,onFinished:v,presenceKey:A,active:g,useTypeEffect:y})=>vi.createElement(ui,{gameState:o,key:A,action:m,active:g,onFinished:v,useTypeEffect:y}))),r.map(({action:m,onClick:v},A)=>vi.createElement("div",{key:"menu-"+A,"data-element-type":"menu"},vi.createElement(ps,{state:o,prompt:m.prompt,choices:m.choices,renderPrompt:!m.prompt,afterChoose:g=>{s.current=!1,v(g),o.stage.next()},words:m.words}))))}import mn,{useEffect as Qp,useRef as ms}from"react";import{motion as Xp}from"motion/react";function Il({state:o,camera:e,children:t}){let n=ms(null),i=ms(null),r=ms(null),{transformRef:s,transitionRefs:a,initDisplayable:l,applyTransition:c,applyTransform:u,applyLoop:d,stopLoop:p,updateStyleSync:f,deps:h}=Kt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,companionRefs:[{ref:n,project:Ta},{ref:i,project:va},{ref:r,project:Sa}],transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return Tt(e,{initDisplayable:l,applyTransition:c,applyTransform:u,applyLoop:d,stopLoop:p,updateStyleSync:f},[...h]),Qp(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),mn.createElement(mn.Fragment,null,mn.createElement(Xp.div,{className:"absolute w-full h-full",ref:s,"data-element-type":"camera"},a.map(([m,v])=>mn.createElement("div",{className:"relative w-full h-full",ref:m,key:v},t))),mn.createElement("div",{className:"absolute w-full h-full","data-element-type":"camera-lens",style:{pointerEvents:"none"}},mn.createElement("div",{className:"absolute w-full h-full",ref:n,"data-element-type":"camera-lens-vignette"}),mn.createElement("div",{className:"absolute w-full h-full",ref:i,"data-element-type":"camera-lens-shutter-top"}),mn.createElement("div",{className:"absolute w-full h-full",ref:r,"data-element-type":"camera-lens-shutter-bottom"})))}import Jp from"react";import{useEffect as fs,useRef as Zp}from"react";import{useCallback as Ml}from"react";function Nl(o){let e=Ml(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=Ml(()=>{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 hs({gameState:o,video:e}){let t=Zp(null),{show:n,hide:i}=Nl(t);fs(()=>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,[]),fs(()=>{i(),e.state.display&&n()},[]),fs(()=>{if(!t.current)return;let s=t.current,a=!1,l=new Set,c=()=>new E(`Failed to add event listener, ref is not available
|
|
60
|
-
at Video.tsx: useEffect`),u=f=>{a||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();i()},play:()=>{if(!t.current)throw c();let h=t.current;return f||h.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(h.currentTime=0,new Promise(m=>{let v=!1,A=null,g=[],y=()=>{v||(v=!0,l.delete(y),A&&A(),g.forEach(T=>T()),m())};l.add(y),A=o.schedule(({retry:T})=>{if(v)return;if(h.readyState<3){let x=()=>{h.removeEventListener("loadeddata",x),T()};h.addEventListener("loadeddata",x),g.push(()=>h.removeEventListener("loadeddata",x));return}let C=()=>y(),k=()=>y(),b=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),y()};h.addEventListener("ended",C),h.addEventListener("stopped",k),h.addEventListener("error",b),g.push(()=>{h.removeEventListener("ended",C),h.removeEventListener("stopped",k),h.removeEventListener("error",b)}),h.play().catch(x=>{o.logger.error("Failed to play video: "+x),y()})},10)}))},pause:()=>{if(!t.current)throw c();t.current.pause()},resume:()=>{if(!t.current)throw c();return t.current.play().catch(h=>{o.logger.error("Failed to resume video: "+h)})},stop:()=>{if(!t.current)throw c();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:h=>{if(!t.current)throw c();t.current.currentTime=h}}))},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),l.forEach(f=>f()),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 Jp.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 _p,{useEffect as ed,useRef as td}from"react";var Gl={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 nd(o,e){return e===void 0?"linear":Array.isArray(e)?`cubic-bezier(${e.join(", ")})`:typeof e=="string"&&Gl[e]?Gl[e]:(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease")}function gs({gameState:o,vfx:e}){let t=td(null);return ed(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,l=new Set,c=new Set,u=[],d=T=>{n.style.transition="",n.style.opacity=String(T)},p=()=>{n.play().catch(T=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+T)})},f=()=>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(T=>{let C=!1,k=()=>x(),b=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),x()},x=()=>{C||(C=!0,c.delete(x),n.removeEventListener("loadeddata",k),n.removeEventListener("error",b),T())};c.add(x),n.addEventListener("loadeddata",k),n.addEventListener("error",b),(n.readyState>=2||n.error)&&x()}),h=(T,C,k)=>{let b=C?.duration??0,x=++s;return k.instant||b<=0?(d(T),Promise.resolve()):new Promise(O=>{let Q=!1,W=null,ve=()=>{Q||(Q=!0,c.delete(ve),W!==null&&clearTimeout(W),s===x&&t.current&&d(T),O())};c.add(ve),n.style.transition=`opacity ${b}ms ${nd(o,C?.easing)}`,n.offsetWidth,n.style.opacity=String(T),W=setTimeout(ve,b)})},m=T=>{r||(r=!0,i=T,o.mountState(e,{show:async C=>{a=!0;let k={instant:!1};l.add(k);try{if(await f(),!t.current)return;n.playbackRate=C?.rate??e.config.playbackRate,e.state.paused||p(),await h(C?.opacity??e.config.opacity,C,k)}finally{l.delete(k)}},hide:async C=>{a=!0;let k={instant:!1};l.add(k);try{await h(0,C,k),t.current&&n.pause()}finally{l.delete(k)}},pause:()=>{n.pause()},resume:()=>{p()},setRate:C=>{n.playbackRate=C}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&d(e.config.opacity)},0)))},v=()=>m(!1),A=()=>{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"],()=>{l.size===0&&c.size===0||(l.forEach(T=>{T.instant=!0}),[...c].forEach(T=>T()),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",A),n.readyState>=3?m(!1):n.error&&A(),()=>{n.removeEventListener("canplay",v),n.removeEventListener("error",A),document.removeEventListener("visibilitychange",y),g.cancel(),u.forEach(T=>T()),[...c].forEach(T=>T()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),_p.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 id from"clsx";import od,{useCallback as rd,useEffect as Ko,useRef as sd}from"react";function ys({children:o,className:e,gameState:t}){let{ratio:n}=ye(),i=R(),[r]=le(),s=sd(null),a=i.config.minWidth,l=i.config.minHeight,c=rd(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,l),r()},[r,t.logger,l,a,n]);return Ko(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Ko(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Ko(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,l,a]),Ko(()=>t.events.on(L.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),od.createElement(sl,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:l,debounceMs:i.config.ratioUpdateInterval,className:id(e),onUpdate:c},o)}import Hl,{useEffect as ad,useRef as ld,useState as Ol}from"react";function vs({src:o,width:e,height:t}){let[n,i]=Ol({x:0,y:0}),[r,s]=Ol(!1),a=ld(null),{ratio:l}=ye();return ad(()=>{let c=u=>{if(a.current){let d=a.current.getBoundingClientRect(),p=u.clientX-d.left,f=u.clientY-d.top;i({x:p,y:f}),r||s(!0)}};return window.addEventListener("mousemove",c),()=>{window.removeEventListener("mousemove",c)}},[r]),Hl.createElement(Ft,{ref:a,className:"overflow-hidden absolute"},Hl.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(${l.state.scale})`},alt:""}))}import Vl from"react";import en from"react";function Ss({error:o,errorInfo:e}){return R().config.app.debug?en.createElement("div",{className:"text-left"},en.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),en.createElement("p",{className:"text-red-700"},"Message: ",o.message),en.createElement("pre",null,"Error Stack: ",o?.stack),en.createElement("pre",null,"Component Stack: ",e?.componentStack),en.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):en.createElement("div",{className:"bg-white w-full h-full"},en.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),en.createElement("p",null,"Please contact the game developer for further assistance."))}var zo=class extends Vl.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?Vl.createElement(Ss,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import Wl from"clsx";import U,{useEffect as Rt,useReducer as Bl,useState as Wn}from"react";import{flushSync as Kl}from"react-dom";import{useRef as cd}from"react";import{useEffect as ud}from"react";function Fl({gameState:o}){let e=cd(null);return ud(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(L.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import Si,{useEffect as pd}from"react";function Ts({gameState:o}){let[e]=le(),{ratio:t}=ye(),n=o.notificationMgr;pd(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return Si.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"},Si.createElement(i,{notifications:n.toArray()}))}function Ul({notifications:o}){return Si.createElement(Po,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>Si.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},Si.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function zl({story:o=ri.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:l,onError:c,children:u,active:d=!0}){let[p,f]=Bl(D=>D+1,0),[h,m]=Bl(D=>D+1,0),[v,A]=Wn(0),g=R(),[y]=Wn(()=>new L(g,{update:f,forceUpdate:()=>{y.logger.weakWarn("Player","force update"),Kl(()=>{f()})},forceRemount:()=>{y.logger.weakWarn("Player","force remount"),Kl(()=>{A(D=>D+1),f()})},next:vt})),T=U.createRef(),C=U.createRef(),[k,b]=Wn(!1),x=U.useRef(!1),O=U.useRef(null),Q=U.useRef(null),{preloaded:W}=Wt(),[ve,Se]=Wn(!1),je=U.useRef(!1),[Ge,yt]=Wn(!1),ct=U.useRef(!1),pe=U.useRef(null),it=U.useRef(!1),[$t]=Wn(new Map);function At(D){return{game:g,gameState:y,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable(),scene:D}}function vt(){let D=()=>{$t.forEach(N=>N.cancel())};if(y.rollLock.isLocked())return;D();let B=!1,he=0;for(;!B;){if(he++>g.config.maxStackModelLoop)throw new E("Max stack model loop reached");let N=g.getLiveGame().next();if(!N){if(g.getLiveGame().stackModel&&!g.getLiveGame().stackModel.isEmpty())continue;break}if(S.isAwaitable(N)){if(O.current===N)break;O.current=N,N.onSettled(()=>{N.isFailed()||(O.current===N&&(O.current=null),vt())}),N.onFailed(Ee=>{O.current===N&&(O.current=null),y.logger.error("Player",Ee)}),B=!0;break}if(N instanceof wn){if(Q.current===N)break;Q.current=N,N.nextUnlock().then(()=>{Q.current===N&&(Q.current=null),vt()}),B=!0;break}if(Xe.isCalledActionResult(N)&&N.wait&&Xe.isStackModelsAwaiting(N.wait.type,N.wait.stackModels)){if(O.current===N)break;if(O.current=N,N.wait){let Ee=Xe.executeStackModelGroup(N.wait.type,N.wait.stackModels);Ee.then(()=>{O.current===N&&(O.current=null),vt()}),Ee.onFailed($=>{O.current===N&&(O.current=null),y.logger.error("Player",$)})}B=!0;break}y.handle(N)}y.stage.update()}Rt(()=>{y.audioManager.initialize()},[]),Rt(()=>(g.getLiveGame().setGameState(y),o&&!g.getLiveGame().isPlaying()&&g.getLiveGame().loadStory(o),o?.entryScene&&!y.getPreloadingScene()&&!y.getLastScene()&&y.preloadScene(o.entryScene),y.playerCurrent=T.current,y.mainContentNode=C.current,()=>{g.getLiveGame().setGameState(void 0),y.playerCurrent=null}),[g,o]),Rt(()=>ot(()=>{b(!0);let D=y.getLastScene(),B=[];D?B.push(D.events.once("event:scene.mount",()=>{y.stage.next()}).cancel):y.stage.next();let he=y.events.on(L.EventTypes["event:state.end"],()=>{l&&l({game:g,gameState:y,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable()})});return y.stage.update(),()=>{D&&B.forEach(N=>N()),he.cancel()}}),[]),Rt(()=>ot(()=>{k&&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()}))}),[k]),Rt(()=>ot(()=>{if(ve&&s&&!je.current){je.current=!0;let D=pe.current||y.getLastScene()||y.getPreloadingScene(),B=At(D);s(B)}}),[ve]),Rt(()=>ot(()=>{if(Ge&&!ct.current){ct.current=!0;let D=pe.current||y.getLastScene()||y.getPreloadingScene(),B=At(D);g.markPreloadComplete(B)&&r&&r(B)}}),[Ge]),Rt(()=>y.events.on(L.EventTypes["event:state.scene.mount"],D=>{pe.current||(pe.current=D,m())}).cancel,[]),Rt(()=>{if(!Ge||!d||it.current||g.isFirstSceneReady())return;let D=pe.current||y.getLastScene();if(!D)return;let B=null,he=null,N=!1;it.current=!0;let Ee=()=>{N=!0,it.current=!1;let $=At(D);g.markFirstSceneReady($)&&a&&a($)};return typeof requestAnimationFrame=="function"?B=requestAnimationFrame(()=>{he=setTimeout(Ee,0)}):he=setTimeout(Ee,0),()=>{N||(it.current=!1,B!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(B),he!==null&&clearTimeout(he))}},[d,h,p,Ge]),Rt(()=>W.events.depends([W.events.on($e.EventTypes["event:preloaded.ready"],()=>{Se(!0),y.stage.update(),o&&g.getLiveGame().isPlaying()&&vt()}),W.events.on($e.EventTypes["event:preloaded.complete"],()=>{yt(!0)})]).cancel,[]),Rt(()=>{y.flushDep=p},[p]);let H=e||g.config.width,G=t||g.config.height;return U.createElement(zo,{onError:c},U.createElement("div",{style:{width:typeof H=="number"?`${H}px`:H,height:typeof G=="number"?`${G}px`:G},className:Wl(n,"__narraleaf_content-player"),ref:T,tabIndex:0},U.createElement(ys,{className:Wl("flex-grow overflow-auto"),gameState:y},U.createElement(Jr,{gameState:y}),U.createElement(Fl,{gameState:y}),U.createElement(Ft,{className:"absolute",ref:C,style:{cursor:y.game.config.cursor?"none":"auto",overflow:y.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},g.config.cursor&&U.createElement(vs,{src:g.config.cursor,width:g.config.cursorWidth,height:g.config.cursorHeight}),U.createElement(dd,{show:ve&&d,key:v},U.createElement($r,null,U.createElement(dl,{state:y}),U.createElement(gl,{state:y}),U.createElement(md,{state:y},U.createElement("div",{className:"w-full h-full absolute",style:{isolation:"isolate"},"data-element-type":"scene-group"},y.getSceneElements().map(D=>U.createElement(cs,{key:"scene-"+D.scene.getId(),state:y,elements:D}))),U.createElement(fd,{state:y}),y.getVideos().map((D,B)=>U.createElement("div",{className:"w-full h-full absolute",key:"video-"+B,"data-element-type":"video"},U.createElement(hs,{gameState:y,video:D}))),y.getVfx().map(D=>U.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}},U.createElement(gs,{gameState:y,vfx:D})))),y.getSceneElements().map(D=>U.createElement(ds,{key:"scene-dialogs-"+D.scene.getId(),state:y,elements:D})),U.createElement(hd,{NvlComponent:g.config.nvlDialog}))),U.createElement(Sl,{state:y}),U.createElement(el,null,u),U.createElement(Ts,{gameState:y})))))}function dd({children:o,show:e}){return U.createElement(U.Fragment,null,e?o:null)}function md({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?U.createElement(Il,{state:o,camera:t},e):U.createElement(U.Fragment,null,e)}function fd({state:o}){let e=U.useRef(null);return Rt(()=>(o.stageTransition.registerOverlayHost(e.current),()=>{o.stageTransition.registerOverlayHost(null)}),[]),U.createElement("div",{className:"w-full h-full absolute pointer-events-none",ref:e,"data-element-type":"stage-transition-overlay-host"})}function hd({NvlComponent:o}){let{dialogs:e,state:t}=Bt(),i=R().getLiveGame().getGameState(),r=U.useMemo(()=>e.map((s,a)=>{let l=s.sentence.evaluate(we.getCtx({gameState:i})),c=t.activeDialogId===s.id,u=c&&t.phase==="typing";return{entry:s,index:a,isActive:c,gameState:i,words:l,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return U.createElement(o,{dialogs:r})}import"client-only";import Bn from"react";function $l({children:o,game:e}){return Bn.createElement(Bn.Fragment,null,Bn.createElement(La,null,Bn.createElement(wa,{game:e},Bn.createElement(Xa,null,Bn.createElement(Da,null,o)))))}var gd=(l=>(l.image="narraleaf:image",l.text="narraleaf:text",l.layer="narraleaf:layer",l.scene="narraleaf:scene",l.video="narraleaf:video",l.vfx="narraleaf:vfx",l.camera="narraleaf:camera",l.puppet="narraleaf:puppet",l))(gd||{});import yd from"clsx";import bt,{useEffect as jl,useRef as vd,useState as Sd}from"react";import{motion as Td,useIsPresent as bd}from"motion/react";var Ad={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function Cd({children:o,initial:e,transition:t,...n}){let i=R(),r=Et(),{ratio:s}=ye(),[a]=pn(re.Preferences.showDialog),l=vd(null),[c]=bn("nextAction"),u=bd(),[d,p]=Sd(null);function f(){r.config.gameState.isAdvanceSuspended()||r.requestComplete()}return jl(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
61
|
-
at Say.tsx: onElementClick`);return}let h=v=>{v.repeat||r.config.gameState.isAdvanceSuspended()||i.keyMap.match("nextAction",v.key)&&r.requestComplete()};window.addEventListener("keydown",h);let m=r.events.on(Ne.Events.simulateClick,()=>{l.current&&l.current.click()});return()=>{window.removeEventListener("keydown",h),m.cancel()}},[r,c]),jl(()=>{let h=i.preference.onPreferenceChange(re.Preferences.autoForward,m=>{m&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{h.cancel()}},[r]),bt.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},bt.createElement("div",{className:yd("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:f,style:{...Oi(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:l},bt.createElement(Qr,{value:d},bt.createElement(Td.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)),bt.createElement("div",{"data-element-type":"dialog-overlay",className:"absolute inset-0 pointer-events-none",ref:p})))}function ql({children:o,...e}){let t=Et();return!t.config.action.sentence||!t.config.action.words?null:bt.createElement(Cd,{...e},o)}var hp=ql;function Yl(){return bt.createElement(ql,null,bt.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},bt.createElement(Or,null),bt.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},bt.createElement(_t,null),bt.createElement(dn,{...Ad}))))}var Ti={say:Yl,menu:Rl,notification:Ul,nvlDialog:Yr};var $o=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 bi=class{constructor(e={}){this.keyMap=e;this.events=new X}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 Ql=(e=>(e.game="game",e))(Ql||{}),Je=class Je{constructor(e){this.hooks=new Mi;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new li(Je.DefaultPreference);this.audioBuses=new Zn(()=>this.config.audioBuses??[],ia(this.preference));this.keyMap=new bi({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new X;this.puppetBackends=new Uo;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=j(Je.DefaultConfig,e),this.plugins=new $o(this),this.router=new un(this)}configure(e){let[t,n]=$s(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=j(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(Je.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(Je.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(Je.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(Je.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(Je.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(Je.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 Ht(this)}};Je.defaultSettings={volume:1},Je.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},Je.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"},Je.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:Ti.notification,menu:Ti.menu,dialog:Ti.say,nvlDialog:Ti.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100,audioBuses:[]},Je.GameSettingsNamespace=Ql,Je.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var re=Je;var jo=class jo extends q{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===ie.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===ie.doAsync){if(r.length===0)return super.executeAction(t,n);let s=jo.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===ie.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===ie.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===ie.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===ie.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let l=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:[l]}}}else if(this.type===ie.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 l=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:[l]}}}else if(this.type===ie.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===ie.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 l=new S,c=new ke(a);return t.timelines.attachTimeline(c),a.then(()=>{l.resolve({type:this.type,node:this.contentNode.getChild()})}),l.onSkipControllerRegister(u=>{u.onAbort(()=>{c.abort()})}),l}else if(this.type===ie.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new S,a=new S,l=new ke(a);t.timelines.attachTimeline(l);let c=t.game.preference,u=c.getPreference(re.Preferences.autoForward),d=c.getPreference(re.Preferences.gameSpeed),p=u?t.game.config.autoForwardDelay/d:null,f=!1,h=null,m=null,v=null,A=()=>{m?.cancel(),v?.cancel(),h&&(clearTimeout(h),h=null)},g=()=>{f||(f=!0,A(),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&&(h=setTimeout(g,p)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(y=>{y.onAbort(()=>{f||(f=!0,A(),l.abort())})}),s}else{if(this.type===ie.label)return super.executeAction(t,n);if(this.type===ie.jump){let s=this._jumpTarget;if(!s){let[c]=this.contentNode.getContent();throw new Fe(`Jump target label "${c}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),l=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},c=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(c,u)},[l]),a.clearMainStack().getStackModelForce().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===ie.break||this.type===ie.waitForClick||this.type===ie.label||this.type===ie.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===ie.break)return super.stringifyWithContent("Control","break");if(this.type===ie.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===ie.label||this.type===ie.jump){let[a]=this.contentNode.getContent(),l=this.type===ie.label?"label":"jump";return super.stringifyWithContent("Control",`${l}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};jo.ActionTypes=ie;var oe=jo;var Ke=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(oe.ActionTypes.do,t)}doAsync(t){return this.push(oe.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(oe.ActionTypes.any,t)}all(t){return this.pushUnchained(oe.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(oe.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(oe.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=Y.from(t);return this.pushWithLambda(oe.ActionTypes.while,n,i)}breakLoop(){let t=new oe(this.chain(),oe.ActionTypes.break,new w().setContent([]));return this.chain(t)}sleep(t){return this.push(oe.ActionTypes.sleep,[],t)}waitForClick(){let t=new oe(this.chain(),oe.ActionTypes.waitForClick,new w().setContent([]));return this.chain(t)}label(t){let n=new oe(this.chain(),oe.ActionTypes.label,new w().setContent([t]));return this.chain(n)}jump(t){let n=new oe(this.chain(),oe.ActionTypes.jump,new w().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new w().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new w().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new w().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Xt.say(n).getActions():Be.toActions([n]))}};var z=class z extends Qe{static get DefaultUserConfig(){return z._defaultUserConfig??(z._defaultUserConfig=new K({name:"(anonymous)",autoInit:!0,src:z.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...ee.DefaultTransformState.getDefaultConfig()},{position:e=>M.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):z.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:z.isLayeredSrc(e)?null:z.isTagSrc(e)&&e.config.src.resolve?z.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):z.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=>z.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(z.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new z({src:e})}constructor(e={}){super();let t=z.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 Ke,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 Ae(n,Ae.ActionTypes.setAppearance,new w().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Ke,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 ne("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:z.StateSerializer.serialize(this.state),transformState:ee.TransformStateSerializer.serialize(this.transformState.get()),loop:this._serializeLoop()}}fromData(e){return this.state=z.StateSerializer.deserialize(e.state),this.transformState.resetTo(ee.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}_applyTransition(e,t){return new Te(this.chain(),de.applyTransition,new w().setContent([e,t]))}_init(e,t){return new Te(this.chain(),de.init,new w().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new Ae(this.chain(),Ae.ActionTypes.initWearable,new w().setContent([e]))}_flush(){return new Ae(this.chain(),Ae.ActionTypes.flush,new w)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get()),this}resolveTags(e,t){if(!z.isTagSrc(this))throw new Error(`Tag not defined
|
|
62
|
-
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(l=>{let c=n.get(l);c&&i.set(c,l)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let l=i.get(a);if(!l)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(l)}),r}_setAppearanceSync(e){if(P.isImageSrc(e)||P.isColor(e)){if(P.isColor(e)&&!this.config.isBackground)throw new
|
|
62
|
+
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(b)),r.get(b)||b}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:h,applyTransition:f,applyTransform:m,applyLoop:v,stopLoop:C,updateStyleSync:g,flush:y,deps:T}=$t({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:b=>{if(l)return(b?b.task.resolve:[null]).map(q=>q&&typeof q=="function"?{style:Jp}:{style:Xp(o.state.darkness)});let x=b?b.transition._getCurrentSrc():Qp(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):G.DefaultImagePlaceholder},{style:{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none",filter:"brightness(1)"}}]},propOverwrite:b=>b.src?{...b,src:c(b.src)}:b});Ct(o,{createWearable:b=>{i(x=>[...x,b])},disposeWearable:b=>{i(x=>x.filter(F=>F.getId()!==b.getId()))},initDisplayable:h,applyTransform:m,applyLoop:v,stopLoop:C,applyTransition:f,events:t,updateStyleSync:g,flush:y},[...T]);let A=Gl((b,x)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${b}px`,height:`${x}px`}))},[t]),w=Gl(()=>{t.emit("event:image.onLoad")},[t]);return It.createElement(qp.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},It.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},l?d.map(([b,x],F)=>{let q=p?p.task.resolve[F]:null;if(q&&typeof q=="function")return It.createElement(jo,{key:x,ref:b,autoFit:o.config.autoFit});let Q=q?q.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():l;return It.createElement(Ol,{key:x,ref:b,src:Q||l,autoFit:o.config.autoFit,resolveSrc:c,onSizeChanged:F===0?A:void 0,onLoad:F===0?w:void 0})}):d.map(([b,x],F)=>It.createElement(jo,{key:x,ref:b,autoFit:o.config.autoFit,onSizeChanged:F===0?A:void 0,onLoad:F===0?w:void 0})),It.createElement("div",{className:Fl("w-full h-full top-0 left-0 absolute")},n.map(b=>It.createElement("div",{className:Fl("w-full h-full relative"),key:"wearable-"+b.getId()},It.createElement(Vl,{image:b,state:e}))))))}var Vl=It.memo(_p),Ul=Vl;import Xo,{useEffect as Bl,useMemo as id,useRef as ds}from"react";var Zp=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,ed=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function Wl(o,e){if(typeof e!="string"||!e.length)return o;if(Zp.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=td(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+nd(r+e.replace(/\\/g,"/"))}function td(o){let e=ed.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function nd(o){let e=o.split("/"),t=[];for(let n=0;n<e.length;n++){let i=e[n];if(!(i==="."||i===""&&n!==e.length-1)){if(i===".."){t.pop();continue}t.push(i)}}return t.join("/")}var Yo=class{constructor(){this.backends=new Map;this.reportedMissing=new Set}register(e){if(!e||typeof e.name!="string"||!e.name.length)throw new Error("A puppet backend must have a non-empty name.");if(typeof e.mount!="function")throw new Error(`Puppet backend "${e.name}" must implement mount().`);return this.backends.set(e.name,e),this.reportedMissing.delete(e.name),this}get(e){return this.backends.get(e)||null}has(e){return this.backends.has(e)}list(){return Array.from(this.backends.keys())}unregister(e){return this.backends.delete(e)}reportMissing(e,t){return this.reportedMissing.has(e)?!1:(this.reportedMissing.add(e),t(`No puppet backend is registered under "${e}". The element keeps its place on the stage, its transform and its saved state, but draws nothing. Register one with game.registerPuppetBackend({name, mount}) before the game mounts.`),!0)}};function ms({state:o,puppet:e}){let[t]=le(),{cacheManager:n}=zt(),i=ds(null),r=id(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=ds(r);s.current=r;let{transformRef:a,transitionRefs:l,initDisplayable:c,applyTransform:u,applyLoop:d,stopLoop:p,applyTransition:h,updateStyleSync:f,deps:m}=$t({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`}}]});Ct(e,{initDisplayable:c,applyTransform:u,applyLoop:d,stopLoop:p,applyTransition:h,updateStyleSync:f,flush:t},[...m]),Bl(()=>{let g=i.current;if(!g)return;let y=o.game,T=e.config.backend,A=y.getPuppetBackend(T);if(!A)return e._setStatus("missing-backend"),y.getPuppetBackendRegistry().reportMissing(T,x=>{o.logger.warn("Puppet",x)}),()=>{e._setStatus("unmounted")};let w;try{w=A.mount(g,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:C,resolveSibling:x=>C(Wl(e.config.src,x)),warn:(x,F)=>{o.logger.warn("Puppet",x,F)}})}catch(x){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${T}" threw while mounting "${e.config.src}"`,x),()=>{e._setStatus("unmounted")}}let b=!1;return e._attachInstance(w),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!b&&typeof w.ready=="function"?w.ready():void 0).then(()=>{b||e._setStatus("ready")}).catch(x=>{b||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${T}" failed to load "${e.config.src}"`,x))}),()=>{b=!0,e._attachInstance(null),e._setStatus("unmounted");try{w.dispose()}catch(x){o.logger.error("Puppet",`Backend "${T}" threw while disposing`,x)}}},[]);let v=ds(r);Bl(()=>{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(T){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,T)}},[r]);function C(g){return P.isDataURI(g)?g:n.get(g)||g}return Xo.createElement(Bt.Div,{"data-element-type":"puppet"},Xo.createElement(Bt.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},l.map(([g,y])=>Xo.createElement("div",{key:y,ref:g,className:e.config.className},Xo.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function fs({state:o,displayable:e}){return xi.createElement(xi.Fragment,null,e.map(t=>{if(t instanceof Tn)return xi.createElement(us,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof G)return xi.createElement(Ul,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof Et)return xi.createElement(ms,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Qo,{useEffect as od}from"react";import{motion as rd}from"motion/react";function zl({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:l,stopLoop:c,updateStyleSync:u,deps:d}=$t({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return Ct(e,{initDisplayable:r,applyTransition:s,applyTransform:a,applyLoop:l,stopLoop:c,updateStyleSync:u},[...d]),od(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Qo.createElement(Qo.Fragment,null,Qo.createElement(rd.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([p,h])=>Qo.createElement("div",{className:"relative w-full h-full",ref:p,key:h},t))))}async function Kl(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 hs,useRef as ad}from"react";import gs from"react";function ys({state:o,className:e,elements:t}){let{scene:n,layers:i}=t,r=ad(null);return hs(()=>(o.stageTransition.registerScene(n,r.current),()=>{o.stageTransition.registerScene(n,null)}),[]),hs(()=>n.events.depends([n.events.on(yt.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),hs(()=>(n.events.emit(yt.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(yt.EventTypes["event:scene.unmount"]),o.events.emit(L.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),Ct(n,{setBackgroundMusic(s,a){return Kl(o,n,s,a)}}),gs.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])=>gs.createElement(zl,{state:o,layer:s,key:s.getId()},gs.createElement(fs,{state:o,displayable:a}))))}import{AnimatePresence as pd}from"motion/react";import{useEffect as dd,useReducer as md,useRef as wi}from"react";import ld from"clsx";import jt,{useCallback as vs,useMemo as cd,useRef as ud}from"react";function Ss({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=I(),a=ud([]),l=vs(f=>(a.current.push(f),a.current.indexOf(f)),[]),c=vs(f=>{let m=a.current.indexOf(f);m!==-1&&a.current.splice(m,1)},[]),u=vs(f=>a.current.indexOf(f),[]),d=s.config.menu,p=cd(()=>e.map(f=>({...f,words:f.prompt.evaluate(we.getCtx({gameState:n}))})),[]);function h(f){t(f)}return jt.createElement(jt.Fragment,null,jt.createElement(Ur,{value:{evaluated:p,choose:h,gameState:n}},jt.createElement(Br,{value:{register:l,unregister:c,getIndex:u}},jt.createElement(Wt,{className:"absolute"},r&&o&&jt.createElement(gi,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),jt.createElement(Bt.Div,{color:"green",border:"dashed",className:ld("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},jt.createElement(d,{items:p.map((f,m)=>m)})))))}function $l({items:o}){return jt.createElement(bo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>jt.createElement(Mo,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import fd from"clsx";import ki from"react";var hd=120;function Ts({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=wi(!1),a=wi({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),l=wi([]),c=wi(null),u=wi(null),[,d]=md(m=>m+1,0),p=()=>{u.current&&(clearTimeout(u.current),u.current=null)},h=()=>{let m=c.current;if(!m)return;let v=a.current;m.forEach(({slot:C,presenceKey:g})=>{v.slotKeys.get(C)===g&&v.slotKeys.delete(C),v.exitingKeys.add(g)}),c.current=null,u.current=null,l.current=[],d()};dd(()=>()=>{p()},[]);let f=(()=>{let m=a.current,v=i.length>0?i.map(({action:y,onClick:T},A)=>({action:y,slot:A,useTypeEffect:!s.current,onFinished:w=>{w!==void 0&&(s.current=w),T(),o.events.emit(L.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((y,T)=>{if(!y.action.prompt||!y.action.words)return[];let A=m.menuPromptIds.get(y);return A||(A=`menu-prompt-${n.getId()}-${m.nextKey++}`,m.menuPromptIds.set(y,A)),[{action:{sentence:y.action.prompt,words:y.action.words,character:null,id:A},slot:T,useTypeEffect:!1}]});if(v.length===0)return!c.current&&l.current.length>0&&(c.current=l.current.map(y=>({...y,active:!1}))),c.current&&!u.current&&(u.current=setTimeout(h,hd)),c.current??[];p(),c.current=null;let C=new Set(v.map(({slot:y})=>y));for(let[y,T]of Array.from(m.slotKeys))C.has(y)||(m.exitingKeys.add(T),m.slotKeys.delete(y));let g=v.map(({slot:y,...T})=>{let A=m.slotKeys.get(y);return(!A||m.exitingKeys.has(A))&&(A=`say-${n.getId()}-${m.nextKey++}`,m.slotKeys.set(y,A)),{...T,presenceKey:A,slot:y,active:!0}});return l.current=g,g})();return ki.createElement("div",{className:fd(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs"},ki.createElement(pd,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{a.current.exitingKeys.clear()}},f.map(({action:m,onFinished:v,presenceKey:C,active:g,useTypeEffect:y})=>ki.createElement(gi,{gameState:o,key:C,action:m,active:g,onFinished:v,useTypeEffect:y}))),r.map(({action:m,onClick:v},C)=>ki.createElement("div",{key:"menu-"+C,"data-element-type":"menu"},ki.createElement(Ss,{state:o,prompt:m.prompt,choices:m.choices,renderPrompt:!m.prompt,afterChoose:g=>{s.current=!1,v(g),o.stage.next()},words:m.words}))))}import gn,{useEffect as gd,useRef as bs}from"react";import{motion as yd}from"motion/react";function jl({state:o,camera:e,children:t}){let n=bs(null),i=bs(null),r=bs(null),{transformRef:s,transitionRefs:a,initDisplayable:l,applyTransition:c,applyTransform:u,applyLoop:d,stopLoop:p,updateStyleSync:h,deps:f}=$t({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,companionRefs:[{ref:n,project:Ea},{ref:i,project:ka},{ref:r,project:Pa}],transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return Ct(e,{initDisplayable:l,applyTransition:c,applyTransform:u,applyLoop:d,stopLoop:p,updateStyleSync:h},[...f]),gd(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),gn.createElement(gn.Fragment,null,gn.createElement(yd.div,{className:"absolute w-full h-full",ref:s,"data-element-type":"camera"},a.map(([m,v])=>gn.createElement("div",{className:"relative w-full h-full",ref:m,key:v},t))),gn.createElement("div",{className:"absolute w-full h-full","data-element-type":"camera-lens",style:{pointerEvents:"none"}},gn.createElement("div",{className:"absolute w-full h-full",ref:n,"data-element-type":"camera-lens-vignette"}),gn.createElement("div",{className:"absolute w-full h-full",ref:i,"data-element-type":"camera-lens-shutter-top"}),gn.createElement("div",{className:"absolute w-full h-full",ref:r,"data-element-type":"camera-lens-shutter-bottom"})))}import vd from"react";import{useEffect as As,useRef as Sd}from"react";import{useCallback as ql}from"react";function Yl(o){let e=ql(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=ql(()=>{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 Cs({gameState:o,video:e}){let t=Sd(null),{show:n,hide:i}=Yl(t);As(()=>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,[]),As(()=>{i(),e.state.display&&n()},[]),As(()=>{if(!t.current)return;let s=t.current,a=!1,l=new Set,c=()=>new E(`Failed to add event listener, ref is not available
|
|
63
|
+
at Video.tsx: useEffect`),u=h=>{a||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();i()},play:()=>{if(!t.current)throw c();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,C=null,g=[],y=()=>{v||(v=!0,l.delete(y),C&&C(),g.forEach(T=>T()),m())};l.add(y),C=o.schedule(({retry:T})=>{if(v)return;if(f.readyState<3){let x=()=>{f.removeEventListener("loadeddata",x),T()};f.addEventListener("loadeddata",x),g.push(()=>f.removeEventListener("loadeddata",x));return}let A=()=>y(),w=()=>y(),b=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),y()};f.addEventListener("ended",A),f.addEventListener("stopped",w),f.addEventListener("error",b),g.push(()=>{f.removeEventListener("ended",A),f.removeEventListener("stopped",w),f.removeEventListener("error",b)}),f.play().catch(x=>{o.logger.error("Failed to play video: "+x),y()})},10)}))},pause:()=>{if(!t.current)throw c();t.current.pause()},resume:()=>{if(!t.current)throw c();return t.current.play().catch(f=>{o.logger.error("Failed to resume video: "+f)})},stop:()=>{if(!t.current)throw c();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:f=>{if(!t.current)throw c();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),l.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 vd.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 Td,{useEffect as bd,useRef as Ad}from"react";var Xl={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 Cd(o,e){return e===void 0?"linear":Array.isArray(e)?`cubic-bezier(${e.join(", ")})`:typeof e=="string"&&Xl[e]?Xl[e]:(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease")}function xs({gameState:o,vfx:e}){let t=Ad(null);return bd(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,l=new Set,c=new Set,u=[],d=T=>{n.style.transition="",n.style.opacity=String(T)},p=()=>{n.play().catch(T=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+T)})},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(T=>{let A=!1,w=()=>x(),b=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),x()},x=()=>{A||(A=!0,c.delete(x),n.removeEventListener("loadeddata",w),n.removeEventListener("error",b),T())};c.add(x),n.addEventListener("loadeddata",w),n.addEventListener("error",b),(n.readyState>=2||n.error)&&x()}),f=(T,A,w)=>{let b=A?.duration??0,x=++s;return w.instant||b<=0?(d(T),Promise.resolve()):new Promise(F=>{let q=!1,Q=null,Ee=()=>{q||(q=!0,c.delete(Ee),Q!==null&&clearTimeout(Q),s===x&&t.current&&d(T),F())};c.add(Ee),n.style.transition=`opacity ${b}ms ${Cd(o,A?.easing)}`,n.offsetWidth,n.style.opacity=String(T),Q=setTimeout(Ee,b)})},m=T=>{r||(r=!0,i=T,o.mountState(e,{show:async A=>{a=!0;let w={instant:!1};l.add(w);try{if(await h(),!t.current)return;n.playbackRate=A?.rate??e.config.playbackRate,e.state.paused||p(),await f(A?.opacity??e.config.opacity,A,w)}finally{l.delete(w)}},hide:async A=>{a=!0;let w={instant:!1};l.add(w);try{await f(0,A,w),t.current&&n.pause()}finally{l.delete(w)}},pause:()=>{n.pause()},resume:()=>{p()},setRate:A=>{n.playbackRate=A}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&d(e.config.opacity)},0)))},v=()=>m(!1),C=()=>{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"],()=>{l.size===0&&c.size===0||(l.forEach(T=>{T.instant=!0}),[...c].forEach(T=>T()),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",C),n.readyState>=3?m(!1):n.error&&C(),()=>{n.removeEventListener("canplay",v),n.removeEventListener("error",C),document.removeEventListener("visibilitychange",y),g.cancel(),u.forEach(T=>T()),[...c].forEach(T=>T()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),Td.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 xd from"clsx";import wd,{useCallback as kd,useEffect as Jo,useRef as Pd}from"react";function ws({children:o,className:e,gameState:t}){let{ratio:n}=he(),i=I(),[r]=le(),s=Pd(null),a=i.config.minWidth,l=i.config.minHeight,c=kd(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,l),r()},[r,t.logger,l,a,n]);return Jo(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Jo(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Jo(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,l,a]),Jo(()=>t.events.on(L.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),wd.createElement(Tl,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:l,debounceMs:i.config.ratioUpdateInterval,className:xd(e),onUpdate:c},o)}import Ql,{useEffect as Ed,useRef as Dd,useState as Jl}from"react";function ks({src:o,width:e,height:t}){let[n,i]=Jl({x:0,y:0}),[r,s]=Jl(!1),a=Dd(null),{ratio:l}=he();return Ed(()=>{let c=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",c),()=>{window.removeEventListener("mousemove",c)}},[r]),Ql.createElement(Wt,{ref:a,className:"overflow-hidden absolute"},Ql.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(${l.state.scale})`},alt:""}))}import _l from"react";import nn from"react";function Ps({error:o,errorInfo:e}){return I().config.app.debug?nn.createElement("div",{className:"text-left"},nn.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),nn.createElement("p",{className:"text-red-700"},"Message: ",o.message),nn.createElement("pre",null,"Error Stack: ",o?.stack),nn.createElement("pre",null,"Component Stack: ",e?.componentStack),nn.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):nn.createElement("div",{className:"bg-white w-full h-full"},nn.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),nn.createElement("p",null,"Please contact the game developer for further assistance."))}var _o=class extends _l.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?_l.createElement(Ps,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import tc from"clsx";import U,{useEffect as Mt,useReducer as nc,useState as $n}from"react";import{flushSync as ic}from"react-dom";import{useRef as Ld}from"react";import{useEffect as Rd}from"react";function Zl({gameState:o}){let e=Ld(null);return Rd(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(L.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import Pi,{useEffect as Id}from"react";function Es({gameState:o}){let[e]=le(),{ratio:t}=he(),n=o.notificationMgr;Id(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return Pi.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"},Pi.createElement(i,{notifications:n.toArray()}))}function ec({notifications:o}){return Pi.createElement(Go,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>Pi.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},Pi.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function oc({story:o=pi.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:l,onError:c,children:u,active:d=!0}){let[p,h]=nc(D=>D+1,0),[f,m]=nc(D=>D+1,0),[v,C]=$n(0),g=I(),[y]=$n(()=>new L(g,{update:h,forceUpdate:()=>{y.logger.weakWarn("Player","force update"),ic(()=>{h()})},forceRemount:()=>{y.logger.weakWarn("Player","force remount"),ic(()=>{C(D=>D+1),h()})},next:Ae})),T=U.createRef(),A=U.createRef(),[w,b]=$n(!1),x=U.useRef(!1),F=U.useRef(null),q=U.useRef(null),{preloaded:Q}=zt(),[Ee,je]=$n(!1),Tt=U.useRef(!1),[pt,qt]=$n(!1),dt=U.useRef(!1),be=U.useRef(null),bt=U.useRef(!1),[Z]=$n(new Map);function De(D){return{game:g,gameState:y,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable(),scene:D}}function Ae(){let D=()=>{Z.forEach(M=>M.cancel())};if(y.rollLock.isLocked())return;D();let W=!1,ne=0;for(;!W;){if(ne++>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(F.current===M)break;F.current=M,M.onSettled(()=>{M.isFailed()||(F.current===M&&(F.current=null),Ae())}),M.onFailed(fe=>{F.current===M&&(F.current=null),y.logger.error("Player",fe)}),W=!0;break}if(M instanceof Dn){if(q.current===M)break;q.current=M,M.nextUnlock().then(()=>{q.current===M&&(q.current=null),Ae()}),W=!0;break}if(Xe.isCalledActionResult(M)&&M.wait&&Xe.isStackModelsAwaiting(M.wait.type,M.wait.stackModels)){if(F.current===M)break;if(F.current=M,M.wait){let fe=Xe.executeStackModelGroup(M.wait.type,M.wait.stackModels);fe.then(()=>{F.current===M&&(F.current=null),Ae()}),fe.onFailed(Ce=>{F.current===M&&(F.current=null),y.logger.error("Player",Ce)})}W=!0;break}y.handle(M)}y.stage.update()}Mt(()=>{y.audioManager.initialize()},[]),Mt(()=>(g.getLiveGame().setGameState(y),o&&!g.getLiveGame().isPlaying()&&g.getLiveGame().loadStory(o),o?.entryScene&&!y.getPreloadingScene()&&!y.getLastScene()&&y.preloadScene(o.entryScene),y.playerCurrent=T.current,y.mainContentNode=A.current,()=>{g.getLiveGame().setGameState(void 0),y.playerCurrent=null}),[g,o]),Mt(()=>st(()=>{b(!0);let D=y.getLastScene(),W=[];D?W.push(D.events.once("event:scene.mount",()=>{y.stage.next()}).cancel):y.stage.next();let ne=y.events.on(L.EventTypes["event:state.end"],()=>{l&&l({game:g,gameState:y,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable()})});return y.stage.update(),()=>{D&&W.forEach(M=>M()),ne.cancel()}}),[]),Mt(()=>st(()=>{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]),Mt(()=>st(()=>{if(Ee&&s&&!Tt.current){Tt.current=!0;let D=be.current||y.getLastScene()||y.getPreloadingScene(),W=De(D);s(W)}}),[Ee]),Mt(()=>st(()=>{if(pt&&!dt.current){dt.current=!0;let D=be.current||y.getLastScene()||y.getPreloadingScene(),W=De(D);g.markPreloadComplete(W)&&r&&r(W)}}),[pt]),Mt(()=>y.events.on(L.EventTypes["event:state.scene.mount"],D=>{be.current||(be.current=D,m())}).cancel,[]),Mt(()=>{if(!pt||!d||bt.current||g.isFirstSceneReady())return;let D=be.current||y.getLastScene();if(!D)return;let W=null,ne=null,M=!1;bt.current=!0;let fe=()=>{M=!0,bt.current=!1;let Ce=De(D);g.markFirstSceneReady(Ce)&&a&&a(Ce)};return typeof requestAnimationFrame=="function"?W=requestAnimationFrame(()=>{ne=setTimeout(fe,0)}):ne=setTimeout(fe,0),()=>{M||(bt.current=!1,W!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(W),ne!==null&&clearTimeout(ne))}},[d,f,p,pt]),Mt(()=>Q.events.depends([Q.events.on($e.EventTypes["event:preloaded.ready"],()=>{je(!0),y.stage.update(),o&&g.getLiveGame().isPlaying()&&Ae()}),Q.events.on($e.EventTypes["event:preloaded.complete"],()=>{qt(!0)})]).cancel,[]),Mt(()=>{y.flushDep=p},[p]);let N=e||g.config.width,R=t||g.config.height;return U.createElement(_o,{onError:c},U.createElement("div",{style:{width:typeof N=="number"?`${N}px`:N,height:typeof R=="number"?`${R}px`:R},className:tc(n,"__narraleaf_content-player"),ref:T,tabIndex:0},U.createElement(ws,{className:tc("flex-grow overflow-auto"),gameState:y},U.createElement(rs,{gameState:y}),U.createElement(Zl,{gameState:y}),U.createElement(Wt,{className:"absolute",ref:A,style:{cursor:y.game.config.cursor?"none":"auto",overflow:y.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},g.config.cursor&&U.createElement(ks,{src:g.config.cursor,width:g.config.cursorWidth,height:g.config.cursorHeight}),U.createElement(Md,{show:Ee&&d,key:v},U.createElement(Zr,null,U.createElement(kl,{state:y}),U.createElement(Ll,{state:y}),U.createElement(Nd,{state:y},U.createElement("div",{className:"w-full h-full absolute",style:{isolation:"isolate"},"data-element-type":"scene-group"},y.getSceneElements().map(D=>U.createElement(ys,{key:"scene-"+D.scene.getId(),state:y,elements:D}))),U.createElement(Gd,{state:y}),y.getVideos().map((D,W)=>U.createElement("div",{className:"w-full h-full absolute",key:"video-"+W,"data-element-type":"video"},U.createElement(Cs,{gameState:y,video:D}))),y.getVfx().map(D=>U.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}},U.createElement(xs,{gameState:y,vfx:D})))),y.getSceneElements().map(D=>U.createElement(Ts,{key:"scene-dialogs-"+D.scene.getId(),state:y,elements:D})),U.createElement(Hd,{NvlComponent:g.config.nvlDialog}))),U.createElement(Ml,{state:y}),U.createElement(fl,null,u),U.createElement(Es,{gameState:y})))))}function Md({children:o,show:e}){return U.createElement(U.Fragment,null,e?o:null)}function Nd({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?U.createElement(jl,{state:o,camera:t},e):U.createElement(U.Fragment,null,e)}function Gd({state:o}){let e=U.useRef(null);return Mt(()=>(o.stageTransition.registerOverlayHost(e.current),()=>{o.stageTransition.registerOverlayHost(null)}),[]),U.createElement("div",{className:"w-full h-full absolute pointer-events-none",ref:e,"data-element-type":"stage-transition-overlay-host"})}function Hd({NvlComponent:o}){let{dialogs:e,state:t}=Kt(),i=I().getLiveGame().getGameState(),r=U.useMemo(()=>e.map((s,a)=>{let l=s.sentence.evaluate(we.getCtx({gameState:i})),c=t.activeDialogId===s.id,u=c&&t.phase==="typing";return{entry:s,index:a,isActive:c,gameState:i,words:l,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return U.createElement(o,{dialogs:r})}import"client-only";import jn from"react";function rc({children:o,game:e}){return jn.createElement(jn.Fragment,null,jn.createElement(Oa,null,jn.createElement(Ma,{game:e},jn.createElement(ul,null,jn.createElement(Fa,null,o)))))}var Fd=(l=>(l.image="narraleaf:image",l.text="narraleaf:text",l.layer="narraleaf:layer",l.scene="narraleaf:scene",l.video="narraleaf:video",l.vfx="narraleaf:vfx",l.camera="narraleaf:camera",l.puppet="narraleaf:puppet",l))(Fd||{});import Od from"clsx";import xt,{useEffect as sc,useRef as Vd,useState as Ud}from"react";import{motion as Wd,useIsPresent as Bd}from"motion/react";var zd={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function Kd({children:o,initial:e,transition:t,...n}){let i=I(),r=Lt(),{ratio:s}=he(),[a]=fn(se.Preferences.showDialog),l=Vd(null),[c]=xn("nextAction"),u=Bd(),[d,p]=Ud(null);function h(){r.config.gameState.isAdvanceSuspended()||r.requestComplete()}return sc(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
64
|
+
at Say.tsx: onElementClick`);return}let f=v=>{v.repeat||r.config.gameState.isAdvanceSuspended()||i.keyMap.match("nextAction",v.key)&&r.requestComplete()};window.addEventListener("keydown",f);let m=r.events.on(Ne.Events.simulateClick,()=>{l.current&&l.current.click()});return()=>{window.removeEventListener("keydown",f),m.cancel()}},[r,c]),sc(()=>{let f=i.preference.onPreferenceChange(se.Preferences.autoForward,m=>{m&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{f.cancel()}},[r]),xt.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},xt.createElement("div",{className:Od("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:h,style:{...Jn(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:l},xt.createElement(is,{value:d},xt.createElement(Wd.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)),xt.createElement("div",{"data-element-type":"dialog-overlay",className:"absolute inset-0 pointer-events-none",ref:p})))}function ac({children:o,...e}){let t=Lt();return!t.config.action.sentence||!t.config.action.words?null:xt.createElement(Kd,{...e},o)}var Hp=ac;function lc(){return xt.createElement(ac,null,xt.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},xt.createElement($r,null),xt.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},xt.createElement(tn,null),xt.createElement(hn,{...zd}))))}var Ei={say:lc,menu:$l,notification:ec,nvlDialog:ns};var Zo=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 Di=class{constructor(e={}){this.keyMap=e;this.events=new Y}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 cc=(e=>(e.game="game",e))(cc||{}),Qe=class Qe{constructor(e){this.hooks=new Wi;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new fi(Qe.DefaultPreference);this.audioBuses=new oi(()=>this.config.audioBuses??[],pa(this.preference));this.keyMap=new Di({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new Y;this.puppetBackends=new Yo;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=K(Qe.DefaultConfig,e),this.plugins=new Zo(this),this.router=new mn(this)}configure(e){let[t,n]=Zs(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=K(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 Ot(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:Ei.notification,menu:Ei.menu,dialog:Ei.say,nvlDialog:Ei.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100,audioBuses:[]},Qe.GameSettingsNamespace=cc,Qe.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var se=Qe;var er=class er extends ${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=er.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 l=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:[l]}}}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 l=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:[l]}}}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 l=new S,c=new ke(a);return t.timelines.attachTimeline(c),a.then(()=>{l.resolve({type:this.type,node:this.contentNode.getChild()})}),l.onSkipControllerRegister(u=>{u.onAbort(()=>{c.abort()})}),l}else if(this.type===oe.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new S,a=new S,l=new ke(a);t.timelines.attachTimeline(l);let c=t.game.preference,u=c.getPreference(se.Preferences.autoForward),d=c.getPreference(se.Preferences.gameSpeed),p=u?t.game.config.autoForwardDelay/d:null,h=!1,f=null,m=null,v=null,C=()=>{m?.cancel(),v?.cancel(),f&&(clearTimeout(f),f=null)},g=()=>{h||(h=!0,C(),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,C(),l.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[c]=this.contentNode.getContent();throw new Oe(`Jump target label "${c}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),l=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},c=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(c,u)},[l]),a.clearMainStack().getStackModelForce().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(),l=this.type===oe.label?"label":"jump";return super.stringifyWithContent("Control",`${l}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};er.ActionTypes=oe;var re=er;var Be=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=j.from(t);return this.pushWithLambda(re.ActionTypes.while,n,i)}breakLoop(){let t=new re(this.chain(),re.ActionTypes.break,new k().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 k().setContent([]));return this.chain(t)}label(t){let n=new re(this.chain(),re.ActionTypes.label,new k().setContent([t]));return this.chain(n)}jump(t){let n=new re(this.chain(),re.ActionTypes.jump,new k().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new re(this.chain(),t,new k().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 k().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new re(this.chain(),t,new k().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?_t.say(n).getActions():We.toActions([n]))}};var z=class z extends ze{static get DefaultUserConfig(){return z._defaultUserConfig??(z._defaultUserConfig=new B({name:"(anonymous)",autoInit:!0,src:z.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...ee.DefaultTransformState.getDefaultConfig()},{position:e=>H.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):z.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:z.isLayeredSrc(e)?null:z.isTagSrc(e)&&e.config.src.resolve?z.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):z.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=>z.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(z.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new z({src:e})}constructor(e={}){super();let t=z.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 Be,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 Se(n,Se.ActionTypes.setAppearance,new k().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Be,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 ie("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:z.StateSerializer.serialize(this.state),transformState:ee.TransformStateSerializer.serialize(this.transformState.get()),loop:this._serializeLoop()}}fromData(e){return this.state=z.StateSerializer.deserialize(e.state),this.transformState.resetTo(ee.deserialize(e.transformState).get()),this._deserializeLoop(e.loop),this}_applyTransition(e,t){return new ye(this.chain(),pe.applyTransition,new k().setContent([e,t]))}_init(e,t){return new ye(this.chain(),pe.init,new k().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new Se(this.chain(),Se.ActionTypes.initWearable,new k().setContent([e]))}_flush(){return new Se(this.chain(),Se.ActionTypes.flush,new k)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState.resetTo(this.getInitialTransformState(this.userConfig).get()),this}resolveTags(e,t){if(!z.isTagSrc(this))throw new Error(`Tag not defined
|
|
65
|
+
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(l=>{let c=n.get(l);c&&i.set(c,l)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let l=i.get(a);if(!l)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(l)}),r}_setAppearanceSync(e){if(P.isImageSrc(e)||P.isColor(e)){if(P.isColor(e)&&!this.config.isBackground)throw new ie("Color src is not allowed for non-background image");this.state.currentSrc=e;return}if(!z.isTagSrc(this))throw this._mixedSrcError();let t=this.state.currentSrc,n=this.resolveTags(t,e);this.state.currentSrc=n}_mixedSrcError(){throw new ie(`Trying to mix src and tags
|
|
63
66
|
To better understand the behavior of the image, you cannot mix static src and tags in the same image. `)}_invalidSrcHandlerError(){throw new Error("Invalid src handler, If you are using tags, config.src must be a function that resolves the src from the tags. If you are using src, config.src must be a string or StaticImageData")}_invalidWearableError(e){throw new Error(`Invalid wearable
|
|
64
67
|
Wearable must be an Image with isWearable set to true
|
|
65
68
|
It seems like you are trying to add a non-wearable image to wearables
|
|
66
69
|
Image below violates the rule:
|
|
67
70
|
`+e)}_invalidTagGroupDefinitionError(e,t=!1){throw new Error("Invalid tag group definition. Tags in groups must be unique and not conflicting with each other."+(e?`
|
|
68
71
|
Tag "${e}" belongs to more than one group.`:"")+(t?`
|
|
69
|
-
Layers offering the same tag set share one group, so a shared tag means two layers offer different sets. Repeat the whole set on every layer that follows the group, using null where that layer draws nothing.`:""))}_setSrc(e,t,n){return n&&e.chain(this._applyTransition(n.copy(),i=>i._setPrevSrc(
|
|
72
|
+
Layers offering the same tag set share one group, so a shared tag means two layers offer different sets. Repeat the whole set on every layer that follows the group, using null where that layer draws nothing.`:""))}_setSrc(e,t,n){return n&&e.chain(this._applyTransition(n.copy(),i=>i._setPrevSrc(Se.resolveCurrentSrc(this))._setTargetSrc(t))),new Se(e,Se.ActionTypes.setSrc,new k().setContent([t]))}_setIsBackground(e){return Object.assign(this.config,{isBackground:e}),this}registerSrc(){let e=this.config.src;return e?.slots?z.getAllLayerSrc(this).forEach(t=>this.srcManager.registerRawSrc(t)):e?.resolve?this.srcManager.registerRawSrc(z.getSrcFromTags(e.defaults,e.resolve)):P.isImageSrc(this.state.currentSrc)&&this.srcManager.registerRawSrc(P.srcToURL(this.state.currentSrc)),this}static collectLayerGroups(e){let t=[],n=new Set;for(let i of e){if(!z.isLayerVariants(i))continue;let r=Object.keys(i),s=[...r].sort().join("\0");n.has(s)||(n.add(s),t.push(r))}return t}static normalizeSrcDefinition(e){return z.isLayeredDefinition(e)?{groups:z.collectLayerGroups(e.layers),defaults:[...e.defaults],resolve:null,slots:e.layers}:z.isTagDefinition(e)?{groups:e.groups,defaults:[...e.defaults],resolve:e.resolve,slots:null}:null}createImageConfig(e){let t=e.get();return z.DefaultImageConfig.create({...t,src:z.normalizeSrcDefinition(t.src)})}getInitialState(){return z.DefaultImageState.create().assign({currentSrc:z.getInitialSrc(this.userConfig.get())}).get()}getInitialTransformState(e){let[t]=e.extract(ee.DefaultTransformState.keys());return new ee(ee.DefaultTransformState.create(t.get()).get())}checkConfig(){for(let e of this.config.wearables)if(!e.config.isWearable)throw this._invalidWearableError(JSON.stringify(e.config));if(z.isTagSrc(this)){let e=this.config.src,t=new Set;for(let r of e.groups)for(let s of r){if(t.has(s))throw this._invalidTagGroupDefinitionError(s,!!e.slots);t.add(s)}let n=this.constructTagMap(e.groups),i=new Set;for(let r of e.defaults){if(i.has(r))throw new Error(`Tag conflict
|
|
70
73
|
Tag "${r}" is conflicting with another tag
|
|
71
74
|
Error found in config.tag.defaults`);if(!n.has(r))throw new Error(`Tag not found
|
|
72
75
|
Tag "${r}" is not defined in tagDefinitions
|
|
73
|
-
Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}if(e.slots){let r=new Set(e.defaults);for(let s of e.groups)if(!s.some(a=>r.has(a)))throw new
|
|
74
|
-
The group with tags "${s.join(", ")}" needs exactly one of them listed in src.defaults`)}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let i of n)t.set(i,n);return t}_setDarkness(e,t,n,i){return new
|
|
76
|
+
Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}if(e.slots){let r=new Set(e.defaults);for(let s of e.groups)if(!s.some(a=>r.has(a)))throw new ie(`Layer has no default
|
|
77
|
+
The group with tags "${s.join(", ")}" needs exactly one of them listed in src.defaults`)}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let i of n)t.set(i,n);return t}_setDarkness(e,t,n,i){return new Se(e,Se.ActionTypes.setDarkness,new k().setContent([t,n,i]))}};z.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",z.StateSerializer=new Ye,z._defaultUserConfig=null,z.DefaultImageConfig=new B({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),z.DefaultImageState=new B({currentSrc:z.DefaultImagePlaceholder,darkness:0});var G=z;var Te=class extends Vt{constructor(){super(...arguments);this._detached=!1}_setDetached(t){return this._detached=t,this}_isDetached(){return this._detached}_setPrevLayers(t){return this._prevLayers=t,this}_setTargetLayers(t){return this._targetLayers=t,this}_getPrevLayers(){return this._prevLayers}_getTargetLayers(){return this._targetLayers}_isLayered(){return!!this._prevLayers||!!this._targetLayers}_setPrevSrc(t){return this._prevSrc=t,this}_setTargetSrc(t){return this._targetSrc=t,this}_setCurrentSrc(t){return this._currentSrc=t,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),n}asPrev(t){return super.asPrev((...n)=>K(t(...n),this._srcToProps(this._prevSrc)))}asTarget(t){return super.asTarget((...n)=>K(t(...n),this._srcToProps(this._targetSrc)))}_srcToProps(t){if(this._isLayered()||this._detached)return{};if(P.isColor(t))return{src:G.DefaultImagePlaceholder,style:{backgroundColor:P.isRGBAColor(t)?P.RGBAColorToHex(t):t}};if(P.isImageSrc(t))return{src:P.srcToURL(t)};throw new ie("Image transition src cannot be identified, using: "+t)}};var Li=class o extends Te{constructor(e){super(),this.from=e.from,this.to=e.to,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.from,end:this.to,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{filter:`brightness(${1-e})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o({from:this.from,to:this.to,duration:this.duration,easing:this.easing})}};var Ri=class Ri extends ${static resolveTagSrc(e,t){if(!G.isTagSrc(e)||!e.config.src.resolve)throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return G.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(G.isLayeredSrc(e))throw e._mixedSrcError();if(G.isStaticSrc(e))return P.isImageSrc(e.state.currentSrc)?P.srcToURL(e.state.currentSrc):e.state.currentSrc;if(G.isTagSrc(e)&&e.config.src.resolve)return G.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===mt.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new S(s=>s);return i.createWearable(n),e.getExposedStateAsync(n,s=>{s.initDisplayable(()=>{r.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.disposeWearable(s)},[n]),r}else if(this.type===mt.setSrc){let n=this.contentNode.getContent()[0];if(P.isColor(n)&&!this.callee.config.isBackground)throw new ie("Color src is not allowed for non-background image");let i=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{this.callee.state.currentSrc=r},[i]),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else{if(this.type===mt.flush)return super.executeAction(e,t);if(this.type===mt.setAppearance){let[n,i]=this.contentNode.getContent();if(!G.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],l=()=>{this.callee.state.currentSrc=a};if(G.isLayeredSrc(this.callee)){if(e.logger.debug("Image - Set Appearance (layered)",s),i){let d=new S(m=>m).registerSkipController(new V(()=>super.executeAction(e,t)));i._setPrevLayers(G.getSrcURLs(this.callee))._setTargetLayers(G.getSrcURLs(this.callee,s));let h=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,d.resolve(super.executeAction(e,t))}),f=e.timelines.attachTimeline(d).attachChild(h);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:f},l,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},l),e.stage.update(),e.getExposedState(this.callee)?.flush(),super.executeAction(e,t)}let c=this.callee.config.src.resolve;if(!c)throw this.callee._invalidSrcHandlerError();let u=G.getSrcFromTags(s,c);if(e.logger.debug("Image - Set Appearance",s,u),i){let d=new S(m=>m).registerSkipController(new V(()=>super.executeAction(e,t)));i._setPrevSrc(Ri.resolveCurrentSrc(this.callee))._setTargetSrc(u);let h=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,d.resolve(super.executeAction(e,t))}),f=e.timelines.attachTimeline(d).attachChild(h);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:f},l,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},l),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else if(this.type===mt.setDarkness){let[n,i,r]=this.contentNode.getContent(),s=this.callee.state.darkness,a=()=>{this.callee.state.darkness=s},l=e.getExposedStateForce(this.callee);if(i){let c=new S(h=>h),u=new Li({from:s,to:n,duration:i,easing:r});if(G.isLayeredSrc(this.callee)){let h=G.getSrcURLs(this.callee);u._setPrevLayers(h)._setTargetLayers(h)}else{let h=Ri.resolveCurrentSrc(this.callee);u._setPrevSrc(h)._setTargetSrc(h)}let d=l.applyTransition(u,()=>{this.callee.state.darkness=n,c.resolve(super.executeAction(e,t))}),p=e.timelines.attachTimeline(c).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:p},()=>{c.isSettled()||c.abort(),d.abort(),a()}),c}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),l.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};Ri.ActionTypes=mt;var Se=Ri;var Ds=class o{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),s=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new o(n,i,r,s)}constructor(e,t,n,i=1){this.r=e,this.g=t,this.b=n,this.a=i}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},Nt=class Nt{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||Nt.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return Nt.isHexString(e)||Nt.isNamedColor(e)||Nt.isRGBAColor(e)}static isNamedColor(e){return Qs(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),i=e.b.toString(16).padStart(2,"0"),r=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${i}${r}`}static colorToString(e){if(Nt.isHexString(e))return e;if(Nt.isNamedColor(e))return e;if(Nt.isRGBAColor(e))return Nt.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[i,r]=e,[s,a]=t,l=this.calc(i,s),c=this.calc(r,a),u=n.invertX?{right:l}:{left:l},d=n.invertY?{bottom:c}:{top:c};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...d}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let i=typeof t=="string"?"+":t<0?"-":"+",r=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${i} ${r})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};Nt.RGBColor=Ds;var P=Nt,Ls=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},He=class o extends Ls{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},fo=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,i=[],r=new Set,s=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!s.length)return null;for(i.push(s[0]);i.length;){let a=i.shift();this.checkAction(e,a,{imageStates:t,scenes:n},r);let l=a.contentNode.getChild();l&&l.action&&i.push(l.action)}return t}checkAction(e,t,{imageStates:n,scenes:i},r){if(t instanceof Se)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof ae){let s=t.callee;if(i.has(s.config.name)){if(i.get(s.config.name)!==s){let a=`Scene with name: ${s.config.name} is duplicated
|
|
75
78
|
Scene: ${s.config.name}
|
|
76
79
|
|
|
77
|
-
At: ${t.__stack}`;throw new
|
|
80
|
+
At: ${t.__stack}`;throw new He(a)}}else i.set(s.config.name,s);if(t.type===_.jumpTo){let a=t.contentNode.getContent()[0],l=e.getScene(a,!0);if(r.has(l))return;r.add(l)}}}checkImage(e,t){if(t.type===mt.setSrc){let i=t.contentNode.getContent()[0];P.isImageURL(i)&&P.isExternalSrc(i)&&(e.usedExternalSrc=!0)}}},ie=class o extends Error{static toMessage(e,t){let n=[];return n.push(...Array.isArray(e)?e:[e]),t&&n.push(...Array.isArray(t)?t.map(o.getActionTrace):[o.getActionTrace(t)]),n.join("")}static getActionTrace(e){return`
|
|
78
81
|
Using action (id: ${e.getId()})
|
|
79
|
-
at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},E=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Fe=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function xd(o,e){return te.color(o,e)}function wd(o){return te.bold(o)}function kd(o){return te.italic(o)}var Cs=class o extends Ce{constructor(e){super(),this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(e=>({style:{opacity:1-e}})),this.asTarget(e=>({style:{opacity:e}}))]}}copy(){return new o({duration:this.duration,easing:this.easing})}};var xs=class o extends Ce{constructor(e){super(),this.duration=e.duration,this.offset=e.offset??[0,0],this.easing=e.easing}createTask(e){let{invertX:t,invertY:n}=e.getStory().getInversionConfig();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.offset[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.offset[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((i,r,s)=>({style:{opacity:i,translate:`${t?-r:r}px ${n?-s:s}px`}}))]}}copy(){return new o({duration:this.duration,offset:this.offset,easing:this.easing})}};function J(o){return o<0?0:o>1?1:o}function Xl(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function ws(o){return{position:"absolute",top:"50%",left:"50%",width:"100%",height:"100%",transform:"translate(-50%, -50%)",backgroundColor:o}}function Jl(o){switch(o){case"left":return"to left";case"top":return"to top";case"bottom":return"to bottom";case"right":default:return"to right"}}function Zl(o){return o==="vertical"?"to right":"to bottom"}var ks=class o extends Ce{constructor(e){super(),this.duration=e.duration,this.blur=e.blur??16,this.easing=e.easing}createTask(){let e=Math.max(0,this.blur);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-J(t),filter:`blur(${e*J(t)}px)`}})),this.asTarget(t=>({style:{opacity:J(t),filter:`blur(${e*(1-J(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var Ps=class o extends Ce{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisSign(){switch(this.direction){case"right":return{axis:"x",sign:1};case"top":return{axis:"y",sign:-1};case"bottom":return{axis:"y",sign:1};case"left":default:return{axis:"x",sign:-1}}}translate(e){let{axis:t}=this.axisSign(),n=`${e}%`;return{translate:t==="x"?`${n} 0px`:`0px ${n}`}}createTask(){let{sign:e}=this.axisSign();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*J(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-J(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};var Es=class o extends Ce{constructor(e){super(),this.duration=e.duration,this.ev=e.ev??4.6,this.lift=e.lift??.04,this.hold=e.hold??0,this.easing=e.easing}burnStyle(e){let t=J(e);if(t<=0)return{filter:"none"};let n=J(this.lift)*t,i=Math.pow(2,Math.max(0,this.ev)*t);return{filter:`invert(1) brightness(${1-n}) invert(1) brightness(${i})`}}createTask(){let t=(1-J(this.hold))/2,n=1-t,i=.5,r=s=>s<=t?t<=0?1:s/t:s>=n?n>=1?1:(1-s)/(1-n):1;return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(s=>({style:{opacity:s<i?1:0,...this.burnStyle(r(s))}})),this.asTarget(s=>({style:{opacity:s<i?0:1,...this.burnStyle(r(s))}}))]}}copy(){return new o({duration:this.duration,ev:this.ev,lift:this.lift,hold:this.hold,easing:this.easing})}};function V(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function qo(o,e,t){return o<e?e:o>t?t:o}var tn=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${V(t)}deg`:Jl(t);return{mask:(r,s)=>{let a=-n+(s?1-J(r):J(r))*(100+n);return s?`linear-gradient(${i}, transparent ${V(a)}%, #000 ${V(a+n)}%)`:`linear-gradient(${i}, #000 ${V(a)}%, transparent ${V(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${V(t)}deg`,`${V(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let l=-n+J(s)*(50+n);if(!a){let c=u=>`linear-gradient(${u}, #000 ${V(l)}%, transparent ${V(l+n)}%)`;return`${c(i)}, ${c(r)}`}if(l<0){let c=J((l+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${V(50-l-n)}%, rgba(0,0,0,${V(c)}) 50%, transparent ${V(50+l+n)}%)`}return`linear-gradient(${i}, transparent ${V(50-l-n)}%, #000 ${V(50-l)}%, #000 ${V(50+l)}%, transparent ${V(50+l+n)}%)`}}}static iris(e={}){let t=e.center??"50% 50%",n=Math.max(0,e.feather??12),i=e.shape??"circle";return{mask:(r,s)=>{if(s){let l=(1-J(r))*150;return`radial-gradient(${i} at ${t}, transparent ${V(l-n)}%, #000 ${V(l)}%)`}let a=J(r)*150;return`radial-gradient(${i} at ${t}, #000 ${V(a-n)}%, transparent ${V(a)}%)`}}}static clock(e={}){let t=e.center??"50% 50%",n=e.from??0,i=Math.max(0,e.feather??24),r=e.direction??"clockwise";return{mask:(s,a)=>{let l=r==="counterclockwise"!=!!a,c=-i+J(s)*(360+i);if(l){let d=Math.max(0,360-c-i),p=Math.max(d,360-c);return`conic-gradient(from ${V(n)}deg at ${t}, transparent ${V(d)}deg, #000 ${V(p)}deg)`}let u=Math.max(0,c);return`conic-gradient(from ${V(n)}deg at ${t}, #000 ${V(u)}deg, transparent ${V(Math.max(u,c+i))}deg)`}}}static fan(e={}){let t=Math.max(1,Math.round(e.blades??4)),n=e.center??"50% 50%",i=e.from??0,r=Math.max(0,e.feather??10),s=360/t;return{mask:(a,l)=>{let c=-r+(l?1-J(a):J(a))*(s+r),u=qo(c,0,s),d=qo(c+r,0,s),p=`repeating-conic-gradient(from ${V(i)}deg at ${n}`;return l?`${p}, transparent 0deg, transparent ${V(u)}deg, #000 ${V(d)}deg, #000 ${V(s)}deg)`:`${p}, #000 0deg, #000 ${V(u)}deg, transparent ${V(d)}deg, transparent ${V(s)}deg)`}}}static blinds(e={}){let t=e.orientation??"horizontal",n=Math.max(1,e.slats??8),i=Math.max(0,e.feather??0),r=typeof t=="number"?`${V(t)}deg`:Zl(t),s=100/n;return{mask:(a,l)=>{let c=-i+(l?1-J(a):J(a))*(s+i),u=qo(c,0,s),d=qo(c+i,0,s);return l?`repeating-linear-gradient(${r}, transparent 0, transparent ${V(u)}%, #000 ${V(d)}%, #000 ${V(s)}%)`:`repeating-linear-gradient(${r}, #000 0, #000 ${V(u)}%, transparent ${V(d)}%, transparent ${V(s)}%)`}}}static dots(e={}){let t=Math.max(1,e.rows??6),n=Math.max(1,e.cols??10),i=Math.max(0,e.feather??20),s=J(e.stagger??0)*.5,a=(l,c,u)=>{let d=-i+J(c)*(100+i);return u?`radial-gradient(circle farthest-corner at ${l}, transparent ${V(d)}%, #000 ${V(d+i)}%)`:`radial-gradient(circle farthest-corner at ${l}, #000 ${V(d)}%, transparent ${V(d+i)}%)`};return{size:`${V(100/n)}% ${V(100/t)}%`,repeat:"repeat",mask:(l,c)=>{let u=c?1-J(l):J(l);if(s<=0)return a("50% 50%",u,c);let d=J(u/(1-s)),p=J((u-s)/(1-s));return c?`${a("50% 50%",p,!0)}, ${a("0% 0%",d,!0)}`:`${a("50% 50%",d)}, ${a("0% 0%",p)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return Xl(e.mask(t,n),e.size,e.repeat)}};var Ds=class o extends Ce{constructor(e){super(),this.duration=e.duration,this.color=e.color??"#000000",this.hold=e.hold??.3,this.pattern=e.pattern??null,this.inverted=e.inverted??!1,this.uncover=e.uncover??"retreat",this.easing=e.easing}coverStyle(e,t){if(!this.pattern)return{...ws(this.color),opacity:J(e)};let n={...ws(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...tn.toStyle(this.pattern,e,!this.inverted)}:{...n,...tn.toStyle(this.uncover,e)}:{...n,...tn.toStyle(this.pattern,e,this.inverted)}}createTask(){let t=(1-J(this.hold))/2,n=1-t,i=.5,r=s=>s<=t?t<=0?1:s/t:s>=n?n>=1?1:(1-s)/(1-n):1;return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(s=>({style:{opacity:s<i?1:0}})),this.asTarget(s=>({style:{opacity:s<i?0:1}})),s=>({src:I.DefaultImagePlaceholder,style:this.coverStyle(r(s),s>=n)})]}}copy(){return new o({duration:this.duration,color:this.color,hold:this.hold,pattern:this.pattern??void 0,inverted:this.inverted,uncover:this.uncover,easing:this.easing})}};var Ls=class o extends Ce{constructor(e){super(),this.duration=e.duration,this.pattern=e.pattern,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(e=>({style:tn.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var Kn="http://www.w3.org/2000/svg",Pd="http://www.w3.org/1999/xlink",Ed=.002,Dd=1,Ld=.12,Rd=0,Rs=class o extends Ce{constructor(t){super();this.filterId=null;this.host=null;this.cut=null;this.duration=t.duration,this.rule=P.srcToURL(t.rule),this.feather=Math.min(Dd,Math.max(Ed,t.feather??Ld)),this.inverted=t.inverted??!1,this.easing=t.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(t=>({style:this.styleAt(t)}))]}}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>this.dispose()),n.onCanceled(()=>this.dispose()),n}copy(){return new o({duration:this.duration,rule:this.rule,feather:this.feather,inverted:this.inverted,easing:this.easing})}styleAt(t){if(t>=1)return this.dispose(),{filter:""};let n=this.ensureScaffold();if(!n)return{filter:""};let i=t*(1+this.feather),r=(this.inverted?1:-1)/this.feather,s=(this.inverted?i-1:i)/this.feather;return this.cut?.setAttribute("k3",String(r)),this.cut?.setAttribute("k4",String(s)),{filter:`url(#${n})`}}ensureScaffold(){if(typeof document>"u")return null;if(this.filterId&&this.host)return this.filterId;let t=`nl-rule-${++Rd}`,n=document.createElementNS(Kn,"svg");n.setAttribute("aria-hidden","true"),n.setAttribute("data-element-type","rule-transition"),n.setAttribute("width","0"),n.setAttribute("height","0"),Object.assign(n.style,{position:"absolute",width:"0",height:"0",overflow:"hidden"});let i=document.createElementNS(Kn,"filter");i.setAttribute("id",t),i.setAttribute("color-interpolation-filters","sRGB"),i.setAttribute("primitiveUnits","objectBoundingBox"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("width","100%"),i.setAttribute("height","100%");let r=document.createElementNS(Kn,"feImage");r.setAttribute("href",this.rule),r.setAttributeNS(Pd,"xlink:href",this.rule),r.setAttribute("preserveAspectRatio","none"),r.setAttribute("x","0"),r.setAttribute("y","0"),r.setAttribute("width","1"),r.setAttribute("height","1"),r.setAttribute("result","rule");let s=document.createElementNS(Kn,"feColorMatrix");s.setAttribute("in","rule"),s.setAttribute("type","luminanceToAlpha"),s.setAttribute("result","lum");let a=document.createElementNS(Kn,"feComposite");a.setAttribute("in","lum"),a.setAttribute("in2","lum"),a.setAttribute("operator","arithmetic"),a.setAttribute("k1","0"),a.setAttribute("k2","0"),a.setAttribute("k3","0"),a.setAttribute("k4","0"),a.setAttribute("result","cut");let l=document.createElementNS(Kn,"feComposite");return l.setAttribute("in","SourceGraphic"),l.setAttribute("in2","cut"),l.setAttribute("operator","in"),i.append(r,s,a,l),n.appendChild(i),document.body.appendChild(n),this.filterId=t,this.host=n,this.cut=a,t}dispose(){this.host?.remove(),this.host=null,this.cut=null,this.filterId=null}};var Is=class extends si{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new Y(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var Yo=class{static getActionId(e){return e.getId()}static setActionId(e,t){return e.setId(t),e}static getStaticId(e){return e.getStaticId()}static setStaticId(e,t){return e.setStaticId(t),e}static chainToActions(e){return e.getActions()}static wrapAction(e){let t=Be.isChained(e)?e.getActions():e;return Ke.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}static getLayerSrcs(e,t){return I.getSrcURLs(e,t)}static registerDisplayable(e,t,n=null,i=null){e.findElementByDisplayable(t)||(e.createDisplayable(t,n,i),e.flush())}static setElementId(e,t){e.setId(t)}static setElementStaticId(e,t){e.setStaticId(t)}static getDisplayableTransformProps(e){return{...e.transformState.get()}}static setDisplayableTransformProps(e,t,n,i={}){let r=t.transformState;i.merge===!1?r.forceOverwrite(n):r.assign(Symbol("DevTools.setDisplayableTransformProps"),n),t.markDirty(),e.getExposedState(t)?.updateStyleSync?.(),e.flush()}static getPuppetStatus(e){return e._getStatus()}static onPuppetStatusChange(e,t){return e._onStatusChange(t)}static async describePuppet(e,t){try{return await t._describe()}catch(n){return e.logger.error("DevTools","Puppet backend threw while describing itself",n),null}}static getPuppetState(e){return kt.normalizeState(e.state)}static setPuppetState(e,t,n,i={}){t.state=i.merge===!1?kt.normalizeState(n):kt.mergeState(t.state,n),t._applyState().catch(r=>{e.logger.error("DevTools","Puppet backend threw while applying state",r)}),e.flush()}static async runPuppetCommand(e,t,n,i){try{await t._runCommand(n,i)||e.logger.weakWarn("DevTools",`Puppet command "${n}" was dropped: the puppet is not mounted.`)}catch(r){e.logger.error("DevTools",`Puppet backend threw while running "${n}"`,r)}}static listPuppetBackends(e){return e.listPuppetBackends()}static getCurrentDialog(e){if(e.isNvlMode()){let n=e.getNvlState();if(!n.activeDialogId||n.phase==="idle")return null;let i=e.getNvlDialog(n.activeDialogId);return i?{actionId:i.actionId||null,ended:n.phase==="awaitAdvance",mode:"nvl"}:null}let t=e.getAdvDialogState();return t?{actionId:t.actionId,ended:t.ended,mode:"adv"}:null}static onDialogStateChange(e,t){let n=[e.events.on(L.EventTypes["event:state.dialog.change"],t),e.events.on(L.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};Yo.DynamicPersistent=Mn;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
|
|
82
|
+
at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},E=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Oe=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function $d(o,e){return te.color(o,e)}function jd(o){return te.bold(o)}function qd(o){return te.italic(o)}var Rs=class o extends Te{constructor(e){super(),this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(e=>({style:{opacity:1-e}})),this.asTarget(e=>({style:{opacity:e}}))]}}copy(){return new o({duration:this.duration,easing:this.easing})}};var Is=class o extends Te{constructor(e){super(),this.duration=e.duration,this.offset=e.offset??[0,0],this.easing=e.easing}createTask(e){let{invertX:t,invertY:n}=e.getStory().getInversionConfig();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.offset[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.offset[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((i,r,s)=>({style:{opacity:i,translate:`${t?-r:r}px ${n?-s:s}px`}}))]}}copy(){return new o({duration:this.duration,offset:this.offset,easing:this.easing})}};function X(o){return o<0?0:o>1?1:o}function uc(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function Ms(o){return{position:"absolute",top:"50%",left:"50%",width:"100%",height:"100%",transform:"translate(-50%, -50%)",backgroundColor:o}}function pc(o){switch(o){case"left":return"to left";case"top":return"to top";case"bottom":return"to bottom";case"right":default:return"to right"}}function dc(o){return o==="vertical"?"to right":"to bottom"}var Ns=class o extends Te{constructor(e){super(),this.duration=e.duration,this.blur=e.blur??16,this.easing=e.easing}createTask(){let e=Math.max(0,this.blur);return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-X(t),filter:`blur(${e*X(t)}px)`}})),this.asTarget(t=>({style:{opacity:X(t),filter:`blur(${e*(1-X(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var Gs=class o extends Te{constructor(e){super(),this.duration=e.duration,this.direction=e.direction??"left",this.easing=e.easing}axisSign(){switch(this.direction){case"right":return{axis:"x",sign:1};case"top":return{axis:"y",sign:-1};case"bottom":return{axis:"y",sign:1};case"left":default:return{axis:"x",sign:-1}}}translate(e){let{axis:t}=this.axisSign(),n=`${e}%`;return{translate:t==="x"?`${n} 0px`:`0px ${n}`}}createTask(){let{sign:e}=this.axisSign();return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:this.translate(e*100*X(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-X(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};var Hs=class o extends Te{constructor(e){super(),this.duration=e.duration,this.ev=e.ev??4.6,this.lift=e.lift??.04,this.hold=e.hold??0,this.easing=e.easing}burnStyle(e){let t=X(e);if(t<=0)return{filter:"none"};let n=X(this.lift)*t,i=Math.pow(2,Math.max(0,this.ev)*t);return{filter:`invert(1) brightness(${1-n}) invert(1) brightness(${i})`}}createTask(){let t=(1-X(this.hold))/2,n=1-t,i=.5,r=s=>s<=t?t<=0?1:s/t:s>=n?n>=1?1:(1-s)/(1-n):1;return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(s=>({style:{opacity:s<i?1:0,...this.burnStyle(r(s))}})),this.asTarget(s=>({style:{opacity:s<i?0:1,...this.burnStyle(r(s))}}))]}}copy(){return new o({duration:this.duration,ev:this.ev,lift:this.lift,hold:this.hold,easing:this.easing})}};function O(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function tr(o,e,t){return o<e?e:o>t?t:o}var on=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${O(t)}deg`:pc(t);return{mask:(r,s)=>{let a=-n+(s?1-X(r):X(r))*(100+n);return s?`linear-gradient(${i}, transparent ${O(a)}%, #000 ${O(a+n)}%)`:`linear-gradient(${i}, #000 ${O(a)}%, transparent ${O(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${O(t)}deg`,`${O(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let l=-n+X(s)*(50+n);if(!a){let c=u=>`linear-gradient(${u}, #000 ${O(l)}%, transparent ${O(l+n)}%)`;return`${c(i)}, ${c(r)}`}if(l<0){let c=X((l+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${O(50-l-n)}%, rgba(0,0,0,${O(c)}) 50%, transparent ${O(50+l+n)}%)`}return`linear-gradient(${i}, transparent ${O(50-l-n)}%, #000 ${O(50-l)}%, #000 ${O(50+l)}%, transparent ${O(50+l+n)}%)`}}}static iris(e={}){let t=e.center??"50% 50%",n=Math.max(0,e.feather??12),i=e.shape??"circle";return{mask:(r,s)=>{if(s){let l=(1-X(r))*150;return`radial-gradient(${i} at ${t}, transparent ${O(l-n)}%, #000 ${O(l)}%)`}let a=X(r)*150;return`radial-gradient(${i} at ${t}, #000 ${O(a-n)}%, transparent ${O(a)}%)`}}}static clock(e={}){let t=e.center??"50% 50%",n=e.from??0,i=Math.max(0,e.feather??24),r=e.direction??"clockwise";return{mask:(s,a)=>{let l=r==="counterclockwise"!=!!a,c=-i+X(s)*(360+i);if(l){let d=Math.max(0,360-c-i),p=Math.max(d,360-c);return`conic-gradient(from ${O(n)}deg at ${t}, transparent ${O(d)}deg, #000 ${O(p)}deg)`}let u=Math.max(0,c);return`conic-gradient(from ${O(n)}deg at ${t}, #000 ${O(u)}deg, transparent ${O(Math.max(u,c+i))}deg)`}}}static fan(e={}){let t=Math.max(1,Math.round(e.blades??4)),n=e.center??"50% 50%",i=e.from??0,r=Math.max(0,e.feather??10),s=360/t;return{mask:(a,l)=>{let c=-r+(l?1-X(a):X(a))*(s+r),u=tr(c,0,s),d=tr(c+r,0,s),p=`repeating-conic-gradient(from ${O(i)}deg at ${n}`;return l?`${p}, transparent 0deg, transparent ${O(u)}deg, #000 ${O(d)}deg, #000 ${O(s)}deg)`:`${p}, #000 0deg, #000 ${O(u)}deg, transparent ${O(d)}deg, transparent ${O(s)}deg)`}}}static blinds(e={}){let t=e.orientation??"horizontal",n=Math.max(1,e.slats??8),i=Math.max(0,e.feather??0),r=typeof t=="number"?`${O(t)}deg`:dc(t),s=100/n;return{mask:(a,l)=>{let c=-i+(l?1-X(a):X(a))*(s+i),u=tr(c,0,s),d=tr(c+i,0,s);return l?`repeating-linear-gradient(${r}, transparent 0, transparent ${O(u)}%, #000 ${O(d)}%, #000 ${O(s)}%)`:`repeating-linear-gradient(${r}, #000 0, #000 ${O(u)}%, transparent ${O(d)}%, transparent ${O(s)}%)`}}}static dots(e={}){let t=Math.max(1,e.rows??6),n=Math.max(1,e.cols??10),i=Math.max(0,e.feather??20),s=X(e.stagger??0)*.5,a=(l,c,u)=>{let d=-i+X(c)*(100+i);return u?`radial-gradient(circle farthest-corner at ${l}, transparent ${O(d)}%, #000 ${O(d+i)}%)`:`radial-gradient(circle farthest-corner at ${l}, #000 ${O(d)}%, transparent ${O(d+i)}%)`};return{size:`${O(100/n)}% ${O(100/t)}%`,repeat:"repeat",mask:(l,c)=>{let u=c?1-X(l):X(l);if(s<=0)return a("50% 50%",u,c);let d=X(u/(1-s)),p=X((u-s)/(1-s));return c?`${a("50% 50%",p,!0)}, ${a("0% 0%",d,!0)}`:`${a("50% 50%",d)}, ${a("0% 0%",p)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return uc(e.mask(t,n),e.size,e.repeat)}};var Fs=class o extends Te{constructor(e){super(),this.duration=e.duration,this.color=e.color??"#000000",this.hold=e.hold??.3,this.pattern=e.pattern??null,this.inverted=e.inverted??!1,this.uncover=e.uncover??"retreat",this.easing=e.easing}coverStyle(e,t){if(!this.pattern)return{...Ms(this.color),opacity:X(e)};let n={...Ms(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...on.toStyle(this.pattern,e,!this.inverted)}:{...n,...on.toStyle(this.uncover,e)}:{...n,...on.toStyle(this.pattern,e,this.inverted)}}createTask(){let t=(1-X(this.hold))/2,n=1-t,i=.5,r=s=>s<=t?t<=0?1:s/t:s>=n?n>=1?1:(1-s)/(1-n):1;return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(s=>({style:{opacity:s<i?1:0}})),this.asTarget(s=>({style:{opacity:s<i?0:1}})),s=>({src:G.DefaultImagePlaceholder,style:this.coverStyle(r(s),s>=n)})]}}copy(){return new o({duration:this.duration,color:this.color,hold:this.hold,pattern:this.pattern??void 0,inverted:this.inverted,uncover:this.uncover,easing:this.easing})}};var Os=class o extends Te{constructor(e){super(),this.duration=e.duration,this.pattern=e.pattern,this.easing=e.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(e=>({style:on.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var qn="http://www.w3.org/2000/svg",Yd="http://www.w3.org/1999/xlink",Xd=.002,Qd=1,Jd=.12,_d=0,Vs=class o extends Te{constructor(t){super();this.filterId=null;this.host=null;this.cut=null;this.duration=t.duration,this.rule=P.srcToURL(t.rule),this.feather=Math.min(Qd,Math.max(Xd,t.feather??Jd)),this.inverted=t.inverted??!1,this.easing=t.easing}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget(t=>({style:this.styleAt(t)}))]}}requestAnimations(t){let n=super.requestAnimations(t);return n.onComplete(()=>this.dispose()),n.onCanceled(()=>this.dispose()),n}copy(){return new o({duration:this.duration,rule:this.rule,feather:this.feather,inverted:this.inverted,easing:this.easing})}styleAt(t){if(t>=1)return this.dispose(),{filter:""};let n=this.ensureScaffold();if(!n)return{filter:""};let i=t*(1+this.feather),r=(this.inverted?1:-1)/this.feather,s=(this.inverted?i-1:i)/this.feather;return this.cut?.setAttribute("k3",String(r)),this.cut?.setAttribute("k4",String(s)),{filter:`url(#${n})`}}ensureScaffold(){if(typeof document>"u")return null;if(this.filterId&&this.host)return this.filterId;let t=`nl-rule-${++_d}`,n=document.createElementNS(qn,"svg");n.setAttribute("aria-hidden","true"),n.setAttribute("data-element-type","rule-transition"),n.setAttribute("width","0"),n.setAttribute("height","0"),Object.assign(n.style,{position:"absolute",width:"0",height:"0",overflow:"hidden"});let i=document.createElementNS(qn,"filter");i.setAttribute("id",t),i.setAttribute("color-interpolation-filters","sRGB"),i.setAttribute("primitiveUnits","objectBoundingBox"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("width","100%"),i.setAttribute("height","100%");let r=document.createElementNS(qn,"feImage");r.setAttribute("href",this.rule),r.setAttributeNS(Yd,"xlink:href",this.rule),r.setAttribute("preserveAspectRatio","none"),r.setAttribute("x","0"),r.setAttribute("y","0"),r.setAttribute("width","1"),r.setAttribute("height","1"),r.setAttribute("result","rule");let s=document.createElementNS(qn,"feColorMatrix");s.setAttribute("in","rule"),s.setAttribute("type","luminanceToAlpha"),s.setAttribute("result","lum");let a=document.createElementNS(qn,"feComposite");a.setAttribute("in","lum"),a.setAttribute("in2","lum"),a.setAttribute("operator","arithmetic"),a.setAttribute("k1","0"),a.setAttribute("k2","0"),a.setAttribute("k3","0"),a.setAttribute("k4","0"),a.setAttribute("result","cut");let l=document.createElementNS(qn,"feComposite");return l.setAttribute("in","SourceGraphic"),l.setAttribute("in2","cut"),l.setAttribute("operator","in"),i.append(r,s,a,l),n.appendChild(i),document.body.appendChild(n),this.filterId=t,this.host=n,this.cut=a,t}dispose(){this.host?.remove(),this.host=null,this.cut=null,this.filterId=null}};var Us=class extends di{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new j(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var nr=class{static getActionId(e){return e.getId()}static setActionId(e,t){return e.setId(t),e}static getStaticId(e){return e.getStaticId()}static setStaticId(e,t){return e.setStaticId(t),e}static chainToActions(e){return e.getActions()}static wrapAction(e){let t=We.isChained(e)?e.getActions():e;return Be.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}static getLayerSrcs(e,t){return G.getSrcURLs(e,t)}static registerDisplayable(e,t,n=null,i=null){e.findElementByDisplayable(t)||(e.createDisplayable(t,n,i),e.flush())}static setElementId(e,t){e.setId(t)}static setElementStaticId(e,t){e.setStaticId(t)}static getDisplayableTransformProps(e){return{...e.transformState.get()}}static setDisplayableTransformProps(e,t,n,i={}){let r=t.transformState;i.merge===!1?r.forceOverwrite(n):r.assign(Symbol("DevTools.setDisplayableTransformProps"),n),t.markDirty(),e.getExposedState(t)?.updateStyleSync?.(),e.flush()}static getPuppetStatus(e){return e._getStatus()}static onPuppetStatusChange(e,t){return e._onStatusChange(t)}static async describePuppet(e,t){try{return await t._describe()}catch(n){return e.logger.error("DevTools","Puppet backend threw while describing itself",n),null}}static getPuppetState(e){return Et.normalizeState(e.state)}static setPuppetState(e,t,n,i={}){t.state=i.merge===!1?Et.normalizeState(n):Et.mergeState(t.state,n),t._applyState().catch(r=>{e.logger.error("DevTools","Puppet backend threw while applying state",r)}),e.flush()}static async runPuppetCommand(e,t,n,i){try{await t._runCommand(n,i)||e.logger.weakWarn("DevTools",`Puppet command "${n}" was dropped: the puppet is not mounted.`)}catch(r){e.logger.error("DevTools",`Puppet backend threw while running "${n}"`,r)}}static listPuppetBackends(e){return e.listPuppetBackends()}static getCurrentDialog(e){if(e.isNvlMode()){let n=e.getNvlState();if(!n.activeDialogId||n.phase==="idle")return null;let i=e.getNvlDialog(n.activeDialogId);return i?{actionId:i.actionId||null,ended:n.phase==="awaitAdvance",mode:"nvl"}:null}let t=e.getAdvDialogState();return t?{actionId:t.actionId,ended:t.ended,mode:"adv"}:null}static onDialogStateChange(e,t){let n=[e.events.on(L.EventTypes["event:state.dialog.change"],t),e.events.on(L.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};nr.DynamicPersistent=Fn;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
|
|
80
83
|
@layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}.collapse{visibility:collapse}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.isolate{isolation:isolate}.z-20{z-index:20}.container{width:100%}.\\!hidden{display:none!important}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.table{display:table}.h-\\[80px\\]{height:80px}.h-full{height:100%}.h-max{height:-moz-max-content;height:max-content}.w-1\\/2{width:50%}.w-\\[100px\\]{width:100px}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-full{min-width:100%}.flex-grow,.grow{flex-grow:1}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.resize{resize:both}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.mask-repeat{-webkit-mask-repeat:repeat;mask-repeat:repeat}.text-center{text-align:center}.text-left{text-align:left}.align-bottom{vertical-align:bottom}.break-all{word-break:break-all}.whitespace-pre-wrap{white-space:pre-wrap}.italic{font-style:italic}.ordinal{--tw-ordinal:ordinal;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.underline{text-decoration-line:underline}.decoration-dotted{text-decoration-style:dotted}.ring{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.grayscale{--tw-grayscale:grayscale(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-filter{backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,ease);transition-duration:var(--tw-duration,0s)}.__narraleaf_content-player *{-webkit-user-select:none;-moz-user-select:none;user-select:none}.__narraleaf_content-player img{pointer-events:none;-webkit-user-drag:none;-webkit-user-select:none}.__narraleaf_content-player .pointer-disabled{pointer-events:none}.__narraleaf_content-player .pointer-disabled>:not(.pointer-disabled){pointer-events:auto}.__narraleaf_content-player img:before,.__narraleaf_content-player img:after{content:none!important;border:none!important}.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.bg-cover{background-size:cover}.bg-center{background-position:50%}.pointer-events-auto-rest *{pointer-events:auto}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}\r
|
|
81
|
-
`,document.head.appendChild(o)}export{
|
|
84
|
+
`,document.head.appendChild(o)}export{vn as Align,an as AudioBusError,oi as AudioBusMixer,ii as AudioBusTree,$r as Avatar,Ns as BlurDissolve,ui as Camera,no as Character,at as CommonPosition,In as CommonPositionType,yr as Condition,Be as Control,ht as Coord2D,Li as Darkness,tt as DefaultAudioBusIds,ns as DefaultNvlContainer,xl as DefaultNvlDialogItem,nr as DevTools,Hp as Dialog,Rs as Dissolve,Fd as ExposedStateType,Hs as Exposure,Is as FadeIn,Sl as FixedAspectRatioContainer,Us as Gallery,se as Game,bo as GameMenu,rc as GameProviders,L as GameState,G as Image,Te as ImageTransition,Wt as Isolated,Mo as Item,Bn as KeyBindingType,Di as KeyMap,j as Lambda,Vn as Layer,op as Layout,Ci as LayoutRouterProvider,Ot as LiveGame,on as Mask,Qi as MaxAudioBusDepth,vr as Menu,li as NVLToken,Ft as Namespace,tn as Nametag,_t as Narrator,Go as Notifications,ts as NvlContainer,Dp as NvlDialogList,Zr as NvlProvider,cp as Page,Yr as PageInjectContext,Ke as Pause,Hn as Persistent,oc as Player,fi as Preference,Et as Puppet,Gs as Push,Os as Reveal,Ha as RootPath,Vs as RuleReveal,yt as Scene,we as Script,ua as SeededBusPreferenceKeys,me as Sentence,di as Service,ve as Sound,da as SoundType,Yc as Stage,ti as Storable,pi as Story,Tn as Text,lt as TextEvent,ri as TextTransition,Lu as Texts,Pu as TextsPreview,Fs as ThroughColor,J as Transform,Vt as Transition,Cr as Vfx,Ar as Video,te as Word,Ji as acceptsAudioBus,jd as b,$d as c,fr as getActiveAudioBusTree,mu as getWordRenderer,qd as i,pu as registerWordRenderer,du as unregisterWordRenderer,pl as useAvatar,Ku as useDialog,Mp as useDialogOverlay,I as useGame,Cp as useIsNvlMode,xp as useIsNvlVisible,xn as useKeyBinding,yp as useLiveGame,Kt as useNvl,_r as useNvlDialogs,_u as useParams,Ju as usePathname,fn as usePreference,Zu as useQueryParams,Ut as useRouter,Gp as useSuspendAdvance,Wr as useUIMenuContext,qu as useVoiceState};
|