narraleaf-react 0.30.0 → 0.31.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,82 +1,82 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ye={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",init:"displayable:init",bringToFront:"displayable:bringToFront"},jt={say:"character:say",action:"character:action",setName:"character:setName"},X={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 dt={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},Ms={action:"condition:action"},Ns={action:"script:action"},Gs={action:"menu:action"},It={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"},ne={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"},Ei={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},Kn={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},mn={action:"layer:action",setZIndex:"layer:setZIndex"},Mt={action:"video:action",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"},_t={action:"vfx:action",show:"vfx:show",hide:"vfx:hide",pause:"vfx:pause",resume:"vfx:resume",setRate:"vfx:setRate"},_e={action:"puppet:action",setMotion:"puppet:setMotion",setExpression:"puppet:setExpression",setSkin:"puppet:setSkin",setParam:"puppet:setParam",setSlot:"puppet:setSlot",command:"puppet:command"};var Hs=(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))(Hs||{}),Yo=(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});Yo.DataTypes=Hs;function z(o,e,...t){let n=(s,a)=>Object.prototype.hasOwnProperty.call(s,a),i={},r=(s,a,c)=>Yo(a)===3&&Yo(c)===3?a.constructor!==Object||c.constructor!==Object?c||a:z(a,c):Array.isArray(a)&&Array.isArray(c)?c&&c.length>0?[...c]:[...a]:a===void 0&&Array.isArray(c)?[...c]:c===void 0?Array.isArray(a)?[...a]:a:Array.isArray(c)?[...c]:c;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]=z({},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 z(i,s,...a)}return i}var Ye=class Ye{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=Qo()}static isAwaitable(e){return e instanceof Ye}static fromPromise(e){let t=new Ye;return e.then(n=>t.resolve(n)).catch(n=>t.fail(n)),t}static resolve(e){let t=new Ye;return t.resolve(e),t}static delay(e){let t=new Ye;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new Ye;return e(t),t}static wait(e){let t=new Ye;return e.then(()=>t.resolve()),e.onFailed(n=>t.fail(n)),t}static race(e){let t=new Ye;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 H(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let i=new Ye().registerSkipController(n||new H(()=>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 Ye;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 H(()=>{e.forEach(n=>n.abort())})),t)}static all(...e){let t=new Ye;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 H(()=>{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>=Ye.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>=Ye.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()}}};Ye.nothing=e=>e,Ye.maxListeners=8;var S=Ye;function Fs(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 kn(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 q=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 c=a?.(...t);c!==null&&typeof c=="object"&&c.then?c.then(n):n(c)}}).listener})}setMaxListeners(e){return this.maxListeners=e,this}hasListeners(e){return this.events[e]?.length>0}clear(){this.events={}}};function Qo(o=1){let e=new Error().stack;return e?e.split(`
|
|
2
2
|
`).slice(o+1).join(`
|
|
3
|
-
`).trim():""}function Ii(o){return new Promise(e=>setTimeout(e,o))}var Ri=class Ri{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(Ri.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Ri.EventTypes={"event:skipController.abort":"event:skipController.abort"};var G=Ri;var Bn=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}},An=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Bn;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 Mi(o,e,t={}){return o?e:t}function Ms(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var ki=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 Ns(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 Gs(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 xn=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 Ii(this.delay),await e())};await e()}};function at(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function Hs(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var Je=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 Fs(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 Vs(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function jo(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function qo(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"&&!qo(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Pi=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Ni(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 Os(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Ei=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Di=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 Li=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 Us(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 Ws(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,c=16777216,l=r*a>>>0,u=r*c+s*a>>>0,d=s*c+(u>>>0)>>>0;e=l,t=d}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Kn=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=$o(),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]:[]}};Kn.ActionTypes={action:"action"};var j=class extends Kn{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 jt=class jt extends j{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 jt.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 G(()=>(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),c=e.timelines.attachTimeline(r).attachChild(a);return a.onCancelled(s),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:c},()=>{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(l=>l),c=null;return a.registerSkipController(new G(()=>(c&&(clearTimeout(c),c=null),s))),c=e.setTimeout(()=>{c=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===J.action)return super.executeAction(e,t);if(this.is(jt,"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 jt.handleSceneInit(this.callee,r,e,S.forward(n,r))}else if(this.type===J.exit){let n=jt.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new S(s=>s);e.timelines.attachTimeline(r),jt.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),jt.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===J.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[c]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,c)},[r]);let s=i.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:s}),null}else if(this.type===J.setBackgroundMusic){let[n,i]=this.contentNode.getContent(),r=this.callee,s=e.getExposedStateForce(r),a=r.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.setBackgroundMusic(c,0)},[a]),s.setBackgroundMusic(n,i||0),super.executeAction(e,t)}else{if(this.type===J.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===J.transitionToScene){let[n,i]=this.contentNode.getContent();return this.applyStageTransition(e,n,i,t)}else if(this.type===J.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===J.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===J.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===J.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===J.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===J.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 Gi(o){return new Promise(e=>setTimeout(e,o))}var Ni=class Ni{constructor(e){this.abortHandler=e;this.events=new q;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Ni.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Ni.EventTypes={"event:skipController.abort":"event:skipController.abort"};var H=Ni;var zn=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}},xn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new zn;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 Hi(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 Di=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 Os(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 wn=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 Gi(this.delay),await e())};await e()}};function rt(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 Qe=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 Fi(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function Xo(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"&&!Xo(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Li=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 Ri=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Ii=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 Mi=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,c=16777216,l=r*a>>>0,u=r*c+s*a>>>0,d=s*c+(u>>>0)>>>0;e=l,t=d}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var $n=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Qo(),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]:[]}};$n.ActionTypes={action:"action"};var $=class extends $n{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 H(()=>(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),c=e.timelines.attachTimeline(r).attachChild(a);return a.onCancelled(s),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:c},()=>{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(l=>l),c=null;return a.registerSkipController(new H(()=>(c&&(clearTimeout(c),c=null),s))),c=e.setTimeout(()=>{c=null,a.resolve(s)},r),a}executeAction(e,t){if(this.type===X.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===X.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===X.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[c]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,c)},[r]);let s=i.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:s}),null}else if(this.type===X.setBackgroundMusic){let[n,i]=this.contentNode.getContent(),r=this.callee,s=e.getExposedStateForce(r),a=r.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.setBackgroundMusic(c,0)},[a]),s.setBackgroundMusic(n,i||0),super.executeAction(e,t)}else{if(this.type===X.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===X.transitionToScene){let[n,i]=this.contentNode.getContent();return this.applyStageTransition(e,n,i,t)}else if(this.type===X.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===X.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===X.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===X.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===X.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===X.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===J.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")}};jt.ActionTypes=J;var re=jt;var Yo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},C=class o extends Yo{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 Gi={center:"center",left:"left",right:"right"};import{animate as Yc}from"motion/react";var wn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(wn||{}),Bs={left:"33.33%",center:"50%",right:"66.66%"},mt=class mt{static isUnknown(e){return e===mt.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},c=t?{right:s}:{left:s};return this.wrap({...a,...c})}static calc(e,t,n){if(!e||mt.isUnknown(e))return"auto";let i=!(t===void 0||mt.isUnknown(t));if(typeof n=="number"&&n>0){let s=mt.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(ct.isCommonPositionType(e))return ft.fromCommonPosition(e);if(ft.isCoord2DPosition(e))return e;if(dn.isAlignPosition(e))return ft.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 mt.isUnknown(e)||e===void 0?mt.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return ft.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:mt.isUnknown(t.x)?0:t.x,y:mt.isUnknown(t.y)?0:t.y,xoffset:mt.isUnknown(t.xoffset)?0:t.xoffset,yoffset:mt.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(wn).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 ct||e instanceof ft||e instanceof dn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return ft.fromCommonPosition(new ct(e));if(this.isRawAlignPosition(e))return ft.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new ft(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}}};mt.Unknown=Symbol("Unknown");var M=mt,Hi=class Hi{static isCommonPositionType(e){return e instanceof Hi}constructor(e){this.position=e}toCSS(){return{x:Bs[this.position],y:"50%",xoffset:0,yoffset:0}}};Hi.Positions=wn;var ct=Hi,ft=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:Bs[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}}},dn=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 Qo(this.mergeWithDefaultConfig(e))}copy(){return new o($({},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)?$({},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}},Qo=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o($({},this.config))}join(e){let t=Hs(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 Qc={[Gi.left]:"25.33%",[Gi.center]:"50%",[Gi.right]:"75.66%"},bt=class bt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new bt(bt.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=bt.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 jo(_.constructStyle(e,this.state,t))}toStyle(e,t){return jo(_.constructStyle(e,this.state,t))}serialize(){return bt.TransformStateSerializer.serialize(this.state)}clone(){return new bt(bt.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=bt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};bt.DefaultTransformState=new K({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new ct("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}),bt.TransformStateSerializer=new Je({position:e=>M.serializePosition(M.tryParsePosition(e))},{position:e=>M.toCoord2D(e)});var X=bt,Ee=class Ee{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},Ee.defaultConfig,t||{});else{let[n,i]=[e,t||Ee.defaultOptions];this.sequences.push({props:n,options:i||Ee.defaultOptions}),this.config=Object.assign({},Ee.defaultConfig)}}static isPosition(e){return ct.isCommonPositionType(e)||ft.isCoord2DPosition(e)||dn.isAlignPosition(e)}static immediate(e){return new Ee(e,{duration:0,ease:"linear"})}static left(e,t){return new Ee({position:ct.Positions.Left},{duration:e,ease:t})}static right(e,t){return new Ee({position:ct.Positions.Right},{duration:e,ease:t})}static center(e,t){return new Ee({position:ct.Positions.Center},{duration:e,ease:t})}static create(e){return new Ee([],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{...$(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,c=function(p,h,g){return typeof p>"u"?typeof g<"u"?h(g):"":h(p)},l=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${u})`,c(t.rotation,p=>`rotate(${p}deg)`,0),c(t.scaleX,p=>`scaleX(${p*a})`,1),c(t.scaleY,p=>`scaleY(${p*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{},a=e.game?.config,c=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...Ee.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?Cn(t.fontColor):void 0,transform:Ee.propToCSSTransform(e,t),...Ee.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}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:r,sequences:s,options:a}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current});s.length||t.logger.warn("Transform","No sequences to animate.");let c=!1,l=e.lock(),u=Yc(s,a),d=()=>{e.overwrite(l,r.get()).unlock(l),u.complete(),c=!0},p=new S().registerSkipController(new G(d)),h=()=>{c||e.overwrite(l,r.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),p.resolve()};return u.then(h,(g=>{t.logger.error("Failed to animate transform. "+(g?.toString?.()||""));try{h()}catch{p.resolve()}})),u.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:r,sequences:s,options:a},this),p}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...Ee.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}){let r=t.clone(),s=r.lock(),a=this.sequences.map(({props:c,options:l})=>{let u=r.assign(s,c).toFramesDefinition(e,n);return[i,u,this.getOptions(l)]});return{finalState:r.unlock(s).freeze(),sequences:a,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0)}}copy(){return new Ee(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}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 c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};Ee.defaultConfig={sync:!0},Ee.defaultOptions={duration:0,ease:"linear"},Ee.CommonImagePositionMap=Qc;var _=Ee;var Fi=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 Ks=Symbol("_Chained"),zs;zs=Ks;var Xo=class Xo{constructor(e){this[zs]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Ks]}static toActions(e){return e.flat(2).map(t=>Xo.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()}},ze=Xo,kn=class extends Fi{chain(e){let t=ze.isChained(this)?this:this.proxy(this,new ze(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 kn{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Rt=class extends j{executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=s=>{let a=s.condition?n?s.condition.toString():"Lambda(unknown)":"null",c=s.action?s.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};Rt.ActionTypes=Es;var zn=64;function js(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function Jo(o){return o.length?o.map(e=>typeof e=="number"?`[${e}]`:`.${e}`).join(""):"the value itself"}function Vi(o,e=0,t=new Set){if(e>zn)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=>Vi(n,e+1,t)):js(o)?Object.values(o).every(n=>Vi(n,e+1,t)):!1}finally{t.delete(o)}}function qs(o,e){let t=[],n=[];return{data:Zo(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function Zo(o,e,t,n,i,r,s){if(t>zn)throw new P(`A stored value nests deeper than ${zn} 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===X.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=X;var se=qt;var Jo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},x=class o extends Jo{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 Oi={center:"center",left:"left",right:"right"};import{animate as tl}from"motion/react";var Pn=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(Pn||{}),qs={left:"33.33%",center:"50%",right:"66.66%"},mt=class mt{static isUnknown(e){return e===mt.Unknown}static D2PositionToCSS(e,t=!1,n=!1,i){let r=this.calc(e.y,e.yoffset,i?.height),s=this.calc(e.x,e.xoffset,i?.width),a=n?{bottom:r}:{top:r},c=t?{right:s}:{left:s};return this.wrap({...a,...c})}static calc(e,t,n){if(!e||mt.isUnknown(e))return"auto";let i=!(t===void 0||mt.isUnknown(t));if(typeof n=="number"&&n>0){let s=mt.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(st.isCommonPositionType(e))return ft.fromCommonPosition(e);if(ft.isCoord2DPosition(e))return e;if(fn.isAlignPosition(e))return ft.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 mt.isUnknown(e)||e===void 0?mt.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return ft.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:mt.isUnknown(t.x)?0:t.x,y:mt.isUnknown(t.y)?0:t.y,xoffset:mt.isUnknown(t.xoffset)?0:t.xoffset,yoffset:mt.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(Pn).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 st||e instanceof ft||e instanceof fn}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return ft.fromCommonPosition(new st(e));if(this.isRawAlignPosition(e))return ft.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new ft(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}}};mt.Unknown=Symbol("Unknown");var N=mt,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=Pn;var st=Ui,ft=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||N.isUnknown(n)?N.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:N.isUnknown(t.x)?e.x:t.x,y:N.isUnknown(t.y)?e.y:t.y,xoffset:N.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:N.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=N.orUnknown(e.x),this.y=N.orUnknown(e.y),this.xoffset=N.orUnknown(e.xoffset),this.yoffset=N.orUnknown(e.yoffset)):(this.x=N.orUnknown(e),this.y=N.orUnknown(t),this.xoffset=N.Unknown,this.yoffset=N.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}}},fn=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=N.orUnknown(e.xalign),this.yalign=N.orUnknown(e.yalign),this.xoffset=N.orUnknown(e.xoffset),this.yoffset=N.orUnknown(e.yoffset)):(this.xalign=N.orUnknown(e),this.yalign=N.orUnknown(t),this.xoffset=N.Unknown,this.yoffset=N.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:N.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:N.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 Zo(this.mergeWithDefaultConfig(e))}copy(){return new o(z({},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)?z({},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}},Zo=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(z({},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 nl={[Oi.left]:"25.33%",[Oi.center]:"50%",[Oi.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?N.toCoord2D(N.tryParsePosition(e||t)):N.mergePosition(N.tryParsePosition(e),N.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 Fi(Z.constructStyle(e,this.state,t))}toStyle(e,t){return Fi(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}};xt.DefaultTransformState=new B({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new st("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 Qe({position:e=>N.serializePosition(N.tryParsePosition(e))},{position:e=>N.toCoord2D(e)});var J=xt,De=class De{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},De.defaultConfig,t||{});else{let[n,i]=[e,t||De.defaultOptions];this.sequences.push({props:n,options:i||De.defaultOptions}),this.config=Object.assign({},De.defaultConfig)}}static isPosition(e){return st.isCommonPositionType(e)||ft.isCoord2DPosition(e)||fn.isAlignPosition(e)}static immediate(e){return new De(e,{duration:0,ease:"linear"})}static left(e,t){return new De({position:st.Positions.Left},{duration:e,ease:t})}static right(e,t){return new De({position:st.Positions.Right},{duration:e,ease:t})}static center(e,t){return new De({position:st.Positions.Center},{duration:e,ease:t})}static create(e){return new De([],e)}static positionToCSS(e,t,n,i){return e?N.isRawPosition(e)?N.D2PositionToCSS(N.rawPositionToCoord2D(e),n,t,i):N.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?N.toCoord2D(N.tryParsePosition(e||t)):N.mergePosition(N.tryParsePosition(e),N.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...z(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{translate:s=[]}=n||{},a=t.zoom??1,c=function(p,h,f){return typeof p>"u"?typeof f<"u"?h(f):"":h(p)},l=s[0]||(r?"":"-")+"50%",u=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${u})`,c(t.rotation,p=>`rotate(${p}deg)`,0),c(t.scaleX,p=>`scaleX(${p*a})`,1),c(t.scaleY,p=>`scaleY(${p*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:i,invertX:r}=e.getStory().getInversionConfig(),{overwrite:s}=n||{},a=e.game?.config,c=a&&a.width>0&&a.height>0?{width:a.width,height:a.height}:void 0;return{...De.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?kn(t.fontColor):void 0,transform:De.propToCSSTransform(e,t),...De.constructVisualEffectStyle(t),...s?s(t):{}}}static constructVisualEffectStyle(e){let t=e;return{maskImage:t.maskImage,WebkitMaskImage:t.maskImage,maskSize:t.maskSize,WebkitMaskSize:t.maskSize,maskPosition:t.maskPosition,WebkitMaskPosition:t.maskPosition,maskRepeat:t.maskRepeat,WebkitMaskRepeat:t.maskRepeat,maskMode:t.maskMode,WebkitMaskMode:t.maskMode,clipPath:t.clipPath,filter:t.filter,backdropFilter:t.backdropFilter,WebkitBackdropFilter:t.backdropFilter,mixBlendMode:t.mixBlendMode}}animate(e,{gameState:t,ref:n,overwrites:i,companionRefs:r}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:s,sequences:a,options:c}=this.constructAnimation({gameState:t,transformState:e,overwrites:i,current:n.current,companions:r?.filter(m=>!!m.ref.current).map(({ref:m,project:y})=>({el:m.current,project:y}))});a.length||t.logger.warn("Transform","No sequences to animate.");let l=!1,u=e.lock(),d=tl(a,c),p=()=>{e.overwrite(u,s.get()).unlock(u),d.complete(),l=!0},h=new S().registerSkipController(new H(p)),f=()=>{l||e.overwrite(u,s.get()).unlock(u),l=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),h.resolve()};return d.then(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:c},this),h}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...De.defaultOptions};let{duration:t,ease:n,delay:i,at:r}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(i,void 0),at:this.atToSeconds(r)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:i,companions:r}){let s=t.clone(),a=s.lock(),c=this.sequences.flatMap(({props:l,options:u})=>{let d=s.assign(a,l),p=d.toFramesDefinition(e,n),h=this.getOptions(u),f=[i,p,h];if(!r||!r.length)return[f];let m=d.get();return[f,...r.map(({el:y,project:b})=>[y,Fi(b(m)),{...h,at:"<"}])]});return{finalState:s.unlock(a).freeze(),sequences:c,options:this.getSequenceOptions()}}getSequenceOptions(){let{repeat:e,repeatDelay:t}=this.config;return{repeat:e,repeatDelay:this.toSeconds(t,void 0)}}copy(){return new De(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 c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};De.defaultConfig={sync:!0},De.defaultOptions={duration:0,ease:"linear"},De.CommonImagePositionMap=nl;var Z=De;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 Ys=Symbol("_Chained"),Qs;Qs=Ys;var _o=class _o{constructor(e){this[Qs]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Ys]}static toActions(e){return e.flat(2).map(t=>_o.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()}},ze=_o,En=class extends Wi{chain(e){let t=ze.isChained(this)?this:this.proxy(this,new ze(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 En{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Nt=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",c=s.action?s.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${r(i.If)} ${i.ElseIf.length>0?`else if ${i.ElseIf.map(r).join(";")} `:""}${i.Else?`else {${r(i.Else)}}`:""}`)}};Nt.ActionTypes=Ms;var jn=64;function Js(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function er(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>jn)return!1;if(typeof o=="number"||typeof o=="string"||typeof o=="boolean"||o==null||o instanceof Date)return!0;if(typeof o!="object"||t.has(o))return!1;t.add(o);try{return Array.isArray(o)?o.every(n=>Bi(n,e+1,t)):Js(o)?Object.values(o).every(n=>Bi(n,e+1,t)):!1}finally{t.delete(o)}}function Zs(o,e){let t=[],n=[];return{data:tr(o,[],0,new Set,t,n,e),dates:t,undefineds:n}}function tr(o,e,t,n,i,r,s){if(t>jn)throw new k(`A stored value nests deeper than ${jn} levels and cannot be saved
|
|
7
|
+
at ${s}, ${er(e)}
|
|
8
8
|
A saved game this deep is almost always a data-structure bug. Flatten the value,
|
|
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
|
|
10
|
-
at ${s}, ${
|
|
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 k(`A stored value refers back to itself and cannot be saved
|
|
10
|
+
at ${s}, ${er(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 P("No listener provided when subscribing to storable changes");return this.events.on(_t.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(_t.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 It(n,{})),this.namespaces[n].deserialize(i)})}finally{this.restoreBatch=null}this.events.emit(_t.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(_t.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(_t.EventTypes["event:storable.restore"],{namespaces:[e]})}};_t.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var $n=_t;var tt=class extends j{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Dt.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===Dt.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===Dt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=S.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[s]),a}else if(this.type===Dt.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===Dt.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===Dt.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===Dt.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===Dt.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=S.forward(e.audioManager.mute(this.callee,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(s),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[r]),s}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};tt.ActionTypes=Dt;var nt={bgm:"bgm",sound:"sound",voice:"voice"},Oi=8,en=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function Pn(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var qn=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=c=>{t.set(c.id,{id:c.id,parentId:c.parentId??null,volume:Pn(c.volume)})};Object.values(nt).forEach(c=>n({id:c}));let i=new Set;e.forEach(c=>{let l=c?.id;if(typeof l!="string"||l.trim().length===0)throw new en(`Audio bus id must be a non-empty string, got ${JSON.stringify(l)}.`);if(i.has(l))throw new en(`Audio bus "${l}" is declared more than once.`);i.add(l),n(c)}),o.assertResolvable(t);let r=[],s=new Map,a=c=>{let l=s.get(c);if(l)return l;let u=t.get(c),d=u.parentId===null?null:a(u.parentId),p={id:u.id,parentId:u.parentId,volume:u.volume,depth:d?d.depth+1:1};return s.set(c,p),r.push(p),p};return t.forEach(c=>a(c.id)),new o(r,s)}static isSeeded(e){return Object.values(nt).includes(e)}static assertResolvable(e){e.forEach(t=>{let n=[t.id],i=new Set([t.id]),r=t;for(;r.parentId!==null;){let s=e.get(r.parentId);if(!s)throw new en(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new en(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>Oi)throw new en(`Audio bus "${t.id}" nests deeper than ${Oi}: ${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<=Oi;){if(n.id===t)return!0;n=n.parentId===null?void 0:this.index.get(n.parentId),i++}return!1}},tr=qn.resolve();function Jc(o){tr=o}function nr(){return tr}function Ui(o,e){let t=tr;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var Xs={[nt.bgm]:"bgmVolume",[nt.sound]:"soundVolume",[nt.voice]:"voiceVolume"};function Js(o){let e={};return Object.entries(Xs).forEach(([t,n])=>{e[t]={get:()=>Pn(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var jn=class jn{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,Pn(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(jn.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=qn.resolve(this.declarations()??[]),Jc(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=Pn(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?Pn(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return Pn(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(jn.EventTypes["event:audioBus.volumeChange"],e)}};jn.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var Yn=jn;var Zs=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(Zs||{}),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 nr().isUnder(this.config.type,nt.bgm)&&console.warn(`NarraLeaf-React [Sound] Playing a bgm-typed sound (src: ${this.config.src}) with \`play()\`. It will play on the music bus but is not the scene's background music, so leaving the scene will not stop it and it will not cross-fade. Use \`scene.setBackgroundMusic()\` if that is what you wanted.`),this.pushAction(tt.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(tt.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(tt.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(tt.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(tt.ActionTypes.setRate,[e])}pause(e){return this.pushAction(tt.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(tt.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}seek(e){return this.pushAction(tt.ActionTypes.seek,[e])}getSrc(){return this.config.src}toData(){return{state: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 tt(this.chain(),e,new C().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 Je;var ye=xe;var _s=3;var Gm={};var En=class extends kn{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let c=a.getFutureActions(e,i).filter(l=>!r.has(l));s.push(...c)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var mn=class mn{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===mn.SrcTypes.image?t.add(s):r===mn.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 R?R.getSrcURL(e):e.type==="image"?R.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(re,J.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(w.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof ve){let n=t;if(t.is(ve,dt.setSrc)){let i=t.contentNode.getContent()[0];if(w.isImageSrc(i))return{type:"image",src:w.srcToURL(i),activeType:"scene"}}else{if(t.type===dt.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===dt.setAppearance){let i=t.contentNode.getContent()[0];if(R.isLayeredSrc(n.callee))return null;if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(R.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:R.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 ye){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof R||w.isStaticImageData(e)){if(e instanceof R){if(!w.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(R.getSrcURL(e)))return this}else if(this.isSrcRegistered(w.srcToURL(e.src)))return this;this.src.push({type:"image",src:w.isStaticImageData(e)?w.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 ye?t:new ye({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 ye?e.getSrc():e;return this.src.some(n=>n.type===mn.SrcTypes.audio?t===n.src.getSrc():n.type===mn.SrcTypes.image?t===R.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)}};mn.SrcTypes={image:"image",video:"video",audio:"audio"};var De=mn;var $e=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 ea(o,e){let{render:t,data:n,...i}=e,r=$(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 Le=class Le{static isWord(e){return e instanceof Le}static color(e,t){return Le.isWord(e)?e.copy().assign({color:t}):new Le(e,{color:t})}static bold(e){return Le.isWord(e)?e.copy().assign({bold:!0}):new Le(e,{bold:!0})}static italic(e){return Le.isWord(e)?e.copy().assign({italic:!0}):new Le(e,{italic:!0})}static custom(e,t,n={}){let i={...n,render:t};return Le.isWord(e)?e.copy().assign(i):new Le(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=ea(Le.defaultConfig,t)}evaluate(e){if($e.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=>Le.isWord(n)?n.inherit(this.config).evaluate(e):new Le(n,this.config)).flat():Le.isWord(t)?t.inherit(this.config).evaluate(e):[new Le(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=ea(this.config,e),this}copy(){return new Le(this.text,this.config)}isPause(){return $e.isPause(this.text)}isTextEvent(){return lt.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Le.defaultConfig={},Le.defaultColor="#000";var Z=Le;var tn=class extends j{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")}};tn.ActionTypes=Ds;var Ce=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 tn(t,tn.ActionTypes.action,new C().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new tn(this.chain(),tn.ActionTypes.action,new C().setContent(e))]}};var Wi=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 we=class o{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onFailed=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),at(()=>{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 P("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 P("Cannot create an 'all' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let c=e[a];i.attachChild(c),c.then(l=>{r[a]=l,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new S,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?at(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new G(()=>(i&&i.abort(),t))),i=e(t),i?at(()=>s()):at(()=>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()?at(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 P(`Attaching to this timeline violates the timeline's state.
|
|
13
|
+
reference, or store an id in place of the object.`);if(Array.isArray(o)||Js(o)){n.add(o);try{if(Array.isArray(o))return o.map((c,l)=>tr(c,[...e,l],t+1,n,i,r,s));let a={};return Object.entries(o).forEach(([c,l])=>{a[c]=tr(l,[...e,c],t+1,n,i,r,s)}),a}finally{n.delete(o)}}}return console.warn(`Value of type "${il(o)}" cannot be saved and was stored as null
|
|
14
|
+
at ${s}, ${er(e)}`),null}function il(o){return typeof o!="object"||o===null?typeof o:o.constructor?.name??"object"}function _s(o,e,t){let n=Xs(o,e,nr);return n=Xs(n,t,()=>{}),n}function Xs(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 nr(o){return o instanceof Date?o:typeof o=="string"||typeof o=="number"?new Date(o):new Date(NaN)}function ea(o){return typeof o=="object"&&o!==null&&Object.getPrototypeOf(o)===Object.prototype}function ir(o,e,t=0){if(Object.is(o,e))return!0;if(t>jn)return!1;if(o instanceof Date||e instanceof Date)return o instanceof Date&&e instanceof Date&&o.getTime()===e.getTime();if(Array.isArray(o)||Array.isArray(e))return Array.isArray(o)&&Array.isArray(e)&&o.length===e.length&&o.every((n,i)=>ir(n,e[i],t+1));if(ea(o)&&ea(e)){let n=Object.keys(o);return n.length===Object.keys(e).length&&n.every(i=>Object.prototype.hasOwnProperty.call(e,i)&&ir(o[i],e[i],t+1))}return!1}var Gt=class o{constructor(e,t,n){this.owner=null;this.name=e,this.key=n||e,this.content=z({},t),this.defaultContent=t}static isSerializable(e){return Bi(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=z({},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=Zs(s,n),c={type:"any",data:a.data};return a.dates.length&&(c.dates=a.dates),a.undefineds.length&&(c.undefineds=a.undefineds),c},date:s=>({type:"date",data:s.toISOString()})},r=this.toTypeName(e);return i[r](e)}unwrap(e){let n={any:i=>_s(i.data,i.dates,i.undefineds),date:i=>nr(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||ir(t,n)||this.owner.reportChange({namespace:this.key,key:String(e),previous:t,next:n})}},en=class en{constructor(){this.events=new q;this.namespaces={};this.restoreBatch=null;this.events.setMaxListeners(64)}static createNamespace(e,t,n){return new Gt(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 k(`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 k("No listener provided when subscribing to storable changes");return this.events.on(en.EventTypes["event:storable.change"],a=>{i!==null&&a.namespace!==i||r!==null&&a.key!==r||s(a)})}onRestore(e){return this.events.on(en.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(en.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(en.EventTypes["event:storable.change"],e)}reportRestore(e){if(this.restoreBatch){this.restoreBatch.add(e);return}this.events.emit(en.EventTypes["event:storable.restore"],{namespaces:[e]})}};en.EventTypes={"event:storable.change":"event:storable.change","event:storable.restore":"event:storable.restore"};var qn=en;var et=class extends ${executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===It.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===It.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===It.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=S.forward(e.audioManager.setVolume(this.callee,i,r),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[s]),a}else if(this.type===It.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===It.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===It.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===It.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===It.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=It;var tt={bgm:"bgm",sound:"sound",voice:"voice"},Ki=8,tn=class extends Error{constructor(e){super(e),this.name="AudioBusError"}};function Dn(o){return o===void 0||!Number.isFinite(o)?1:Math.min(1,Math.max(0,o))}var Qn=class o{constructor(e,t){this.nodes=e;this.index=t}static resolve(e=[]){let t=new Map,n=c=>{t.set(c.id,{id:c.id,parentId:c.parentId??null,volume:Dn(c.volume)})};Object.values(tt).forEach(c=>n({id:c}));let i=new Set;e.forEach(c=>{let l=c?.id;if(typeof l!="string"||l.trim().length===0)throw new tn(`Audio bus id must be a non-empty string, got ${JSON.stringify(l)}.`);if(i.has(l))throw new tn(`Audio bus "${l}" is declared more than once.`);i.add(l),n(c)}),o.assertResolvable(t);let r=[],s=new Map,a=c=>{let l=s.get(c);if(l)return l;let u=t.get(c),d=u.parentId===null?null:a(u.parentId),p={id:u.id,parentId:u.parentId,volume:u.volume,depth:d?d.depth+1:1};return s.set(c,p),r.push(p),p};return t.forEach(c=>a(c.id)),new o(r,s)}static isSeeded(e){return Object.values(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 tn(`Audio bus "${r.id}" names an unknown parent "${r.parentId}".`);if(i.has(s.id))throw new tn(`Audio bus tree has a cycle: ${[...n,s.id].join(" -> ")}.`);if(i.add(s.id),n.push(s.id),n.length>Ki)throw new tn(`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}},or=Qn.resolve();function ol(o){or=o}function rr(){return or}function zi(o,e){let t=or;return t.has(o)?e.some(n=>t.isUnder(o,n)):!0}var ta={[tt.bgm]:"bgmVolume",[tt.sound]:"soundVolume",[tt.voice]:"voiceVolume"};function na(o){let e={};return Object.entries(ta).forEach(([t,n])=>{e[t]={get:()=>Dn(o.getPreference(n)),set:i=>o.setPreference(n,i),subscribe:i=>o.onPreferenceChange(n,i)}}),e}var Yn=class Yn{constructor(e,t={}){this.declarations=e;this.events=new q;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,Dn(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(Yn.EventTypes["event:audioBus.volumeChange"],e,t,n)}getTree(){return this.tree||(this.tree=Qn.resolve(this.declarations()??[]),ol(this.tree)),this.tree}invalidate(){return this.tree=null,this}isResolved(){return this.tree!==null}setVolume(e,t){let n=Dn(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?Dn(t.get()):this.overrides.get(e)??1}getDeclaredVolume(e){return this.getTree().get(e)?.volume??1}getEffectiveVolume(e){return Dn(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(Yn.EventTypes["event:audioBus.volumeChange"],e)}};Yn.EventTypes={"event:audioBus.volumeChange":"event:audioBus.volumeChange"};var Xn=Yn;var ia=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(ia||{}),Ae=class Ae extends ce{static toSound(e){return e==null?null:typeof e=="string"?new Ae({src:e}):e}static isSound(e){return e instanceof Ae}static voice(e){let t=typeof e=="string"?{src:e}:e;return new Ae({type:"voice",...t})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new Ae({type:"bgm",...t})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new Ae({type:"sound",...t})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=Ae.DefaultUserConfig.create(t),[i]=n.extract(Ae.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){return rr().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:Ae.StateSerializer.serialize(this.state)}}fromData(e){return this.state=Ae.StateSerializer.deserialize(e.state),this}copy(){return new Ae(this.userConfig.get())}reset(){return super.reset(),this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return Ae.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new et(this.chain(),e,new x().setContent(t)))}};Ae.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",Ae.DefaultUserConfig=new B({src:Ae.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Ae.DefaultConfig=new B({src:Ae.noSound,loop:!1,streaming:!1,seek:0,endTime:void 0,loopStart:void 0,type:"sound"}),Ae.DefaultState=new B({volume:1,rate:1,paused:!1,muted:!1}),Ae.StateSerializer=new Qe;var ve=Ae;var oa=3;var Bm={};var Ln=class extends En{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,i={}){let r=new Set,s=[];for(Array.isArray(t)?s.push(...t):s.push(t);s.length;){let a=s.shift();if(r.has(a))continue;r.add(a),n(a);let c=a.getFutureActions(e,i).filter(l=>!r.has(l));s.push(...c)}}getAllChildren(e,t,n={}){let i=[];return this.forEachChild(e,t,r=>i.push(r),n),i}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,i=>n.set(i.getId(),i)),n}getAllElementMap(e,t,n={}){let i=new Map;return this.forEachChild(e,t,r=>i.set(r.callee.getId(),r.callee),n),i}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(i=>i.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let i=e[n];n===0&&t?t.setChild(i.contentNode):n>0&&e[n-1].contentNode?.setChild(i.contentNode)}return e.length?e[0].contentNode:null}};var hn=class hn{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===hn.SrcTypes.image?t.add(s):r===hn.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(se,X.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(w.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,dt.setSrc)){let i=t.contentNode.getContent()[0];if(w.isImageSrc(i))return{type:"image",src:w.srcToURL(i),activeType:"scene"}}else{if(t.type===dt.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===dt.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 ve){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof I||w.isStaticImageData(e)){if(e instanceof I){if(!w.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(I.getSrcURL(e)))return this}else if(this.isSrcRegistered(w.srcToURL(e.src)))return this;this.src.push({type:"image",src:w.isStaticImageData(e)?w.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===hn.SrcTypes.audio?t===n.src.getSrc():n.type===hn.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)}};hn.SrcTypes={image:"image",video:"video",audio:"audio"};var Le=hn;var $e=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 at=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 ra(o,e){let{render:t,data:n,...i}=e,r=z(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 Re=class Re{static isWord(e){return e instanceof Re}static color(e,t){return Re.isWord(e)?e.copy().assign({color:t}):new Re(e,{color:t})}static bold(e){return Re.isWord(e)?e.copy().assign({bold:!0}):new Re(e,{bold:!0})}static italic(e){return Re.isWord(e)?e.copy().assign({italic:!0}):new Re(e,{italic:!0})}static custom(e,t,n={}){let i={...n,render:t};return Re.isWord(e)?e.copy().assign(i):new Re(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=ra(Re.defaultConfig,t)}evaluate(e){if($e.isPause(this.text))return[this];if(at.isTextEvent(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>Re.isWord(n)?n.inherit(this.config).evaluate(e):new Re(n,this.config)).flat():Re.isWord(t)?t.inherit(this.config).evaluate(e):[new Re(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=ra(this.config,e),this}copy(){return new Re(this.text,this.config)}isPause(){return $e.isPause(this.text)}isTextEvent(){return at.isTextEvent(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Re.defaultConfig={},Re.defaultColor="#000";var _=Re;var nn=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")}};nn.ActionTypes=Ns;var Ce=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 nn(t,nn.ActionTypes.action,new x().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new nn(this.chain(),nn.ActionTypes.action,new x().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 xe=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()}),rt(()=>{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 k("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 k("Cannot create an 'all' timeline with no awaitables.");let t=new S,n=new S,i=new o(n),r=new Array(e.length),s=0;for(let a=0;a<e.length;a++){let c=e[a];i.attachChild(c),c.then(l=>{r[a]=l,s++,s===e.length&&t.resolve(r)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{i.abort()})}),[t,i]}static sequence(e,t){let n=t,i=null,r=new S,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?rt(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new H(()=>(i&&i.abort(),t))),i=e(t),i?rt(()=>s()):rt(()=>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()?rt(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 k(`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())}},Bi=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof we?e:new we(e);return this.timelines.push(t),this.guard&&t.setGuard(this.guard),t}abortAll(){for(let e of this.timelines)e.abort();this.cleanupSettled()}cleanupSettled(){this.timelines=this.timelines.filter(e=>!e.isSettled())}};var At=class At extends j{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:ye.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=At.trailingVoice.get(e);n&&n!==t&&e.audioManager.isPlaying(n)&&e.timelines.attachTimeline(e.audioManager.stop(n,0)),t?At.trailingVoice.set(e,t):At.trailingVoice.delete(e)}executeAction(e,t){if(this.type===$t.say){let n=null,i="",r=null,s=new S(y=>y).registerSkipController(new G(()=>{n?.()})),a=new we(s),c=this.contentNode.getContent(),l=e.isNvlMode(),u=e.getLiveGame(),d=e.createPresentationSnapshot(),p=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,h=At.getVoice(e,c);if(h){At.cutTrailingVoice(e,h);let y=e.audioManager.play(h);a.attachChild(y)}let g=h?e.events.on(E.EventTypes["event:state.player.lineEnd"],()=>{let y=At.endVoiceWithPreference(e,h);y&&e.timelines.attachTimeline(y),g?.cancel()}):null;if(l){let y=this.getId(),f=(e.getActiveNvlDialogForAction(y)||e.getLatestNvlDialogForAction(y))?.id||e.allocateNvlDialogId(y),v=c.evaluate(Ce.getCtx({gameState:e}));i=Z.getText(v),u.events.emit(Mt.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let x=!1,T=()=>{x||(x=!0,e.events.emit(E.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:b}=e.ensureNvlDialog({id:f,actionId:y,character:this.callee,sentence:c,text:i});r=f;let k=e.consumeNvlTypingSuppression(),D=b&&!k?"typing":"awaitAdvance";e.activateNvlDialog(f,D,!b);let W=e.waitForNvlAdvance(f,()=>{e.settleNvlDialog(f),T()});n=()=>{W.cancel()}}else{let y=e.idManager.generateId(),A=e.createDialog(y,c,()=>{e.settleAdvDialog(y),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()})});e.beginAdvDialog(y,this.getId()),i=A.text,n=()=>{e.settleAdvDialog(y),A.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(g?.cancel(),h&&e.audioManager.isPlaying(h)){let y=At.endVoiceWithPreference(e,h);y&&a.attachChild(y)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(d),p?u.setLastDialog(p.sentence,p.speaker):u.lastDialog=null});return e.gameHistory.push({token:m,action:this,element:{type:"say",text:i,voice:h?h.getSrc():null,voiceId:c.config.voiceId??null,character:this.callee.state.name},isPending:!0,snapshot:u.captureGameState()}),s}else if(this.type===$t.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")}};At.ActionTypes=$t,At.trailingVoice=new WeakMap;var it=At;function or(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function ia(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return na(o);let i=ir(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=ir(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=ir(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function ir(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 na(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}function oa(o,e){let t=[],n=i=>{i&&typeof i!="function"&&w.isImageSrc(i)&&t.push(i)};n(e?.config.avatar),n(o.config.avatar);for(let i of o.config.portraits||[])n(or(i).avatar);return t}var nn=class extends j{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===wi.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===wi.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")}};nn.ActionTypes=wi;var Qn=class Qn extends j{executeAction(e,t){if(this.type===ge.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===ge.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===ge.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===ge.bringToFront)return this.bringToFront(e,this.callee,t);throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new S().registerSkipController(new G(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t),l=t.transformState.clone(),u=c.applyTransform(n,a),d=e.timelines.attachTimeline(s).attachChild(u);return u.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:d},p=>{s.isSettled()||s.abort(),u.abort(),t.transformState.forceOverwrite(p.state)},[l]),s}applyTransition(e,t,n,i,r){let s=new S().registerSkipController(new G(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t).applyTransition(n,a),u=e.timelines.attachTimeline(s).attachChild(l);return l.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{s.isSettled()||s.abort(),l.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let l=e.findElementByDisplayable(this.callee,i);l&&e.disposeDisplayable(n,l.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new S().registerSkipController(new G(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:c},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}bringToFront(e,t,n){let i=e.findElementByDisplayable(t),r=i&&Qn.getLayerElements(i,t);if(!r)throw new P(`Displayable not found when bringing it to front. The element may not be on stage yet. (element: ${t.getId()})`);let s=r.indexOf(t);s!==r.length-1&&(r.splice(s,1),r.push(t),e.flush()),e.actionHistory.push({action:this,stackModel:n.stackModel},c=>{let l=e.findElementByDisplayable(t),u=l&&Qn.getLayerElements(l,t);if(!u)return;let d=u.indexOf(t);d!==c&&(u.splice(d,1),u.splice(c,0,t),e.flush())},[s]);let a=new S;return a.resolve(super.executeAction(e,n)),a}static getLayerElements(e,t){for(let n of e.layers.values())if(n.includes(t))return n;return null}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};Qn.ActionTypes=ge;var Re=Qn;var ut=class o extends ce{constructor(){super(...arguments);this.srcManager=new De}pos(t,n,i){return this.transform(new _({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new _({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new _({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new _({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new _({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 _({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new _({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new _(t,n))}mask(t,n={}){let i=w.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c,...l}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c},l)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new je,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new je,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...c}=t,l={duration:s,ease:a,...c},u=o.wipeClipPath(n,100),d=o.wipeClipPath(n,0),p=o.createClipPathTransform([[i?d:u,{duration:0}],[i?u:d,l]]);return r?this.combineActions(new je,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 Re(n,ge.applyTransform,new C().setContent([t.copy()]));return n.chain(i)}bringToFront(){let t=this.chain(),n=new Re(t,ge.bringToFront,new C().setContent([]));return t.chain(n)}registerEffectSrc(t){let n=t.maskImage;if(typeof n=="string")for(let i of o.extractCSSUrls(n))this.srcManager.registerRawSrc(i)}static toCSSUrl(t){return`url("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}")`}static extractCSSUrls(t){let n=[],i=/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g,r;for(;r=i.exec(t);){let s=r[1]||r[2]||r[3];s&&n.push(s.trim())}return n}static createClipPathTransform(t){return new _(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 _?t.copy():new _({opacity:1},t),r=new Re(n,ge.applyTransform,new C().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof _?t.copy():new _({opacity:0},t),r=new Re(n,ge.applyTransform,new C().setContent([i]));return n.chain(r)}};var ht=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(ht||{});import{animate as Zc}from"motion/react";var Nt=class{requestAnimations(e){let t=e.map(m=>m.start),n=[],i=0,r=!1,s=!1,a=!1,c=[],l=[],u=[],d=()=>{e.forEach((m,y)=>{t[y]=m.end}),i=e.length,c.forEach(m=>m(t)),l.forEach(m=>m())};return{onUpdate:m=>(c.push(m),{cancel:()=>{let y=c.indexOf(m);y!==-1&&c.splice(y,1)}}),onComplete:m=>(l.push(m),{cancel:()=>{let y=l.indexOf(m);y!==-1&&l.splice(y,1)}}),onCanceled:m=>(u.push(m),{cancel:()=>{let y=u.indexOf(m);y!==-1&&u.splice(y,1)}}),complete:()=>{if(!(i===e.length||s)){if(!r){a=!0;return}n.forEach(m=>m.complete())}},start:()=>{if(!(r||s||i===e.length)){if(r=!0,a){d();return}e.forEach((m,y)=>{n.push(this.requestMotion(m,{onComplete:()=>{t[y]=m.end,c.forEach(A=>A(t)),i++,i===e.length&&l.forEach(A=>A())},onUpdate:A=>{t[y]=A,c.forEach(f=>f(t))}}))})}},cancel:()=>{s=!0,n.forEach(m=>m.cancel()),u.forEach(m=>m())}}}toFinalStyle(e){return e.resolve.map(t=>typeof t=="function"?t(...e.animations.map(n=>n.end)):t.resolver(...e.animations.map(n=>n.end)))}asPrev(e){return{resolver:e,key:"current"}}asTarget(e){return{resolver:e,key:"target"}}requestMotion(e,t){return Zc(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Nt.AnimationType=ht;var Xn=class extends Nt{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new P(`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 Ki=class o extends Xn{constructor(e){super(),this.fontSize=e.fontSize,this.duration=e.duration,this.easing=e.easing}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.fontSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(e=>({style:{fontSize:`${e}px`}}))]}}copy(){return new o({fontSize:this.fontSize,duration:this.duration,easing:this.easing})}};var ke=class ke extends ut{static get DefaultUserConfig(){return ke._defaultUserConfig??(ke._defaultUserConfig=new K({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:"",...X.DefaultTransformState.getDefaultConfig()},{position:e=>M.tryParsePosition(e)}))}static get DefaultTextTransformState(){return ke._defaultTextTransformState??(ke._defaultTextTransformState=new K({fontColor:"#000000",...X.DefaultTransformState.getDefaultConfig()}))}constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=ke.DefaultUserConfig.create(n),r=ke.DefaultTextConfig.create(i.get());this.userConfig=i,this.config=r.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(i)}setText(e){let t=this.chain(),n=new nn(t,nn.ActionTypes.setText,new C().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new _({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new je,i=>{if(t){let s=new Ki({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new nn(i,nn.ActionTypes.setFontSize,new C().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:ke.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=ke.StateSerializer.deserialize(e.state),this.transformState=X.deserialize(e.transformState),this}_init(e){return new Re(this.chain(),ge.init,new C().setContent([e||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(ke.DefaultTextTransformState.keys());return new X(ke.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Re(e,ge.applyTransition,new C().setContent([t,n=>n._setElement(this)]))}getInitialState(){return ke.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};ke._defaultUserConfig=null,ke.DefaultTextConfig=new K({alignX:"center",alignY:"center",className:"",layer:void 0}),ke.DefaultTextState=new K({fontSize:16,display:!1,text:""}),ke._defaultTextTransformState=null,ke.StateSerializer=new Je;var fn=ke;var Jn=class extends j{executeAction(e,t){if(this.type===et.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===et.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===et.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===et.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===et.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===et.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let c=new S().registerSkipController(new G(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{c.isSettled()||c.resolve(super.executeAction(e,t))});let l=e.timelines.attachTimeline(c);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:l},()=>{c.isSettled()||c.abort()}),c}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};Jn.ActionTypes=et;var Ne=class Ne extends ut{constructor(t){super();this.events=new Y;this.instance=null;this.status="unmounted";let n=Ne.DefaultUserConfig.create(t),i=Ne.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 Ne._defaultUserConfig??(Ne._defaultUserConfig=new K({backend:"",src:"",options:{},size:null,className:"",layer:void 0,motion:null,expression:null,skin:null,params:{},slots:{},...X.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:Ne.copyParams(n.params),slots:Ne.copySlots(n.slots)}}static mergeState(t,n){return Ne.normalizeState({...t,...n,params:{...t.params,...n.params||{}},slots:{...t.slots,...n.slots||{}}})}static copyParams(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&(n[i]=r);return n}static copySlots(t){let n={};if(!t||typeof t!="object")return n;for(let[i,r]of Object.entries(t))(typeof r=="string"||r===null)&&(n[i]=r);return n}setMotion(t){return this.chain(this.createAction(et.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(et.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(et.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(et.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(et.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(et.command,[t,n,i]))}getStatus(){return this.status}onStatusChange(t){return this.events.on("event:puppet.statusChange",t)}useLayer(t){return this.userConfig.get().layer=t,Object.assign(this.config,{layer:t}),this}toData(){return{state:Ne.normalizeState(this.state),transformState:this.transformState.serialize()}}fromData(t){return this.state=Ne.normalizeState(t.state),this.transformState=X.deserialize(t.transformState),this}_init(t){return new Re(this.chain(),ge.init,new C().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}_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=Ne.normalizeState(this.state);return this.state=Ne.mergeState(this.state,t),n}async _applyState(){let t=this.instance;t&&await t.apply(Ne.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 Jn(this.chain(),t,C.create(n))}getInitialTransformState(t){let[n]=t.extract(X.DefaultTransformState.keys());return new X(X.DefaultTransformState.create(n.get()).get())}getInitialState(){let t=this.userConfig.get();return Ne.normalizeState({motion:t.motion,expression:t.expression,skin:t.skin,params:t.params,slots:t.slots})}};Ne._defaultUserConfig=null,Ne.DefaultPuppetConfig=new K({backend:"",src:"",options:{},size:null,className:"",layer:void 0});var xt=Ne;var Zn=class Zn extends j{executeAction(e,t){let n=this;if(n.is(Zn,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let c=s.get(i);s.set(i,r(c))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.set(i,c)},[a]),super.executeAction(e,t)}else if(n.is(Zn,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(c=>{s[c]=r.get(c),r.set(c,a[c])}),e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{Object.keys(c).forEach(l=>{r.set(l,c[l])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};Zn.ActionTypes=Wn;var zi=Zn;var pt=class pt{static isSentence(e){return e instanceof pt}static toSentence(e){return pt.isSentence(e)?e:new pt(e)}static format(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(this.formatWord(e[n]));else t.push(this.formatWord(e));return t}static formatWord(e){return Z.isWord(e)?e:new Z(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[Z.isWord(e)?e:new Z(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(pt.isSingleWord):pt.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||Z.isWord(e)||$e.isPause(e)||lt.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=pt.format(e),this.config=$(pt.defaultConfig,{...t,voice:typeof t.voice=="string"?ye.voice(t.voice):ye.toSound(t.voice)}),this.state=Is(pt.defaultState)}toData(){return null}fromData(e){return this.state=$(this.state,e),this}toString(){return this.text.map(e=>e.text).join("")}setCharacter(e){return this.config.character=e,this}evaluate(e){let t=[];for(let n=0;n<this.text.length;n++){let i=this.text[n].evaluate(e);t.push(...pt.formatStaticWord(i))}return t}copy(){return new pt([...this.text],this.config)}};pt.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},pt.defaultState={};var fe=pt;var on=class on extends ce{constructor(e,t={}){super(),this.config=$(on.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>fe.isSingleWord(c))){let c=e,l=fe.format([t,...n]),u=new fe(Ns(c,l),{character:this}),d=new it(this.chain(),it.ActionTypes.say,new C().setContent(u));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new fe(r,{...i,character:this}):(fe.isSentence(r)?r:new fe(r,{...i,character:this})).copy();s.setCharacter(this);let a=new it(this.chain(),it.ActionTypes.say,new C().setContent(s));return this.chain(a)}setName(e){let t=new it(this.chain(),it.ActionTypes.setName,new C().setContent([e]));return this.chain(t)}setAvatar(e){return this.config.avatar=e===null?null:e,this}addPortrait(e,t={}){return this.config.portraits.push({image:e,avatar:t.avatar}),this}setPortraits(e){return this.config.portraits=[...e],this}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&fe.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):fe.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:on.StateSerializer.serialize(this.state)}}fromData(e){return this.state=on.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};on.defaultCharacterColor="#000",on.defaultConfig={portraits:[]},on.StateSerializer=new Je;var $i=on,qt=new $i(null);var q=class o{static isLambda(e){return e instanceof o&&"handler"in e}static isLambdaHandler(e){return typeof e=="function"}static from(e){return o.isLambda(e)?e:new o(e)}static not(e){return new o(t=>!e.evaluate(t).value)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){let t=e.game.getLiveGame(),n=t.getStorable();return{gameState:e,game:e.game,liveGame:t,storable:n,$:i=>n.getNamespace(i)}}toString(){return`Lambda(${this.handler.toString()})`}},rr=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 Ge(`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())}},ji=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof xe?e:new xe(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 wt=class wt 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=wt.trailingVoice.get(e);n&&n!==t&&e.audioManager.isPlaying(n)&&e.timelines.attachTimeline(e.audioManager.stop(n,0)),t?wt.trailingVoice.set(e,t):wt.trailingVoice.delete(e)}executeAction(e,t){if(this.type===jt.say){let n=null,i="",r=null,s=new S(y=>y).registerSkipController(new H(()=>{n?.()})),a=new xe(s),c=this.contentNode.getContent(),l=e.isNvlMode(),u=e.getLiveGame(),d=e.createPresentationSnapshot(),p=u.lastDialog?{sentence:u.lastDialog.sentence,speaker:u.lastDialog.speaker}:null,h=wt.getVoice(e,c);if(h){wt.cutTrailingVoice(e,h);let y=e.audioManager.play(h);a.attachChild(y)}let f=h?e.events.on(E.EventTypes["event:state.player.lineEnd"],()=>{let y=wt.endVoiceWithPreference(e,h);y&&e.timelines.attachTimeline(y),f?.cancel()}):null;if(l){let y=this.getId(),v=(e.getActiveNvlDialogForAction(y)||e.getLatestNvlDialogForAction(y))?.id||e.allocateNvlDialogId(y),g=c.evaluate(Ce.getCtx({gameState:e}));i=_.getText(g),u.events.emit(Ht.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let C=!1,T=()=>{C||(C=!0,e.events.emit(E.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:A}=e.ensureNvlDialog({id:v,actionId:y,character:this.callee,sentence:c,text:i});r=v;let P=e.consumeNvlTypingSuppression(),D=A&&!P?"typing":"awaitAdvance";e.activateNvlDialog(v,D,!A);let W=e.waitForNvlAdvance(v,()=>{e.settleNvlDialog(v),T()});n=()=>{W.cancel()}}else{let y=e.idManager.generateId(),b=e.createDialog(y,c,()=>{e.settleAdvDialog(y),e.gameHistory.resolvePending(m),s.resolve({type:this.type,node:this.contentNode.getChild()})});e.beginAdvDialog(y,this.getId()),i=b.text,n=()=>{e.settleAdvDialog(y),b.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 y=wt.endVoiceWithPreference(e,h);y&&a.attachChild(y)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(d),p?u.setLastDialog(p.sentence,p.speaker):u.lastDialog=null});return e.gameHistory.push({token:m,action:this,element:{type:"say",text:i,voice:h?h.getSrc():null,voiceId:c.config.voiceId??null,character:this.callee.state.name},isPending:!0,snapshot:u.captureGameState()}),s}else if(this.type===jt.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")}};wt.ActionTypes=jt,wt.trailingVoice=new WeakMap;var nt=wt;function ar(o){return"image"in o?{image:o.image,avatar:o.avatar}:{image:o}}function ca(o){let{sentenceAvatar:e,portraitAvatar:t,characterAvatar:n}=o;if(!o.character||!o.character.state.name||e===!1)return aa(o);let i=sr(e,o);if(i.resolved)return{source:i.source,character:o.character,portrait:o.portrait};let r=sr(t,o);if(r.resolved)return{source:r.source,character:o.character,portrait:o.portrait};let s=sr(n,o);return s.resolved?{source:s.source,character:o.character,portrait:o.portrait}:{source:null,character:o.character,portrait:o.portrait}}function sr(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 aa(o){return{source:null,character:o.character||null,portrait:o.portrait||null}}function la(o,e){let t=[],n=i=>{i&&typeof i!="function"&&w.isImageSrc(i)&&t.push(i)};n(e?.config.avatar),n(o.config.avatar);for(let i of o.config.portraits||[])n(ar(i).avatar);return t}var on=class extends ${executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Ei.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===Ei.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")}};on.ActionTypes=Ei;var Jn=class Jn extends ${executeAction(e,t){if(this.type===ye.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===ye.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===ye.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===ye.bringToFront)return this.bringToFront(e,this.callee,t);throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new S().registerSkipController(new H(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},c=e.getExposedStateForce(t),l=t.transformState.clone(),u=c.applyTransform(n,a),d=e.timelines.attachTimeline(s).attachChild(u);return u.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:d},p=>{s.isSettled()||s.abort(),u.abort(),t.transformState.forceOverwrite(p.state)},[l]),s}applyTransition(e,t,n,i,r){let s=new S().registerSkipController(new H(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,i)))),a=()=>{s.isSettled()||(r?.(),s.resolve(super.executeAction(e,i)))},l=e.getExposedStateForce(t).applyTransition(n,a),u=e.timelines.attachTimeline(s).attachChild(l);return l.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},()=>{s.isSettled()||s.abort(),l.abort()}),s}initDisplayable(e,t,n,i,r=!0,s){if(r!==!1){let l=e.findElementByDisplayable(this.callee,i);l&&e.disposeDisplayable(n,l.scene,i),e.createDisplayable(n,t,i)}e.flush();let a=new S().registerSkipController(new H(()=>super.executeAction(e,s)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,s))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:s.stackModel,timeline:c},()=>{r!==!1&&e.findElementByDisplayable(n,i)&&e.disposeDisplayable(n,t,i)}),a}bringToFront(e,t,n){let i=e.findElementByDisplayable(t),r=i&&Jn.getLayerElements(i,t);if(!r)throw new k(`Displayable not found when bringing it to front. The element may not be on stage yet. (element: ${t.getId()})`);let s=r.indexOf(t);s!==r.length-1&&(r.splice(s,1),r.push(t),e.flush()),e.actionHistory.push({action:this,stackModel:n.stackModel},c=>{let l=e.findElementByDisplayable(t),u=l&&Jn.getLayerElements(l,t);if(!u)return;let d=u.indexOf(t);d!==c&&(u.splice(d,1),u.splice(c,0,t),e.flush())},[s]);let a=new S;return a.resolve(super.executeAction(e,n)),a}static getLayerElements(e,t){for(let n of e.layers.values())if(n.includes(t))return n;return null}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};Jn.ActionTypes=ye;var Ie=Jn;var ct=class o extends ce{constructor(){super(...arguments);this.srcManager=new Le}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=w.srcToURL(t),{maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c,...l}=n;return this.srcManager.registerRawSrc(i),this.effect({maskImage:o.toCSSUrl(i),maskSize:r,maskPosition:s,maskRepeat:a,maskMode:c},l)}clearMask(t){return this.effect({maskImage:"none",maskSize:"auto",maskPosition:"0% 0%",maskRepeat:"repeat",maskMode:"match-source"},t)}clip(t,n){return this.effect({clipPath:t},n)}clearClip(t){return this.effect({clipPath:"none"},t)}circleReveal(t={}){let{center:n="50% 50%",from:i=0,to:r=150,clearClip:s=!0,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new je,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:c="easeInOut",...l}=t,u={duration:a,ease:c,...l},d=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),u]]);return s?this.combineActions(new je,p=>p.transform(d).clearClip({duration:0})):this.transform(d)}wipe(t={}){let{direction:n="left",reverse:i=!1,clearClip:r=!i,duration:s=600,ease:a="easeInOut",...c}=t,l={duration:s,ease:a,...c},u=o.wipeClipPath(n,100),d=o.wipeClipPath(n,0),p=o.createClipPathTransform([[i?d:u,{duration:0}],[i?u:d,l]]);return r?this.combineActions(new je,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 Ie(n,ye.applyTransform,new x().setContent([t.copy()]));return n.chain(i)}bringToFront(){let t=this.chain(),n=new Ie(t,ye.bringToFront,new x().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 Ie(n,ye.applyTransform,new x().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 Ie(n,ye.applyTransform,new x().setContent([i]));return n.chain(r)}};var ht=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(ht||{});import{animate as rl}from"motion/react";var Ft=class{requestAnimations(e){let t=e.map(m=>m.start),n=[],i=0,r=!1,s=!1,a=!1,c=[],l=[],u=[],d=()=>{e.forEach((m,y)=>{t[y]=m.end}),i=e.length,c.forEach(m=>m(t)),l.forEach(m=>m())};return{onUpdate:m=>(c.push(m),{cancel:()=>{let y=c.indexOf(m);y!==-1&&c.splice(y,1)}}),onComplete:m=>(l.push(m),{cancel:()=>{let y=l.indexOf(m);y!==-1&&l.splice(y,1)}}),onCanceled:m=>(u.push(m),{cancel:()=>{let y=u.indexOf(m);y!==-1&&u.splice(y,1)}}),complete:()=>{if(!(i===e.length||s)){if(!r){a=!0;return}n.forEach(m=>m.complete())}},start:()=>{if(!(r||s||i===e.length)){if(r=!0,a){d();return}e.forEach((m,y)=>{n.push(this.requestMotion(m,{onComplete:()=>{t[y]=m.end,c.forEach(b=>b(t)),i++,i===e.length&&l.forEach(b=>b())},onUpdate:b=>{t[y]=b,c.forEach(v=>v(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 rl(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Ft.AnimationType=ht;var Zn=class extends Ft{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new k(`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 qi=class o extends Zn{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 we=class we extends ct{static get DefaultUserConfig(){return we._defaultUserConfig??(we._defaultUserConfig=new B({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:"",...J.DefaultTransformState.getDefaultConfig()},{position:e=>N.tryParsePosition(e)}))}static get DefaultTextTransformState(){return we._defaultTextTransformState??(we._defaultTextTransformState=new B({fontColor:"#000000",...J.DefaultTransformState.getDefaultConfig()}))}constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=we.DefaultUserConfig.create(n),r=we.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 on(t,on.ActionTypes.setText,new x().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 je,i=>{if(t){let s=new qi({fontSize:e,duration:t,easing:n});i.chain(this._applyTransition(i,s))}let r=new on(i,on.ActionTypes.setFontSize,new x().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:we.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=we.StateSerializer.deserialize(e.state),this.transformState=J.deserialize(e.transformState),this}_init(e){return new Ie(this.chain(),ye.init,new x().setContent([e||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(we.DefaultTextTransformState.keys());return new J(we.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new Ie(e,ye.applyTransition,new x().setContent([t,n=>n._setElement(this)]))}getInitialState(){return we.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};we._defaultUserConfig=null,we.DefaultTextConfig=new B({alignX:"center",alignY:"center",className:"",layer:void 0}),we.DefaultTextState=new B({fontSize:16,display:!1,text:""}),we._defaultTextTransformState=null,we.StateSerializer=new Qe;var gn=we;var _n=class extends ${executeAction(e,t){if(this.type===_e.setMotion){let[n]=this.contentNode.getContent();return this.patchState(e,t,{motion:n})}else if(this.type===_e.setExpression){let[n]=this.contentNode.getContent();return this.patchState(e,t,{expression:n})}else if(this.type===_e.setSkin){let[n]=this.contentNode.getContent();return this.patchState(e,t,{skin:n})}else if(this.type===_e.setParam){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{params:{[n]:i}})}else if(this.type===_e.setSlot){let[n,i]=this.contentNode.getContent();return this.patchState(e,t,{slots:{[n]:i}})}else if(this.type===_e.command){let[n,i,r]=this.contentNode.getContent();return this.runCommand(e,t,n,i,r?.await===!0)}throw super.unknownTypeError()}patchState(e,t,n){let i=this.callee,r=i._patchState(n);return this.pushState(e,i),e.actionHistory.push({action:this,stackModel:t.stackModel},s=>{i.state=s,this.pushState(e,i)},[r]),super.executeAction(e,t)}pushState(e,t){t._applyState().catch(n=>{e.logger.error("Puppet",`Backend "${t.config.backend}" threw while applying state`,n)})}runCommand(e,t,n,i,r){let s=this.callee,a=()=>s._runCommand(n,i).then(u=>{u||e.logger.weakWarn("Puppet",`Command "${n}" was dropped: the puppet is not on stage. Show the element before commanding it.`)}).catch(u=>{e.logger.error("Puppet",`Backend "${s.config.backend}" threw while running "${n}"`,u)});if(!r)return a(),super.executeAction(e,t);let c=new S().registerSkipController(new H(()=>(e.logger.info("Puppet Command","Skipped"),super.executeAction(e,t))));a().then(()=>{c.isSettled()||c.resolve(super.executeAction(e,t))});let l=e.timelines.attachTimeline(c);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:l},()=>{c.isSettled()||c.abort()}),c}stringify(e,t,n){return super.stringifyWithName("PuppetAction")}};_n.ActionTypes=_e;var Ge=class Ge extends ct{constructor(t){super();this.events=new q;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:{},...J.DefaultTransformState.getDefaultConfig()},{position:t=>N.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(_e.setMotion,[t]))}setExpression(t){return this.chain(this.createAction(_e.setExpression,[t]))}setSkin(t){return this.chain(this.createAction(_e.setSkin,[t]))}setParam(t,n){return this.chain(this.createAction(_e.setParam,[t,n]))}setSlot(t,n){return this.chain(this.createAction(_e.setSlot,[t,n]))}command(t,n,i){return this.chain(this.createAction(_e.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()}}fromData(t){return this.state=Ge.normalizeState(t.state),this.transformState=J.deserialize(t.transformState),this}_init(t){return new Ie(this.chain(),ye.init,new x().setContent([t||null,this.config.layer||null]))}reset(){super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}_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 _n(this.chain(),t,x.create(n))}getInitialTransformState(t){let[n]=t.extract(J.DefaultTransformState.keys());return new J(J.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 kt=Ge;var ei=class ei extends ${executeAction(e,t){let n=this;if(n.is(ei,"persistent:set")){let[i,r]=n.contentNode.getContent(),s=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=s.get(i);if(typeof r=="function"){let c=s.get(i);s.set(i,r(c))}else s.set(i,r);return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{s.set(i,c)},[a]),super.executeAction(e,t)}else if(n.is(ei,"persistent:assign")){let[i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),s={},a=typeof i=="function"?i(r.getContent()):i;return Object.keys(a).forEach(c=>{s[c]=r.get(c),r.set(c,a[c])}),e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{Object.keys(c).forEach(l=>{r.set(l,c[l])})},[s]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};ei.ActionTypes=Kn;var Yi=ei;var lt=class lt{static isSentence(e){return e instanceof lt}static toSentence(e){return lt.isSentence(e)?e:new lt(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 _.isWord(e)?e:new _(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[_.isWord(e)?e:new _(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(lt.isSingleWord):lt.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||_.isWord(e)||$e.isPause(e)||at.isTextEvent(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=lt.format(e),this.config=z(lt.defaultConfig,{...t,voice:typeof t.voice=="string"?ve.voice(t.voice):ve.toSound(t.voice)}),this.state=Fs(lt.defaultState)}toData(){return null}fromData(e){return this.state=z(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(...lt.formatStaticWord(i))}return t}copy(){return new lt([...this.text],this.config)}};lt.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},lt.defaultState={};var de=lt;var rn=class rn extends ce{constructor(e,t={}){super(),this.config=z(rn.defaultConfig,t),this.authoredName=e||"",this.state=this.getInitialState();let n=this,i=function(r,s,...a){return n.call(r,s,...a)};return new Proxy(i,{get(r,s){return n[s]},set(r,s,a){return n[s]=a,!0},has(r,s){return s in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>de.isSingleWord(c))){let c=e,l=de.format([t,...n]),u=new de(Os(c,l),{character:this}),d=new nt(this.chain(),nt.ActionTypes.say,new x().setContent(u));return this.chain(d)}let i=t||{},r=e,s=Array.isArray(r)?new de(r,{...i,character:this}):(de.isSentence(r)?r:new de(r,{...i,character:this})).copy();s.setCharacter(this);let a=new nt(this.chain(),nt.ActionTypes.say,new x().setContent(s));return this.chain(a)}setName(e){let t=new nt(this.chain(),nt.ActionTypes.setName,new x().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&&de.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):de.isSentence(e)?this.say(e):this.say(e,t)}toData(){return{state:rn.StateSerializer.serialize(this.state)}}fromData(e){return this.state=rn.StateSerializer.deserialize(e.state),this}reset(){return super.reset(),this.state=this.getInitialState(),this}getInitialState(){return{name:this.authoredName}}};rn.defaultCharacterColor="#000",rn.defaultConfig={portraits:[]},rn.StateSerializer=new Qe;var Qi=rn,Yt=new Qi(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()})`}},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 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(Nt,[this,Nt.ActionTypes.action,new x().setContent(t.conditions)])]}construct(t,n,i){let r=this.narrativeToActions(t);for(let s=0;s<r.length;s++){let a=r[s].contentNode,c=r[s+1]?.contentNode;c&&a.setChild(c),s===r.length-1&&n&&a.setChild(n),s===0&&i&&i.setChild(a)}return r}_getFutureActions(){return ze.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 Nt(i,Nt.ActionTypes.action,new x().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Yt.say(n).getActions():ze.toActions([n]))}};var Xi=class Xi extends ce{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new Gt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Kn.set,[e,t]))}assign(e){return this.chain(this.createAction(Kn.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 _(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new _(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=Xi.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new Yi(this.chain(),e,x.create(t))}};Xi.NamespacePrefix="persistent";var Rn=Xi,Ji=class Ji extends Rn{constructor(e){super(e,{}),this.namespace=this.prefix(e,Ji.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new Gt(this.namespace,this.defaultContent))}};Ji.LocalNamespacePrefix="local";var In=Ji;var Mn=class extends ${executeAction(e,t){if(this.type===mn.action)return super.executeAction(e,t);if(this.type===mn.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")}};Mn.ActionTypes=mn;var it=class it extends ct{static get DefaultUserConfig(){return it._defaultUserConfig??(it._defaultUserConfig=new B({zIndex:0,...J.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 Mn(this.chain(),mn.setZIndex,new x().setContent([e])))}bringToFront(){throw new k(`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=this.getInitialTransformState(),this}toData(){return{state:it.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=it.StateSerializer.deserialize(e.state),this.transformState=J.deserialize(e.transformState),this}copy(){return new it(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new Mn(this.chain(),mn.action,new x),new Ie(this.chain(),ye.init,new x().setContent([e,null,!1]))]}getInitialState(){return it.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(J.DefaultTransformState.keys());return new J(J.DefaultTransformState.create(e.get()).get())}};it._defaultUserConfig=null,it.DefaultConfig=new B({name:"(anonymous)",zIndex:0}),it.StateSerializer=new Qe,it.DefaultState=new B({zIndex:0});var Nn=it;var ti=class extends ce{constructor(e){super(),this.scene=e}show(e){let t=new se(this.scene.chain(),X.nvlShow,new x().setContent([e]));return this.chain(t)}hide(e){let t=new se(this.scene.chain(),X.nvlHide,new x().setContent([e]));return this.chain(t)}end(){let e=new se(this.scene.chain(),X.nvlEnd,new x().setContent([]));return this.chain(e)}};var Fe=class Fe extends Ln{constructor(t,n){super();this.srcManager=new Le;this.events=new q;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 In(t)}static get DefaultSceneConfig(){return Fe._defaultSceneConfig??(Fe._defaultSceneConfig=new B({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Nn("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Nn("[[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(!zi(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 Qe({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(je.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new je({allowFutureScene:!1}),i=>{let s=z({},n instanceof Ft?{transition:n}:n);return i.chain(new se(i,"scene:preUnmount",new x().setContent([]))).chain(this._initScene(t))._transitionToScene(s.transition,t).chain(this._exit()),i})._jumpTo(t)}setBackgroundMusic(t,n){return this.chain(new se(this.chain(),X.setBackgroundMusic,new x().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new ti(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},u=new se(this.chain(),X.nvlEnd,new x().setContent([l])),d=[...c,u];super.constructNodes(d);let p=new se(this.chain(),X.nvlBlock,new x().setContent([d,l]));return this.chain(p)}action(t){return this.actions=t,this}preloadImage(t){if(!w.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 se(this.chain(),"scene:action",new x);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(m=>ze.isChained(m)?m.fromChained(m):m).flat(2),s=[],a=[],c=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(m=>{ze.isChained(m)||(m instanceof I?s.push(m):m instanceof gn?a.push(m):m instanceof kt&&c.push(m))});let l=[],u=[],d=new Map;s.forEach(m=>{m.config.isWearable?u.push(m):m.config.autoInit&&l.push(m);for(let y of m.config.wearables){if(d.get(y)&&d.get(y)!==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(y)?.state.currentSrc+`)
|
|
26
|
-
Current Parent (src: `+m.state.currentSrc+")");d.set(y,m)}});let p=[...this._initScene(this),...l.map(m=>m._init(this)),...u.map(m=>{if(!d.has(m))throw new Error("Wearable image must have a parent image");return d.get(m)._initWearable(m)}),...a.map(m=>m._init()),...c.map(m=>m._init()),...r],h=super.constructNodes(p),
|
|
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 R({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 re(this.chain(),"scene:jumpTo",new C().setContent([t])))}_exit(){return new re(this.chain(),"scene:exit",new C().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new re(i,J.transitionToScene,new C().setContent([t,n]))):i}_init(t){return new re(this.chain(),"scene:init",new C().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};He.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"},He.DefaultUserConfig=new K({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),He._defaultSceneConfig=null;var gt=He;import*as da from"howler";var Yi=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 _c={volume:1,limit:1/0},el=class sa{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={..._c,...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 sa(e,this.audioProvider,t,this);return this.subChannels.set(e,n),this.audioProvider.registerChannel(n),n}getChannel(e){return this.ensureNotRemoved(),this.subChannels.get(e)??null}getChannels(){return this.ensureNotRemoved(),Array.from(this.subChannels.values())}setVolume(e){return this.ensureNotRemoved(),this.volume=Math.max(0,Math.min(1,e)),this.muted||(this.gainNode.gain.value=this.volume),this}getVolume(){return this.volume}mute(e){return this.ensureNotRemoved(),this.muted=e!==void 0?e:!0,this.gainNode.gain.value=this.muted?0:this.volume,this}unmute(){return this.mute(!1)}isMuted(){return this.muted}remove(){if(this.removed)return this;this.removed=!0;for(let t of this.tokens)t.stop();this.tokens.clear();let e=Array.from(this.subChannels.values());this.subChannels.clear();for(let t of e)t.remove();try{this.gainNode.disconnect()}catch(t){console.warn("Failed to disconnect Channel gain node during remove().",t)}return this.audioProvider.unregisterChannel(this),this.parentChannel&&this.parentChannel.removeSubChannel(this.name),this}removeSubChannel(e){this.subChannels.delete(e)}getTokens(){this.ensureNotRemoved();let e=[...this.tokenQueue];for(let t of this.subChannels.values())e.push(...t.getTokens());return e}isRemoved(){return this.removed}getParent(){return this.parentChannel}getOptions(){return{...this.options}}},aa=!1;function tl(o){aa=o}function rn(o,e){aa||(e!==void 0?console.warn(o,e):console.warn(o))}var nl=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){rn("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){rn("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){rn("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()}},ra=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}},il=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 nl(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){rn("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){rn("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 ra(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new ra(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}},ol=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}},rl=10*1024*1024,sl=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 ol(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}}},al={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},ca=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...al,...o},tl(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new sl(this.audioContext),this.masterChannel=new el("__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=>{rn("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:c=!1}=e??{},l,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")l=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),l=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),l=p}let d=new il(this.audioContext,l,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(l instanceof AudioBufferSourceNode?(l.loop=c,c&&s!==void 0&&(l.loopStart=r,l.loopEnd=s)):l instanceof HTMLAudioElement&&(l.loop=c),u){let p=!1,h=()=>{p||(p=!0,u.releaseRef?.())};d.once("ended",h),d.once("stop",h)}return d}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<rl?"full":"stream"}catch(t){return rn("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=>{rn("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var de=class de{constructor(e){this.gameState=e;this.state=new Map;this.channels=new Map;this.busTree=null;this.busSubscription=null;this.unknownBuses=new Set;this.globalVolume=1;this.ready=Promise.resolve();this.isReady=!1;this.isInitializing=!1}get mixer(){return this.gameState.game.audioBuses}initialize(){if(this.isReady||this.isInitializing)return;this.mixer.getTree();let e=new ca({maxChannels:de.MaxChannels});this.sound=e,this.isInitializing=!0,this.ready=e.onceReady().then(()=>{e.setVolume(this.globalVolume),this.realizeBusTree(e),this.isReady=!0,this.isInitializing=!1}).catch(t=>{throw this.isInitializing=!1,this.gameState.logger.error("AudioManager","Failed to initialize audio subsystem",t),t})}realizeBusTree(e){let t=this.mixer.getTree();this.busTree=t,this.channels.clear(),t.getNodes().forEach(n=>{let i=this.mixer.getEffectiveVolume(n.id),r=n.parentId===null?null:this.channels.get(n.parentId)??null,a=(r?r.getChannel(n.id):e.getChannel(n.id))??(r?r.createChannel(n.id,{volume:i}):e.createChannel(n.id,{volume:i}));this.applyBusVolume(a,i,!1),this.channels.set(n.id,a)}),this.busSubscription?.cancel(),this.busSubscription=this.mixer.onVolumeChange((n,i,r)=>{this.applyBusVolume(this.channels.get(n)??null,r,!0)})}applyBusVolume(e,t,n){if(!e)return;let i=de.readGain(e);if(e.setVolume(t),!n||i===null)return;let r=e.getGainNode().gain,s=e.getVolume();if(typeof r.setTargetAtTime!="function"||typeof r.cancelScheduledValues!="function"||typeof this.sound?.getAudioContext!="function")return;let a=this.sound.getAudioContext().currentTime;r.cancelScheduledValues(a),r.setValueAtTime(i,a),r.setTargetAtTime(s,a,de.BusRampTimeConstant),r.setValueAtTime(s,a+de.BusRampSettle)}static readGain(e){if(typeof e.getGainNode!="function")return null;let t=e.getGainNode()?.gain;return typeof t?.value=="number"?t.value:null}channelFor(e){let t=this.channels.get(e.config.type);return t||(this.channels.size>0&&!this.unknownBuses.has(e.config.type)&&(this.unknownBuses.add(e.config.type),this.gameState.logger.weakWarn("AudioManager",`No audio bus "${e.config.type}" is declared; playing on "${nt.sound}" instead.`)),this.channels.get(nt.sound)??null)}static defaultFade(e){return{end:e.state.volume,duration:0}}play(e,t=de.defaultFade(e)){let n=new S;return this.ready.then(async()=>{this.state.has(e)&&this.state.get(e).token.stop();try{let i=this.channelFor(e),r=await this.sound.load(e.config.src),s=de.clipRegionOf(e),a=await i.play(r,{volume:0,...de.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,s);let c=e.state.muted??!1;a.mute(c),e.state.muted=c,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(l=>{a.once("ended",()=>l())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t=de.defaultFade(e)){await this.ready,this.state.has(e)&&this.state.get(e).token.stop();try{let n=this.channelFor(e);if(!n)throw new P(`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,c=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=c<i?c:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,S.resolve(void 0)):S.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime()}]),groups:this.getBuses().map(e=>[e.id,e.volume])}}fromData(e,t){return e.groups?.forEach(([n,i])=>{this.setBusVolume(n,i)}),e.sounds.forEach(([n,i])=>{let r=t.get(n);if(!r){this.gameState.logger.weakWarn("AudioManager",`Skipped restoring a sound that is not in this story (id: "${n}")`);return}this.soundFromData(r,i)}),this}soundFromData(e,t){this.state.has(e)&&this.state.get(e).token.stop(),this.ready.then(async()=>{try{let n=this.channelFor(e),i=await this.sound.load(e.config.src),r=de.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...de.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&de.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(de.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let c=e.state.muted??!1;a.mute(c),e.state.muted=c,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 Qi=de;import*as ml from"html-to-image";var Xi=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 we(t);return t.registerSkipController(new G(()=>{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 Ji(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 cl=4e3,pa={zIndex:0,visibility:"visible"},ll={...pa,zIndex:1},la={position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:2};function Zi(){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 ul(){return{...Zi(),visibility:"hidden"}}var _i=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 G(s.cancel)),c=new we(a),l=[],u=r.resolve.map(h=>{if(typeof h=="function"){let m=this.createOverlay();return l.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(h.key==="target"?t.to:t.from).getId(),role:h.key}}),d={task:r,controller:s,roles:t,targets:u,overlays:l,cancelLoadGate:()=>{},stale:!1};this.running=d,s.onUpdate(h=>this.applyFrame(d,h)),s.onComplete(()=>{this.settle(d,[[t.to,Zi()],[t.from,ul()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(d,[[t.from,Zi()],[t.to,Zi()]]),c.abort()}),this.applyFrame(d,r.animations.map(h=>h.start));let p=this.waitForSceneReady(t.to);return d.cancelLoadGate=p.cancel,p.promise.then(()=>{d.stale||s.start()}),c}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?r.element:this.sceneElements.get(r.sceneId)??null;if(!s)return;let a=typeof n=="function"?n:n.resolver,c=r.kind==="overlay"?la:r.role==="target"?ll:pa,l=$({style:c},a(...t));Ji(s,l,pl)})}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,la),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()},cl)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(dl)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},ua=["src","width","height"];function pl(o){if(!ua.some(t=>t in o))return o;let e={...o};return ua.forEach(t=>delete e[t]),e}function dl(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 eo=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let i=Ni(6),{action:r,timeline:s,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(l))}return{id:i}}has(e){return this.history.some(t=>t.id===e)}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var to=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??Ni(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 hn=class extends j{executeAction(e,t){let n=new S().registerSkipController(new G(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.reset()},e.gameHistory.updateByToken(l,p=>{p&&p.element.type==="menu"&&(p.element.selected=u.evaluated,p.isPending=!1)})}),{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{c.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:l,action:this,element:{type:"menu",text:c.prompt,selected:null},isPending:!0,snapshot:e.getLiveGame().captureGameState()}),n}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};hn.ActionTypes=Ls;var gn=class gn extends ce{constructor(t,n={}){super();this.choices=[];this.prompt=fe.isSentence(t)?t:t===null?null:new fe(t),this.config=$(gn.defaultConfig,n)}static prompt(t,n={}){return new gn(t!==void 0?t:null,n)}static choose(t,n){return new gn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return fe.isSentence(t)&&n?i.choices.push({prompt:fe.toSentence(t),action:this.narrativeToActions(n),config:{}}):(Z.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:fe.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:fe.toSentence(t.prompt),action:this.narrativeToActions(t.action),config:{disabled:t.config?.disabled?q.from(t.config.disabled):void 0,hidden:t.config?.hidden?q.from(t.config.hidden):void 0}}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),i}hideIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Ge("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.hideIf` before `menu.choose`");return n.config.hidden=q.from(t),this.chain()}disableIf(t){let n=this.choices[this.choices.length-1];if(!n)throw new Ge("Trying to configure the last choice of a menu, but no choice added. This may be caused by calling `menu.disableIf` before `menu.choose`");return n.config.disabled=q.from(t),this.chain()}enableWhen(t,n,i){return this.choose({prompt:n,action:i,config:{disabled:q.not(q.from(t))}})}showWhen(t,n,i){return this.choose({prompt:n,action:i,config:{hidden:q.not(q.from(t))}})}fromChained(t){return[new hn(this.chain(),hn.ActionTypes.action,new C().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?qt.say(n).getActions():ze.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??{}}))}};gn.defaultConfig={},gn.targetAction=hn;var sr=gn;var Gt=class Gt extends ut{static get DefaultUserConfig(){return Gt._defaultUserConfig??(Gt._defaultUserConfig=new K({...X.DefaultTransformState.getDefaultConfig(),opacity:1}))}constructor(e={}){super();let t=Gt.DefaultUserConfig.create(e),n=Gt.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})}resetCamera(e,t){return this.transform(new _([{props:{filter:"none"},options:{duration:0}},{props:{position:new ct("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1},options:{duration:e,ease:t}}]))}bringToFront(){throw new P(`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=this.getInitialTransformState(),this}toData(){return{transformState:this.transformState.serialize()}}fromData(e){return this.transformState=X.deserialize(e.transformState),this}copy(){return new Gt(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(X.DefaultTransformState.keys());return new X(X.DefaultTransformState.create(e.get()).get())}};Gt._defaultUserConfig=null,Gt.DefaultConfig=new K({name:"(camera)"});var ei=Gt;var sn=class sn extends En{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=$(sn.defaultConfig,r),this._camera=i??new ei}static empty(){return new sn("empty").entry(new gt("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 Dn(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 Ge(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return Ws(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(!qo(r))throw new ne(`Service ${i} serialize method should return a pure object.
|
|
26
|
+
Current Parent (src: `+m.state.currentSrc+")");d.set(y,m)}});let p=[...this._initScene(this),...l.map(m=>m._init(this)),...u.map(m=>{if(!d.has(m))throw new Error("Wearable image must have a parent image");return d.get(m)._initWearable(m)}),...a.map(m=>m._init()),...c.map(m=>m._init()),...r],h=super.constructNodes(p),f=new x(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 oe&&r.type===ne.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 oe&&r.type===ne.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"?Yt.say(n).getActions():ze.toActions([n]))}isSceneRootConstructed(){return!!this.sceneRoot}registerSrc(t,n=new Set){if(!this.sceneRoot)return;let i=new Set,r=new Set,s=[this.sceneRoot],a=new Set;for(;s.length;){let c=s.shift();if(!i.has(c)){if(i.add(c),c instanceof se){let l=c.callee;if(w.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:w.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===X.jumpTo){let u=c,d=Fe.getScene(t,u.contentNode.getContent()[0]);if(!d)throw c._sceneNotFoundError(c.getSceneName(u.contentNode.getContent()[0]));let p=Le.getPreloadableSrc(t,c);if(p&&this.srcManager.register(p),r.has(u)||n.has(d))continue;r.add(u),a.add(d),n.add(d)}}else if(c instanceof Se){let l=Le.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof et)this.srcManager.register(c.callee);else if(c instanceof nt){let l=c.type===jt.say?c.contentNode.getContent():null;for(let u of la(c.callee,l))this.srcManager.register({type:"image",src:w.srcToURL(u)})}else if(c instanceof oe){let u=c.getFutureActions(t,{allowFutureScene:!0});s.push(...u)}else c instanceof Ie&&this.srcManager.register(c.callee.srcManager.getSrc());s.push(...c.getFutureActions(t,{allowFutureScene:!0}))}}a.forEach(c=>{c.registerSrc(t,n),this.srcManager.registerFuture(c.srcManager)})}assignActionId(t){let n=this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}),i=new Set;n.forEach(a=>{let c=a.getStaticId();if(c){if(i.has(c))throw new He(`Duplicate static action id: ${c}`);i.add(c)}});let r=0,s=()=>{let a=`a-${r++}`;for(;i.has(a);)a=`a-${r++}`;return i.add(a),a};n.forEach(a=>{let c=a.getStaticId();a.resolveId(c||s())})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((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&&!zi(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 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 se(this.chain(),"scene:jumpTo",new x().setContent([t])))}_exit(){return new se(this.chain(),"scene:exit",new x().setContent([]))}_transitionToScene(t,n){let i=this.chain();return t?i.chain(new se(i,X.transitionToScene,new x().setContent([t,n]))):i}_init(t){return new se(this.chain(),"scene:init",new x().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 gt=Fe;import*as Ta 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 sl={volume:1,limit:1/0},al=class pa{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={...sl,...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 pa(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}}},da=!1;function cl(o){da=o}function sn(o,e){da||(e!==void 0?console.warn(o,e):console.warn(o))}var ll=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){sn("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){sn("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){sn("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()}},ua=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}},ul=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 ll(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){sn("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){sn("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 ua(this,e);return r.finish(),r}this.volume=o,this._isMuted||(this.gainNode.gain.value=o);let n=new ua(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}},pl=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}},dl=10*1024*1024,ml=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 pl(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}}},fl={volume:1,latencyHint:"interactive",sampleRate:44100,maxChannels:128,silent:!1},ma=class{constructor(o){this.registeredChannels=new Set,this.isReady=!1,this.readyPromise=null,this.destroyed=!1,this.unlockHandler=null,this.options={...fl,...o},cl(!!this.options.silent),this.audioContext=new AudioContext({latencyHint:this.options.latencyHint,sampleRate:this.options.sampleRate}),this.audioCache=new ml(this.audioContext),this.masterChannel=new al("__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=>{sn("Failed to resume AudioContext while unlocking.",t)})};this.unlockHandler=e,document.addEventListener("click",e),document.addEventListener("touchstart",e),document.addEventListener("keydown",e)})}clearUnlockHandler(){if(!this.unlockHandler||typeof document>"u")return;let o=this.unlockHandler;this.unlockHandler=null,document.removeEventListener("click",o),document.removeEventListener("touchstart",o),document.removeEventListener("keydown",o)}ensureNotDestroyed(){if(this.destroyed)throw new Error("Sound instance has been destroyed and cannot be used.")}ensureReady(){if(!this.isReady)throw new Error("Audio context is not ready. Call onceReady() and wait for it to resolve before creating channels or playing audio.")}getAudioContext(){return this.audioContext}async createToken(o,e,t){this.ensureNotDestroyed(),this.ensureReady();let{volume:n=1,rate:i=1,startTime:r=0,endTime:s,load:a="auto",loop:c=!1}=e??{},l,u=null;if(typeof o=="string")if(await this.resolveLoadMode(o,a)==="stream")l=this.createStreamSource(o);else{u=await this.audioCache.load(o),u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=u.raw(),l=p}else{u=o,u.addRef?.();let p=this.audioContext.createBufferSource();p.buffer=o.raw(),l=p}let d=new ul(this.audioContext,l,{volume:n,rate:i,startOffset:r,duration:s?s-r:0},t);if(l instanceof AudioBufferSourceNode?(l.loop=c,c&&s!==void 0&&(l.loopStart=r,l.loopEnd=s)):l instanceof HTMLAudioElement&&(l.loop=c),u){let p=!1,h=()=>{p||(p=!0,u.releaseRef?.())};d.once("ended",h),d.once("stop",h)}return d}async resolveLoadMode(o,e){if(e==="stream"||e==="full")return e;try{let t=await fetch(o,{method:"HEAD"});if(!t.ok)return"stream";let n=t.headers.get("Content-Length");if(!n)return"stream";let i=parseInt(n,10);return isNaN(i)?"stream":i<dl?"full":"stream"}catch(t){return sn("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=>{sn("Failed to close AudioContext during destroy().",o)}))}isDestroyed(){return this.destroyed}};var ue=class ue{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 ma({maxChannels:ue.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=ue.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,ue.BusRampTimeConstant),r.setValueAtTime(s,a+ue.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=ue.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=ue.clipRegionOf(e),a=await i.play(r,{volume:0,...ue.playRegionOf(s,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&ue.applyLoopRegion(a,s);let c=e.state.muted??!1;a.mute(c),e.state.muted=c,this.state.set(e,{token:a,cachedAudio:r,originalVolume:t.end}),t.duration>0?await a.fade(0,t.end,t.duration).finished:a.setVolume(t.end),e.state.volume=t.end,e.state.paused=!1,e.config.loop||await new Promise(l=>{a.once("ended",()=>l())}),n.resolve()}catch(i){this.gameState.logger.error("AudioManager",`Failed to play sound (src: "${e.config.src}")`,i),n.resolve()}}),n}async playSoundToken(e,t=ue.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 k(`Channel not found for audio bus: "${e.config.type}"`);let i=await this.sound.load(e.config.src),r=ue.clipRegionOf(e),s=await n.play(i,{volume:0,...ue.playRegionOf(r,e.config.loop),loop:e.config.loop,rate:e.state.rate});e.config.loop&&ue.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=ue.clampToRegion(t,ue.clipRegionOf(e));return n.token.seek(i),n.pausePosition!==void 0&&(n.pausePosition=i),S.resolve(void 0)}static clipRegionOf(e){let t=e.config.seek,n=e.config.endTime;if(n===void 0||!Number.isFinite(n)||n<=t)return{startTime:t};let i=e.config.loopStart;return i===void 0||!Number.isFinite(i)?{startTime:t,endTime:n}:{startTime:t,endTime:n,loopStart:i}}static playRegionOf(e,t){return t||e.endTime===void 0?{startTime:e.startTime}:{startTime:e.startTime,endTime:e.endTime}}static applyLoopRegion(e,t){let{startTime:n,endTime:i}=t;if(i===void 0||!Number.isFinite(i)||i<=n||typeof AudioBufferSourceNode>"u")return;let r=e.sourceController;if(typeof r?.getSource!="function")return;let s=r.getSource();if(!(s instanceof AudioBufferSourceNode))return;let a=t.loopStart,c=a!==void 0&&Number.isFinite(a)?Math.min(Math.max(a,n),i):n;s.loop=!0,s.loopStart=c<i?c:n,s.loopEnd=i}static clampToRegion(e,t){let n=Math.max(0,e);return t.endTime===void 0?n:n>=t.endTime?t.startTime:n}setRate(e,t){return this.state.has(e)?(this.state.get(e).token.setRate(t),e.state.rate=t,S.resolve(void 0)):S.resolve(void 0)}getPosition(e){return this.state.has(e)?this.state.get(e).token.getCurrentTime():0}isPlaying(e){return this.isManaged(e)?this.state.get(e).token.isPlaying():!1}getToken(e){return this.state.get(e)?.token??null}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.token.isPlaying(),position:t.token.getCurrentTime()}]),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=ue.clipRegionOf(e),s=r.endTime!==void 0&&e.config.loop,a=await n.play(i,{volume:e.state.volume,...ue.playRegionOf(r,e.config.loop),startTime:s?r.startTime:t.position,loop:e.config.loop,rate:e.state.rate});e.config.loop&&ue.applyLoopRegion(a,r),s&&Math.abs(t.position-r.startTime)>.01&&a.seek(ue.clampToRegion(t.position,r)),this.state.set(e,{token:a,cachedAudio:i,originalVolume:e.state.volume});let c=e.state.muted??!1;a.mute(c),e.state.muted=c,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()}};ue.MaxChannels=1024,ue.BusRampTimeConstant=.02,ue.BusRampSettle=ue.BusRampTimeConstant*5;var _i=ue;import*as Tl from"html-to-image";var eo=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new q}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 xe(t);return t.registerSkipController(new H(()=>{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 hl=4e3,ga={zIndex:0,visibility:"visible"},gl={...ga,zIndex:1},fa={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 yl(){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 H(s.cancel)),c=new xe(a),l=[],u=r.resolve.map(h=>{if(typeof h=="function"){let m=this.createOverlay();return l.push(m),{kind:"overlay",element:m}}return{kind:"scene",sceneId:(h.key==="target"?t.to:t.from).getId(),role:h.key}}),d={task:r,controller:s,roles:t,targets:u,overlays:l,cancelLoadGate:()=>{},stale:!1};this.running=d,s.onUpdate(h=>this.applyFrame(d,h)),s.onComplete(()=>{this.settle(d,[[t.to,no()],[t.from,yl()]]),n(),a.resolve()}),s.onCanceled(()=>{this.settle(d,[[t.from,no()],[t.to,no()]]),c.abort()}),this.applyFrame(d,r.animations.map(h=>h.start));let p=this.waitForSceneReady(t.to);return d.cancelLoadGate=p.cancel,p.promise.then(()=>{d.stale||s.start()}),c}applyFrame(e,t){e.task.resolve.forEach((n,i)=>{let r=e.targets[i],s=r.kind==="overlay"?r.element:this.sceneElements.get(r.sceneId)??null;if(!s)return;let a=typeof n=="function"?n:n.resolver,c=r.kind==="overlay"?fa:r.role==="target"?gl:ga,l=z({style:c},a(...t));to(s,l,vl)})}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,fa),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()},hl)}),r=Promise.all(Array.from(t.querySelectorAll("img")).map(Sl)).then(()=>{});return{promise:Promise.race([r,i]),cancel:()=>n()}}},ha=["src","width","height"];function vl(o){if(!ha.some(t=>t in o))return o;let e={...o};return ha.forEach(t=>delete e[t]),e}function Sl(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,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:r,id:i,args:n||[],undo:t,timeline:s,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(u=>u(l))}return{id:i}}has(e){return this.history.some(t=>t.id===e)}undoUntil(e){let t=-1;for(let r=this.history.length-1;r>=0;r--)if(this.history[r].id===e){t=r;break}if(t===-1)return null;let n=[];for(let r=this.history.length-1;r>=t;r--)this.history[r].timeline&&!this.history[r].timeline.isSettled()&&this.history[r].timeline.abort(),this.liveGame.getGameStateForce?.().logger?.debug("ActionHistory","Undoing",this.history[r].action.type),this.history[r].undo?.(...this.history[r].args||[]),n.push(this.history[r]);this.history.length=t,this.hooks.onUndo.forEach(r=>r(n));let i=this.liveGame.getStackModelForce().serialize();if(i){let[r]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(i,r)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let i=t.length-1;i>=0;i--)if(t[i].isPending!==!0){n=t[i];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var 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 yn=class extends ${executeAction(e,t){let n=new S().registerSkipController(new H(()=>{c.cancel()})),i=e.timelines.attachTimeline(n),r=this.contentNode.getContent(),s=e.createPresentationSnapshot(),a=null,c=e.createMenu(r,u=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:u.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[d]}}),a=()=>{d.reset()},e.gameHistory.updateByToken(l,p=>{p&&p.element.type==="menu"&&(p.element.selected=u.evaluated,p.isPending=!1)})}),{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:i},()=>{c.cancel(),a?.(),e.restorePresentationSnapshot(s)});return e.gameHistory.push({token:l,action:this,element:{type:"menu",text:c.prompt,selected:null},isPending:!0,snapshot:e.getLiveGame().captureGameState()}),n}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let i=this.contentNode.getContent(),r=i.choices.map(s=>`{${s.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${i.prompt}) {[${r.join(",")}]}`)}};yn.ActionTypes=Gs;var vn=class vn extends ce{constructor(t,n={}){super();this.choices=[];this.prompt=de.isSentence(t)?t:t===null?null:new de(t),this.config=z(vn.defaultConfig,n)}static prompt(t,n={}){return new vn(t!==void 0?t:null,n)}static choose(t,n){return new vn(null,{}).choose(t,n)}choose(t,n){let i=this.chain();return de.isSentence(t)&&n?i.choices.push({prompt:de.toSentence(t),action:this.narrativeToActions(n),config:{}}):(_.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?i.choices.push({prompt:de.toSentence(t),action:this.narrativeToActions(n),config:{}}):typeof t=="object"&&"prompt"in t&&"action"in t?i.choices.push({prompt:de.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 yn(this.chain(),yn.ActionTypes.action,new x().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"?Yt.say(n).getActions():ze.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??{}}))}};vn.defaultConfig={},vn.targetAction=yn;var lr=vn;var yt={shutter:0,shutterColor:"#000",vignette:0,vignetteColor:"#000",vignetteInner:"44%",vignetteOuter:"78%"};function ur(o){return typeof o!="number"||!Number.isFinite(o)?0:Math.max(0,Math.min(1,o))}function ni(o,e){return typeof o=="string"&&o.length>0?o:e}function ya(o){let e=ur(o.shutter);return{backgroundColor:ni(o.shutterColor,yt.shutterColor),clipPath:`inset(0 0 ${100-50*e}% 0)`}}function va(o){let e=ur(o.shutter);return{backgroundColor:ni(o.shutterColor,yt.shutterColor),clipPath:`inset(${100-50*e}% 0 0 0)`}}function Sa(o){let e=ni(o.vignetteInner,yt.vignetteInner),t=ni(o.vignetteOuter,yt.vignetteOuter),n=`radial-gradient(circle at center, transparent ${e}, black ${t})`;return{backgroundColor:ni(o.vignetteColor,yt.vignetteColor),opacity:ur(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 ct{static get DefaultUserConfig(){return ut._defaultUserConfig??(ut._defaultUserConfig=new B({...J.DefaultTransformState.getDefaultConfig(),opacity:1,...yt}))}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 Z(e,t))}resetCamera(e,t){return this.transform(new Z([{props:{filter:"none"},options:{duration:0}},{props:{position:new st("center"),scaleX:1,scaleY:1,zoom:1,rotation:0,opacity:1,shutter:yt.shutter,vignette:yt.vignette},options:{duration:e,ease:t}},{props:{shutterColor:yt.shutterColor,vignetteColor:yt.vignetteColor,vignetteInner:yt.vignetteInner,vignetteOuter:yt.vignetteOuter},options:{duration:0}}]))}static clampLens(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}bringToFront(){throw new k(`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=this.getInitialTransformState(),this}toData(){return{transformState:this.transformState.serialize()}}fromData(e){return this.transformState=J.deserialize(e.transformState),this}copy(){return new ut(this.userConfig.get())}getInitialTransformState(){let[e]=this.userConfig.extract(ut.DefaultUserConfig.keys());return new J(ut.DefaultUserConfig.create(e.get()).get())}};ut._defaultUserConfig=null,ut.DefaultConfig=new B({name:"(camera)"});var ii=ut;var an=class an extends Ln{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=z(an.defaultConfig,r),this._camera=i??new ii}static empty(){return new an("empty").entry(new gt("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 Rn(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 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 ie(`Service ${i} serialize method should not return a promise`);if(!Xo(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(gt.isScene(t))return t;let r=this.scenes.get(t)||null;if(!r&&n)throw Reflect.construct(i||
|
|
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 G(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")}};an.ActionTypes=Zt;var ro=an;var Nn=class Nn extends ce{constructor(e){super();let t=Nn.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ne("Vfx must have a src")}show(e){return this.chain(this.createAction(Zt.show,[e]))}hide(e){return this.chain(this.createAction(Zt.hide,[e]))}pause(){return this.chain(this.createAction(Zt.pause,[]))}resume(){return this.chain(this.createAction(Zt.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(Zt.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 Nn.DefaultVfxState.create().get()}createAction(e,t){return new ro(this.chain(),e,C.create(t))}};Nn.DefaultVfxConfig=new K({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),Nn.DefaultVfxState=new K({display:!1,paused:!1});var ur=Nn;var le=class le{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 Bn;this.htmlToImage=ml;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 Yi(e,"NarraLeaf-React"),this.audioManager=new Qi(this),this.guard=new Wi(e.config.app.guard).observe(this),this.timelines=new Bi(this.guard),this.notificationMgr=new Xi(this,[]),this.idManager=new Ei,this.actionHistory=new eo(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new to(this.actionHistory),this.stageTransition=new _i(this),this.events.on(le.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=gt.isScene(e)?e:e.entryScene;if(!t)throw new P("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(le.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(or);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let c=s[a];for(let l=c.length-1;l>=0;l--){let u=c[l],d=r.get(u);if(d&&this.isDisplayableVisible(u))return d}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(Ce.getCtx({gameState:this}));this.game.getLiveGame().events.emit(Mt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:Z.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1)},text:Z.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(Ce.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(Mt.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?Z.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(le.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(le.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(le.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(le.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(le.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(le.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(le.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})=>re.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(le.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(le.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(le.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(le.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{re.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(le.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(le.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(le.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(le.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(le.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 P(`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 P("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=we.proxy(S.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof ut&&n.push(i)}),n.forEach(i=>{let r=this.getExposedStateForce(i),s=r.applyTransform(_.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(le.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 P("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(le.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:c})=>{this.logger.debug("Loading scene: "+a);let l=t.get(a);if(!l)throw new P("Scene not found, id: "+a+`
|
|
37
|
-
NarraLeaf cannot find the element with the id from the saved game`);let u={scene:l,layers:this.constructLayerMap(c.layers,t),menus:[],texts:[]};this.state.elements.push(u),this.registerSrcManager(l.srcManager),this.getExposedStateAsync(l,d=>{
|
|
38
|
-
NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),this.state.vfx=(e.vfx??[]).map(([a,c])=>{let l=t.get(a);if(!l)throw new
|
|
39
|
-
NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),e.nvlState){let a=(e.nvlState.dialogs||[]).map(c=>{let l=c.characterId&&t.get(c.characterId)||null,u=c.text||"";return{id:c.id,actionId:c.actionId||c.id,character:l,sentence:new
|
|
40
|
-
NarraLeaf cannot find the element with the id from the saved game`);return[r,i.map(s=>{if(!t.has(s))throw new
|
|
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(gt.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>an.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${an.MAX_DEPTH})`);let s=i.shift();if(gt.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 so(t).run(this)}};an.defaultConfig={origin:"bottom left"},an.MAX_DEPTH=32767;var oi=an;var ao=class extends ${executeAction(e,t){let[n,i]=this.contentNode.getContent(),r=this.callee.triggerAction(Ce.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 pr=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(Ks(r)){let s=[],a=new S().registerSkipController(new H(()=>{for(let l of s)l?.()}));return r({...t,onAbort:l=>{s.push(l)}},...i).then(()=>a.resolve()),a}r({...t,onAbort:()=>{}},...i)}_registerActionHandler(t,n){this._handlers[t]=n}_createAction(t,n,i){return new ao(t,"service:action",new x().setContent([n,i]))}},dr=class extends pr{},ri=class extends dr{};var Vt=class Vt extends ${executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(Vt,"video:play"))return this.changeStateAsync(e,s=>s.play(),t);if(n.is(Vt,"video:pause"))return this.changeState(e,s=>s.pause(),t);if(n.is(Vt,"video:stop"))return this.changeState(e,s=>s.stop(),t);if(n.is(Vt,"video:seek"))return this.changeState(e,s=>s.seek(n.contentNode.getContent()[0]),t);if(n.is(Vt,"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(Vt,"video:hide")){let s=i.state.display;return this.changeState(e,a=>{i.state.display=!1,e.actionHistory.push(r,c=>{i.state.display=c},[s]),a.hide(),e.removeVideo(i),e.stage.update()},t)}else if(n.is(Vt,"video:resume"))return this.changeState(e,s=>s.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new k(`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 H(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")}};Vt.ActionTypes=Mt;var co=Vt;var Gn=class Gn extends ce{constructor(e){super();let t=Gn.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ie("Video must have a src")}show(){return this.chain(this.createAction(Mt.show,[]))}hide(){return this.chain(this.createAction(Mt.hide,[]))}play(){return this.chain(this.createAction(Mt.play,[]))}pause(){return this.chain(this.createAction(Mt.pause,[]))}resume(){return this.chain(this.createAction(Mt.resume,[]))}stop(){return this.chain(this.createAction(Mt.stop,[]))}seek(e){return this.chain(this.createAction(Mt.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 Gn.DefaultVideoState.create().get()}createAction(e,t){return new co(this.chain(),e,x.create(t))}};Gn.DefaultVideoConfig=new B({src:"",muted:!1}),Gn.DefaultVideoState=new B({display:!1});var mr=Gn;var cn=class cn extends ${executeAction(e,t){let n=this,i=this.callee,r={action:n,stackModel:t.stackModel};if(n.is(cn,"vfx:show")){let[s]=n.contentNode.getContent(),a=i.state.display;return e.isVfxAdded(i)||(e.addVfx(i),e.stage.update()),i.state.display=!0,e.actionHistory.push(r,c=>{i.state.display=c},[a]),this.changeStateAsync(e,c=>c.show(s),t)}else if(n.is(cn,"vfx:hide")){if(!e.isVfxAdded(i))return e.logger.weakWarn("NarraLeaf-React: Vfx","Hiding a Vfx that is not shown, ignored. (src: "+i.config.src+")"),S.resolve(super.executeAction(e,t));let[s]=n.contentNode.getContent(),a=i.state.display;return this.changeStateAsync(e,async c=>{await c.hide(s),i.state.display=!1,e.actionHistory.push(r,l=>{i.state.display=l},[a]),e.removeVfx(i),e.stage.update()},t)}else{if(n.is(cn,"vfx:pause"))return this.changeState(e,s=>{i.state.paused=!0,s.pause()},t);if(n.is(cn,"vfx:resume"))return this.changeState(e,s=>{i.state.paused=!1,s.resume()},t);if(n.is(cn,"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 k(`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 H(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")}};cn.ActionTypes=_t;var lo=cn;var Hn=class Hn extends ce{constructor(e){super();let t=Hn.DefaultVfxConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new ie("Vfx must have a src")}show(e){return this.chain(this.createAction(_t.show,[e]))}hide(e){return this.chain(this.createAction(_t.hide,[e]))}pause(){return this.chain(this.createAction(_t.pause,[]))}resume(){return this.chain(this.createAction(_t.resume,[]))}setPlaybackRate(e){return this.chain(this.createAction(_t.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 Hn.DefaultVfxState.create().get()}createAction(e,t){return new lo(this.chain(),e,x.create(t))}};Hn.DefaultVfxConfig=new B({src:"",blendMode:"normal",loop:!0,muted:!0,opacity:1,playbackRate:1,fit:"cover",zIndex:0}),Hn.DefaultVfxState=new B({display:!1,paused:!1});var fr=Hn;var le=class le{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 zn;this.htmlToImage=Tl;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 q,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 Ri,this.actionHistory=new oo(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new ro(this.actionHistory),this.stageTransition=new io(this),this.events.on(le.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=gt.isScene(e)?e:e.entryScene;if(!t)throw new k("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(le.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(ar);if(!t.length)return null;let n=this.getLastScene(),i=n?this.findElementByScene(n):null;if(!i)return null;let r=new Map(t.map(a=>[a.image,a])),s=Array.from(i.layers.values());for(let a=s.length-1;a>=0;a--){let c=s[a];for(let l=c.length-1;l>=0;l--){let u=c[l],d=r.get(u);if(d&&this.isDisplayableVisible(u))return d}}return null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],i=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:r=>{n.push(r)}})},t);return()=>{n.forEach(r=>r()),clearTimeout(i)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,i){let r=this.findElementByScene(this.getLastSceneIfNot(i))?.texts;if(!r)throw this.sceneNotFound();let s=t.evaluate(Ce.getCtx({gameState:this}));this.game.getLiveGame().events.emit(Ht.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:_.getText(s)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:s},()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1),n&&n()});return r.push(a),this.stage.update(),{cancel:()=>{let c=r.indexOf(a);c!==-1&&r.splice(c,1)},text:_.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(Ce.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?_.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(le.EventTypes["event:state.nvl.enter"],t,e||null),this.events.emit(le.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(le.EventTypes["event:state.nvl.visibilityChange"],!1,t),this.events.emit(le.EventTypes["event:state.nvl.exit"]),this.emitNvlStateChange(),this}setNvlVisibility(e,t){return this.nvlState={...this.nvlState,visible:e},this.events.emit(le.EventTypes["event:state.nvl.visibilityChange"],e,t),this.emitNvlStateChange(),this}appendNvlDialog(e){return this.nvlState.dialogs=[...this.nvlState.dialogs,e],this.events.emit(le.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(le.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})=>se.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(le.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.events.emit(le.EventTypes["event:state.nvl.visibilityChange"],this.nvlState.visible,this.nvlState.visible?this.nvlState.options?.showTransition:this.nvlState.options?.hideTransition)):(this.events.emit(le.EventTypes["event:state.nvl.visibilityChange"],!1,this.nvlState.options?.hideTransition),this.events.emit(le.EventTypes["event:state.nvl.exit"])),this.emitNvlStateChange(),this}restorePresentationSnapshot(e){return e.scenes.forEach(t=>{se.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(le.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(le.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(le.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(le.EventTypes["event:state.dialog.change"])),this)}settleAdvDialog(e){return this.advDialogState?.dialogId===e&&(this.advDialogState=null,this.events.emit(le.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 k(`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 Ta.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 k("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]=xe.proxy(S.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(i=>{i instanceof ct&&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 Ve("State already mounted");if(!e)throw new Ve("Invalid state key");return this.exposedState.set(e,t),this.events.emit(le.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 k("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(le.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:c})=>{this.logger.debug("Loading scene: "+a);let l=t.get(a);if(!l)throw new k("Scene not found, id: "+a+`
|
|
37
|
+
NarraLeaf cannot find the element with the id from the saved game`);let u={scene:l,layers:this.constructLayerMap(c.layers,t),menus:[],texts:[]};this.state.elements.push(u),this.registerSrcManager(l.srcManager),this.getExposedStateAsync(l,d=>{se.initBackgroundMusic(l,d)})}),this.audioManager.fromData(r,t),this.state.videos=s.map(([a,c])=>{let l=t.get(a);if(!l)throw new k("Video not found, id: "+a+`
|
|
38
|
+
NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),this.state.vfx=(e.vfx??[]).map(([a,c])=>{let l=t.get(a);if(!l)throw new k("Vfx not found, id: "+a+`
|
|
39
|
+
NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l}),e.nvlState){let a=(e.nvlState.dialogs||[]).map(c=>{let l=c.characterId&&t.get(c.characterId)||null,u=c.text||"";return{id:c.id,actionId:c.actionId||c.id,character:l,sentence:new de(u,{character:l}),text:u}});this.nvlState={active:e.nvlState.active,visible:e.nvlState.visible,sessionId:e.nvlState.sessionId,dialogs:a,options:e.nvlState.options||null,activeDialogId:e.nvlState.activeDialogId||null,phase:e.nvlState.phase||(e.nvlState.activeDialogId?"awaitAdvance":"idle"),pendingAdvance:e.nvlState.pendingAdvance||!1,isTyping:!1},this.syncNvlDerivedState(),this.nvlState.active&&this.events.emit(le.EventTypes["event:state.nvl.enter"],this.nvlState.sessionId||"",this.nvlState.options),this.nvlState.visible&&this.events.emit(le.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 k('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(le.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 k("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new k("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 k("Layer not found, id: "+n+`
|
|
40
|
+
NarraLeaf cannot find the element with the id from the saved game`);return[r,i.map(s=>{if(!t.has(s))throw new k("Displayable not found, id: "+s+`
|
|
41
41
|
NarraLeaf cannot find the element with the id from the saved game
|
|
42
|
-
This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};le.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.lineEnd":"event:state.player.lineEnd","event:state.dialog.change":"event:state.dialog.change","event:state.player.requestFlush":"event:state.player.requestFlush","event:state.player.stageClick":"event:state.player.stageClick","event:state.scene.mount":"event:state.scene.mount","event:state.scene.unmount":"event:state.scene.unmount","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes","event:state.nvl.enter":"event:state.nvl.enter","event:state.nvl.exit":"event:state.nvl.exit","event:state.nvl.dialogComplete":"event:state.nvl.dialogComplete","event:state.nvl.dialogAppend":"event:state.nvl.dialogAppend","event:state.nvl.visibilityChange":"event:state.nvl.visibilityChange","event:state.nvl.change":"event:state.nvl.change"};var E=le;var
|
|
42
|
+
This may be caused by the damage of the saved game file or the change of the story file`);return t.get(s)})]}))}};le.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.lineEnd":"event:state.player.lineEnd","event:state.dialog.change":"event:state.dialog.change","event:state.player.requestFlush":"event:state.player.requestFlush","event:state.player.stageClick":"event:state.player.stageClick","event:state.scene.mount":"event:state.scene.mount","event:state.scene.unmount":"event:state.scene.unmount","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes","event:state.nvl.enter":"event:state.nvl.enter","event:state.nvl.exit":"event:state.nvl.exit","event:state.nvl.dialogComplete":"event:state.nvl.dialogComplete","event:state.nvl.dialogAppend":"event:state.nvl.dialogAppend","event:state.nvl.visibilityChange":"event:state.nvl.visibilityChange","event:state.nvl.change":"event:state.nvl.change"};var E=le;var ba=32767,bl=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 Mi().addPushValidator(n=>{let i=this.stack.peek();if(n===i)throw new Ve("StackModel: Unexpected self-push in stack.");if(o.isCalledActionResult(i)){if(i.wait&&o.isStackModelsAwaiting(i.wait.type,i.wait.stackModels))throw new Ve("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(S.isAwaitable(i)&&!i.isSettled())throw new Ve("StackModel: Unexpected unsettled Awaitable in stack.");if(!o.isCalledActionResult(n)&&!S.isAwaitable(n))throw new Ve("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%ba===0){let t=Date.now()-this.loopStartTime;if(e-this.loopDebugCheckpoint>=ba&&t<bl){let i=new k(`[NarraLeaf] Potential infinite loop detected!
|
|
43
43
|
Loop has executed ${e} iterations in ${t}ms.
|
|
44
44
|
This is likely a bug in your game script. Check your loop conditions.
|
|
45
|
-
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
|
|
46
|
-
NarraLeaf cannot find the element with the id from the saved game`);
|
|
45
|
+
Loop type: ${this.loopConfig.type}, broken: ${this.loopConfig.broken}`);throw this.liveGame.getGameStateForce().logger.error("StackModel",i.message),i}this.loopDebugCheckpoint=e,this.loopStartTime=Date.now()}}breakLoop(){if(!this.loopConfig)throw new k("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 H(()=>{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 Ve("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(c=>c.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:c}=i;if(c==null)throw new Error(`Missing stackWaitType for link action: ${s}`);this.stack.push({type:r,node:s?t.get(s)?.contentNode??null:null,wait:{type:c,stackModels:a.map(l=>o.createStackModel(this.liveGame,l,t))}})}if(e.loop){let i=e.loop,r=[];for(let a of i.bodyActionIds){let c=t.get(a);if(!c)throw new Error(`Loop body action not found: ${a}`);r.push(c)}let s=null;if(i.type==="condition"&&i.conditionActionId){let a=t.get(i.conditionActionId);if(a){let c=a.contentNode.getContent();Array.isArray(c)&&c.length>=2&&j.isLambda(c[1])&&(s=c[1])}}this.loopConfig={type:i.type,counter:i.counter,limit:i.limit,conditionActionId:i.conditionActionId,bodyActionIds:i.bodyActionIds,broken:i.broken},this.loopBodyActions=r,this.loopCondition=s,this.loopStartTime=Date.now(),this.loopDebugCheckpoint=i.counter}return this}isEmpty(){return this.stack.isEmpty()}push(...e){return this.stack.push(...e),this}};var Me=class Me{constructor(e){this.events=new q;this.story=null;this.gameLock=new xn;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 qn,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new Gt(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:oa,created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:e.hash()},game:{...this.serializeGameState(),history:this.gameState.gameHistory.serialize()}}}serializeGameState(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");let n=this._storable.toData(),i=e.toData(),r=t.getAllElementStates();this.auditElementDirtyMarks(t);let s=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(c=>c.serialize());return{store:n,stage:i,elementStates:r,stackModel:s,asyncStackModels:a,services:t.serializeServices()}}auditElementDirtyMarks(e){if(!this.game.config.app.debug||this.elementAuditCountdown-- >0)return;this.elementAuditCountdown=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:c,asyncStackModels:l}}=e,[u,d]=this.constructMaps();this.initNamespaces(),this._storable.load(i),d.forEach(p=>p.reset()),s.forEach(({id:p,data:h})=>{t.logger.debug("restore element",p);let f=d.get(p);if(!f)throw new Error("Element not found, id: "+p+`
|
|
46
|
+
NarraLeaf cannot find the element with the id from the saved game`);f.fromData(h),f.markDirty()}),this.currentSavedGame=e,t.loadData(r,d),this.stackModel.deserialize(c,u),l.forEach(p=>{let h=Xe.createStackModel(this,p,u);this.asyncStackModels.add(h),t.timelines.attachTimeline(this.executeAsyncStackModel(h))}),n.deserializeServices(a),t.gameHistory.load(e.game.history??[],u),this.game.hooks.trigger("afterRestore",[]),t.events.once(E.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===jt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),!0}undoInPlace(e,t){this.assertGameState();let n=this.gameState.actionHistory;if(!n.has(e.token))return!1;let i=this.gameLock.register().lock();this.stackModel.abortStackTop();let r=n.undoUntil(e.token);if(!r)return this.gameLock.off(i.unlock()),!1;let[s]=this.constructMaps(),{rootStackSnapshot:a,stackModel:c}=r;return r.action.type===jt.say&&this.gameState.isNvlMode()&&this.gameState.suppressNextNvlTyping(),this.stackModel.deserialize(a,s),c===this.stackModel&&this.stackModel.push(Xe.fromAction(r.action)),this.gameLock.off(i.unlock()),this.gameState.logger.debug(t,"Stepped back in place to",e.token),this.gameState.stage.forceUpdate(),this.gameState.stage.next(),this.gameState.schedule(()=>{this.gameState&&this.gameState.forceAnimation()},0),!0}auditRestoredLine(e,t){if(!this.game.config.app.debug||!e.snapshot)return;let n=JSON.stringify([...e.snapshot.elementStates].sort((r,s)=>r.id.localeCompare(s.id))),i=JSON.stringify([...this.serializeGameState().elementStates].sort((r,s)=>r.id.localeCompare(s.id)));n!==i&&this.gameState?.logger.warn(t,`Stepping back in place did not reproduce the state this line's snapshot describes, so an action's undo does not fully reverse it. Restoring the snapshot would have been correct; this path was not.
|
|
47
47
|
expected: ${n}
|
|
48
|
-
actual: ${i}`)}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),i=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),r=S.toPromiseForce(i);return{cancel:()=>{i.abort()},promise:r}}playSound(e){this.assertGameState();let t=e instanceof URL?e.toString():e,n=typeof t=="string"?new ye({src:t}):t;return this.gameState.audioManager.playSoundToken(n)}skipDialog(){this.assertGameState(),this.gameState.events.emit(E.EventTypes["event:state.player.skip"],!0)}async fastForward(e={}){this.assertGameState();let t=this.gameState,n=e.until??"menu",i=typeof n=="object"?n.actionId:null,r=n==="menu"||i!==null,s=e.maxSteps??t.game.config.maxStackModelLoop,a=e.stepTimeout??Ie.FastForwardStepTimeout,c=i!==null?{reachedTarget:!1}:{},l=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let u=0;for(;u++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...c};if(this.stackModel.isEmpty())return{reason:"end",...c};let d=this.stackModel.getWaitingAwaitable();if(d){if(!await Ie.settleSuspendedStep(t,d,a))return{reason:"stalled",...c}}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...c}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(l)}}static settleSuspendedStep(e,t,n){return new Promise(i=>{let r=!1,s=null,a,c=d=>{r||(r=!0,s!==null&&(clearTimeout(s),s=null),a?.cancel?.(),i(d))};if(a=t.onSettled(()=>c(!0)),r){a?.cancel?.();return}let l=Date.now()+n,u=()=>{if(!r&&(e.events.emit(E.EventTypes["event:state.player.skip"],!0),!r)){if(Date.now()>=l){c(!1);return}s=setTimeout(u,Ie.FastForwardSkipInterval)}};u()})}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(Ie.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(Ie.EventTypes["event:menu.choose"],e)}onCurrentActionChange(e){return this.events.on(Ie.EventTypes["event:action.current"],e)}getCurrentActionId(){return this._currentActionId}getStackSnapshot(){return this.stackModel?{root:this.stackModel.snapshot(),async:Array.from(this.asyncStackModels).map(e=>e.snapshot())}:{root:{frames:[]},async:[]}}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let i=this.story?.entryScene?.getSceneRoot();i?this.stackModel.push(Ze.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 Ze(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 Ze(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");this._currentActionId=t.getId(),this.events.hasListeners(Ie.EventTypes["event:action.current"])&&this.events.emit(Ie.EventTypes["event:action.current"],{actionId:t.getId(),actionType:t.type}),t.callee?.markDirty();let i=t.executeAction(e,n);return S.isAwaitable(i)?i:i||null}setGameState(e){if(e&&this.gameState)throw new Fe("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Ze(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),[Rt].some(c=>i?.action&&i.action instanceof c)){i=null;continue}if(i.action&&i.action.is(re,J.jumpTo)){let[c]=i.action.contentNode.getContent(),l=e.getScene(c);if(!l)throw i.action._sceneNotFoundError(i.action.getSceneName(c));if(a.has(l)){i=null;continue}a.add(l),i=l.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(ie,te.do)){let[c]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=c[0]?.contentNode||null}i?.action&&r.push(i.action),i=i?.getChild()||null}return r}clearMainStack(){if(!this.stackModel)throw new 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:Os(),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 P("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 P("Player Element Not Mounted")}};Ie.DefaultNamespaces={game:{}},Ie.GameSpacesKey={game:"game"},Ie.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose","event:action.current":"event:action.current"},Ie.ElementAuditInterval=50,Ie.FastForwardStepTimeout=1e4,Ie.FastForwardSkipInterval=16;var Mt=Ie;var ii=class ii{constructor(e){this.events=new Y;this.settings={...e},this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(ii.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(ii.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))}};ii.EventTypes={"event:game.preference.change":"event:game.preference.change"};var oi=ii;import"client-only";import nc,{useEffect as lp,useRef as $r}from"react";import"client-only";import fa,{useContext as ha,useState as hl}from"react";var pr=fa.createContext(null);function ga({children:o,game:e}){"use client";let t=new oe({}),[n]=hl(e||t);return fa.createElement(pr,{value:n},o)}function L(){let o=ha(pr);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function ya(){return ha(pr)}import gl,{createContext as yl,useContext as va}from"react";var Sa="/",so=class so{constructor(e,t=so.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,c]=s.split("=");a&&(i[decodeURIComponent(a)]=c?decodeURIComponent(c):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let c=a.slice(1);n[c]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new P(`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 P(`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(),at(()=>{t()}))})}else at(()=>{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)}};so.rootPath=Sa;var cn=so,dr=yl(null);function Ta({children:o}){let e=L();return gl.createElement(dr,{value:{router:e.router}},o)}function Ft(){if(!va(dr))throw new Error("useRouter must be used within a RouterProvider");return va(dr).router}import Aa from"react";import Cl from"clsx";import vl,{createContext as Sl,useContext as Tl,useLayoutEffect as bl,useReducer as Al,useState as xl}from"react";var Yt=class Yt{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(Yt.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(Yt.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(Yt.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(Yt.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(Yt.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(Yt.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};Yt.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 mr=Yt,fr=Sl(null);function ba({children:o}){"use client";let[e]=xl(()=>new mr);return vl.createElement(fr,{value:{ratio:e}},o)}function he(){let o=Tl(fr),[,e]=Al(n=>n+1,0);if(!fr||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return bl(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function Vt({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=he(),s=r.getStyle();return Aa.createElement("div",{className:Cl("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},Aa.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import wl,{useEffect as kl}from"react";function ln(o){let e=L(),[t,n]=wl.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return kl(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import hr from"react";import ao from"react";import xa from"clsx";function co({children:o,className:e,style:t,...n}){let{ratio:i}=he(),r=L();return ao.createElement(Vt,{className:xa("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},ao.createElement("div",{className:"absolute inset-0 w-full h-full"},ao.createElement("div",{className:"inset-0 w-full h-full"},ao.createElement("div",{className:xa("pointer-events-auto-rest",e),style:t},o))))}function Pl({children:o,className:e,style:t}){return hr.createElement(hr.Fragment,null,hr.createElement(co,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import Ca from"clsx";import wa from"react";function lo({className:o,children:e,...t}){let{ratio:n}=he();return wa.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:Ca("w-full h-full")},wa.createElement("div",{className:Ca("z-20",o),...t},e))}import vt,{useState as ka}from"react";import{motion as El}from"motion/react";function uo({children:o,border:e="solid",color:t="red",tag:n,borderWidth:i=1,as:r="div",ref:s,...a}){let c=L(),[l,u]=ka(!1);if(!c.config.app.inspector)return vt.createElement(r,{...a,ref:s},o);let d={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return vt.createElement(r,{...d,ref:s},n&&l&&vt.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function Dl({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=L(),[a,c]=ka(!1);if(!s.config.app.inspector)return vt.createElement(i,{...r});let l={...r,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return vt.createElement("div",null,vt.createElement(i,{...l}),t&&a&&vt.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function Ll(o){return vt.createElement(uo,{...o,as:"div"})}function Rl(o){return vt.createElement(uo,{...o,as:"span"})}function Il(o){return vt.createElement(Dl,{...o,as:"img"})}function Ml(o){return vt.createElement(uo,{...o,as:"button"})}function Nl(o){return vt.createElement(uo,{...o,as:El.div,ref:o.ref,layout:o.layout})}var Gl={Div:Ll,Span:Rl,Button:Ml,Img:Il,mDiv:Nl},Ot=Gl;import yo from"clsx";import Ve,{useEffect as Sn,useRef as Ia,useState as xr}from"react";import{useEffect as Hl,useState as Fl}from"react";function se(o){let[e,t]=Fl(0);Hl(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import Pa from"react";var yn=Pa.createContext(null);function Ct(){let o=Pa.useContext(yn);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}import po,{useCallback as Vl,useLayoutEffect as ri,useMemo as Ea,useRef as Da}from"react";import{useIsPresent as Ol}from"motion/react";var wt=class wt{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 ki,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(wt.Events.complete):this.safeEmit(wt.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(wt.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(wt.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(oe.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit(wt.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(wt.Events.onFlush),this}onFlush(e){return this.events.on(wt.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(oe.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(oe.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit(wt.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(oe.Preferences.gameSpeed))}getPlayingVoiceToken(){let e=this.config.action.sentence;if(!e)return null;try{let t=it.getVoice(this.config.gameState,e);if(!t)return null;let n=this.config.gameState.audioManager.getToken(t);return n&&n.isPlaying()?n:null}catch{return null}}releaseVoiceWait(){let e=this.voiceWaitDisposer;this.voiceWaitDisposer=null,e?.()}};wt.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Me=wt;function si({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=Ol(),s=i&&r,a=Da(!1),c=Da(o),l=c.current!==o,u=Ea(()=>o.sentence?.evaluate(Ce.getCtx({gameState:n})),[o.sentence,n]),d=Ea(()=>new Me({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:l}),[o,n,t,u]),p=n.game.config.dialog,h=Vl(g=>{!s||a.current||(a.current=!0,e?.(g))},[s,e]);return ri(()=>{a.current=!1},[d]),ri(()=>{c.current=o},[o]),ri(()=>(d.setActive(s),()=>{d.setActive(!1)}),[d,s]),ri(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",d),d.events.on(Me.Events.complete,g=>{n.logger.log("NarraLeaf-React: Say","Complete",d.isIdle()),s&&(d.isIdle()||g?h(!1):d.setIdle(!0))}).cancel),[d,h,n,s]),ri(()=>{let g=A=>{s&&(A?(d.setIdle(!0),d.forceSkip()):d.isIdle()?h(!0):d.forceSkip())},m=n.events.on(E.EventTypes["event:state.player.skip"],g),y=n.events.on(E.EventTypes["event:state.player.stageClick"],()=>g(!1));return()=>{m.cancel(),y.cancel()}},[d,h,n,s]),po.createElement(po.Fragment,null,po.createElement(yn,{value:d},po.createElement(p,null)))}import{useEffect as mo,useState as Bl}from"react";import{useEffect as Ul,useState as Wl}from"react";function vn(o){let e=L(),[t,n]=Wl(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return Ul(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var Gn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Gn||{});function fo({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=L(),[s]=vn("nextAction"),[a]=Bl(()=>{let c=o.firedTextEvents??(o.firedTextEvents=new Set);return new Me({useTypeEffect:i,action:{sentence:o.sentence,character:o.character,words:t,id:o.id},evaluatedWords:t,gameState:e,firedTextEvents:c})});return mo(()=>{if(!n)return;let c=()=>{e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()},l=()=>{e.requestNvlSkip(o.id)==="typing"&&a.forceSkip()},u=e.events.on(E.EventTypes["event:state.player.stageClick"],c),d=e.events.on(E.EventTypes["event:state.player.skip"],l);return()=>{u.cancel(),d.cancel()}},[a,o.id,e,n]),mo(()=>{if(!n)return;let c=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",c);return()=>{u.cancel()}}let l=r.getLiveGame().onPlayerEvent("keydown",c);return()=>{l.cancel()}},[a,o.id,r,e,n,s]),mo(()=>{let c=a.events.on(Me.Events.complete,l=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!l&&a.setIdle(!0))});return()=>{c.cancel()}},[a,o.id,e,n]),mo(()=>{let c=a.events.on(Me.Events.simulateClick,()=>{if(!n)return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()});return()=>{c.cancel()}},[a,n]),a}function Kl(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&&(R.isLayeredSrc(i)?s.flush():s.updateStyleSync())}n&&e.audioManager.play(n,{end:n.state.volume,duration:0})}function ho(o,e,t){e.has(o)||(e.add(o),Kl(o,t))}function La(o,e,t){let n=[];for(let i of o)if(i.isTextEvent()){let r=i.text;e.has(r)||n.push(r),ho(r,e,t)}return n}var Hn=new Map,gr=new Set;function zl(o,e){return Hn.set(o,e),gr.delete(o),()=>{Hn.get(o)===e&&Hn.delete(o)}}function $l(o){Hn.delete(o)}function jl(o){return Hn.get(o)??null}function yr(o){if(!o)return null;if(typeof o!="string")return o;let e=Hn.get(o);return e||(gr.has(o)||(gr.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 vr from"react";var ql=2;function go(o){return o==="vertical-rl"||o==="vertical-lr"}function Yl(o){return o===!1?0:typeof o=="number"?Number.isFinite(o)?Math.max(0,Math.round(o)):0:ql}function Tr(o,e){return go(o)?{writingMode:o,textOrientation:e??"mixed"}:o?{writingMode:o}:{}}var Sr=/[0-9A-Za-z]+(?:[.:\-/][0-9A-Za-z]+)*/g;function Ql(o,e){if(e<=0)return[{text:o,combineUpright:!1}];let t=[],n=0;Sr.lastIndex=0;for(let i=Sr.exec(o);i;i=Sr.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 br(){return{wordBreak:"normal",lineBreak:"strict",overflowWrap:"break-word"}}function Ar(o,e,t){if(!e)return o;let n=Yl(t);if(n<=0)return o;let i=Ql(o,n);return i.some(r=>r.combineUpright)?i.map((r,s)=>r.combineUpright?vr.createElement("span",{key:s,style:{textCombineUpright:"all"}},r.text):vr.createElement(vr.Fragment,{key:s},r.text)):o}function*wr(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if($e.isPause(n.text)){yield $e.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
|
+
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(E.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,c=i!==null?{reachedTarget:!1}:{},l=t.audioManager.getGlobalVolume();t.audioManager.setGlobalVolume(0),t.setFastForwarding(!0);try{let u=0;for(;u++<s;){if(i!==null&&this.stackModel.peekExecutingActionId()===i)return{reason:"action",reachedTarget:!0};if(r&&t.hasActiveMenu())return{reason:"menu",...c};if(this.stackModel.isEmpty())return{reason:"end",...c};let d=this.stackModel.getWaitingAwaitable();if(d){if(!await Me.settleSuspendedStep(t,d,a))return{reason:"stalled",...c}}else t.stage.next(),await Promise.resolve()}return{reason:"maxSteps",...c}}finally{t.setFastForwarding(!1),t.audioManager.setGlobalVolume(l)}}static settleSuspendedStep(e,t,n){return new Promise(i=>{let r=!1,s=null,a,c=d=>{r||(r=!0,s!==null&&(clearTimeout(s),s=null),a?.cancel?.(),i(d))};if(a=t.onSettled(()=>c(!0)),r){a?.cancel?.();return}let l=Date.now()+n,u=()=>{if(!r&&(e.events.emit(E.EventTypes["event:state.player.skip"],!0),!r)){if(Date.now()>=l){c(!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 Ve("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 Ve("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(c=>i?.action&&i.action instanceof c)){i=null;continue}if(i.action&&i.action.is(se,X.jumpTo)){let[c]=i.action.contentNode.getContent(),l=e.getScene(c);if(!l)throw i.action._sceneNotFoundError(i.action.getSceneName(c));if(a.has(l)){i=null;continue}a.add(l),i=l.getSceneRoot()?.contentNode||null;continue}else if(i.action&&i.action.is(oe,ne.do)){let[c]=i.action.contentNode.getContent();i.getChild()?.action&&s.push(i.getChild().action),i=c[0]?.contentNode||null}i?.action&&r.push(i.action),i=i?.getChild()||null}return r}clearMainStack(){if(!this.stackModel)throw new Ve("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new Ve("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 k("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 k("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 si=class si{constructor(e){this.events=new q;this.settings={...e},this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(si.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(si.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))}};si.EventTypes={"event:game.preference.change":"event:game.preference.change"};var ai=si;import"client-only";import uc,{useEffect as gp,useRef as Qr}from"react";import"client-only";import Aa,{useContext as Ca,useState as Al}from"react";var hr=Aa.createContext(null);function xa({children:o,game:e}){"use client";let t=new re({}),[n]=Al(e||t);return Aa.createElement(hr,{value:n},o)}function R(){let o=Ca(hr);if(!o)throw new Error("useGame must be used within a GameProvider");return o}function wa(){return Ca(hr)}import Cl,{createContext as xl,useContext as ka}from"react";var Pa="/",uo=class uo{constructor(e,t=uo.rootPath){this.events=new q;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:i}=this.parseUrl(t);this.currentPath=n,this.currentQuery=i,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),i={};if(n){let r=n.split("&");for(let s of r){let[a,c]=s.split("=");a&&(i[decodeURIComponent(a)]=c?decodeURIComponent(c):"")}}return{path:t||"/",query:i}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([i,r])=>`${encodeURIComponent(i)}=${encodeURIComponent(r)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};if(this.currentPath===r)return this.currentQuery=s,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(r,s)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(r,s);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=r,this.currentQuery=s,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:i}=this.parseUrl(e),r=this.resolvePath(n),s={...i,...t};return this.currentPath=r,this.currentQuery=s,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(r,s):(this.history.push(this.buildUrl(r,s)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length<i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),i=this.parsePath(t);if(n.length!==i.length)return!1;for(let r=0;r<i.length;r++){let s=n[r],a=i[r];if(a!=="*"){if(a.startsWith(":"))continue;if(s!==a)return!1}}return!0}extractParams(e,t){let n={},i=this.parsePath(e),r=this.parsePath(t);if(i.length!==r.length)return n;for(let s=0;s<r.length;s++){let a=r[s];if(a.startsWith(":")){let c=a.slice(1);n[c]=i[s]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new k(`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 k(`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(),rt(()=>{t()}))})}else rt(()=>{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=Pa;var ln=uo,gr=xl(null);function Ea({children:o}){let e=R();return Cl.createElement(gr,{value:{router:e.router}},o)}function Ot(){if(!ka(gr))throw new Error("useRouter must be used within a RouterProvider");return ka(gr).router}import La from"react";import Rl from"clsx";import wl,{createContext as kl,useContext as Pl,useLayoutEffect as El,useReducer as Dl,useState as Ll}from"react";var Qt=class Qt{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new q().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(Qt.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(Qt.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(Qt.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(Qt.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(Qt.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(Qt.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};Qt.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 yr=Qt,vr=kl(null);function Da({children:o}){"use client";let[e]=Ll(()=>new yr);return wl.createElement(vr,{value:{ratio:e}},o)}function me(){let o=Pl(vr),[,e]=Dl(n=>n+1,0);if(!vr||!o)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=o;return El(()=>(e(),t.onUpdate(()=>{e()})),[t]),o}function Ut({children:o,className:e,style:t,ref:n,...i}){let{ratio:r}=me(),s=r.getStyle();return La.createElement("div",{className:Rl("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${r.state.minWidth}px`,minHeight:`${r.state.minHeight}px`},...i},La.createElement("div",{style:{...s,position:"relative",...t||{}},...i||{},ref:n},o))}import Il,{useEffect as Ml}from"react";function un(o){let e=R(),[t,n]=Il.useState(e.preference.getPreference(o)),i=r=>{e.preference.setPreference(o,r),n(r)};return Ml(()=>e.preference.onPreferenceChange(o,n).cancel,[o,e.preference,n]),[t,i]}import Sr from"react";import po from"react";import Ra from"clsx";function mo({children:o,className:e,style:t,...n}){let{ratio:i}=me(),r=R();return po.createElement(Ut,{className:Ra("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:Ra("pointer-events-auto-rest",e),style:t},o))))}function Nl({children:o,className:e,style:t}){return Sr.createElement(Sr.Fragment,null,Sr.createElement(mo,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},o))}import Ia from"clsx";import Ma from"react";function fo({className:o,children:e,...t}){let{ratio:n}=me();return Ma.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:Ia("w-full h-full")},Ma.createElement("div",{className:Ia("z-20",o),...t},e))}import Tt,{useState as Na}from"react";import{motion as Gl}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 c=R(),[l,u]=Na(!1);if(!c.config.app.inspector)return Tt.createElement(r,{...a,ref:s},o);let d={...a,onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),style:{...a.style||{},outline:`${i}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return Tt.createElement(r,{...d,ref:s},n&&l&&Tt.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),o)}function Hl({border:o="solid",color:e="red",tag:t,borderWidth:n=1,as:i="img",...r}){let s=R(),[a,c]=Na(!1);if(!s.config.app.inspector)return Tt.createElement(i,{...r});let l={...r,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...r.style||{},outline:`${o} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return Tt.createElement("div",null,Tt.createElement(i,{...l}),t&&a&&Tt.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function Fl(o){return Tt.createElement(ho,{...o,as:"div"})}function Vl(o){return Tt.createElement(ho,{...o,as:"span"})}function Ol(o){return Tt.createElement(Hl,{...o,as:"img"})}function Ul(o){return Tt.createElement(ho,{...o,as:"button"})}function Wl(o){return Tt.createElement(ho,{...o,as:Gl.div,ref:o.ref,layout:o.layout})}var Bl={Div:Fl,Span:Vl,Button:Ul,Img:Ol,mDiv:Wl},Wt=Bl;import bo from"clsx";import Oe,{useEffect as bn,useRef as Ua,useState as Pr}from"react";import{useEffect as Kl,useState as zl}from"react";function ae(o){let[e,t]=zl(0);Kl(()=>{n()},o??[]);function n(){t(i=>i+1)}return[n,e]}import Ga from"react";var Sn=Ga.createContext(null);function Pt(){let o=Ga.useContext(Sn);if(!o)throw new Error("useDialogContext must be used within a DialogContext");return o}import go,{useCallback as $l,useLayoutEffect as ci,useMemo as Ha,useRef as Fa}from"react";import{useIsPresent as jl}from"motion/react";var Et=class Et{constructor(e){this.events=new q;this._forceSkipped=!1;this._idle=!1;this._active=!0;this.voiceWaitDisposer=null;this.config=e,this._state="pending",this.autoForwardScheduler=new Di,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(Et.Events.complete):this.safeEmit(Et.Events.requestComplete))}forceSkip(){this._active&&(this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Et.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(Et.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(Et.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(Et.Events.onFlush),this}onFlush(e){return this.events.on(Et.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(Et.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=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?.()}};Et.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var Ne=Et;function li({action:o,onFinished:e,useTypeEffect:t=!0,gameState:n,active:i=!0}){let r=jl(),s=i&&r,a=Fa(!1),c=Fa(o),l=c.current!==o,u=Ha(()=>o.sentence?.evaluate(Ce.getCtx({gameState:n})),[o.sentence,n]),d=Ha(()=>new Ne({useTypeEffect:t,action:o,evaluatedWords:u||[],gameState:n,suppressInitialAnimation:l}),[o,n,t,u]),p=n.game.config.dialog,h=$l(f=>{!s||a.current||(a.current=!0,e?.(f))},[s,e]);return ci(()=>{a.current=!1},[d]),ci(()=>{c.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,f=>{n.logger.log("NarraLeaf-React: Say","Complete",d.isIdle()),s&&(d.isIdle()||f?h(!1):d.setIdle(!0))}).cancel),[d,h,n,s]),ci(()=>{let f=b=>{s&&(b?(d.setIdle(!0),d.forceSkip()):d.isIdle()?h(!0):d.forceSkip())},m=n.events.on(E.EventTypes["event:state.player.skip"],f),y=n.events.on(E.EventTypes["event:state.player.stageClick"],()=>f(!1));return()=>{m.cancel(),y.cancel()}},[d,h,n,s]),go.createElement(go.Fragment,null,go.createElement(Sn,{value:d},go.createElement(p,null)))}import{useEffect as yo,useState as Ql}from"react";import{useEffect as ql,useState as Yl}from"react";function Tn(o){let e=R(),[t,n]=Yl(e.keyMap.getKeyBinding(o)),i=r=>{e.keyMap.setKeyBinding(o,r),n(r)};return ql(()=>e.keyMap.onKeyBindingChange(o,n).cancel,[o,e.keyMap,n]),[t,i]}var Fn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Fn||{});function vo({entry:o,gameState:e,words:t,isActive:n,useTypeEffect:i}){let r=R(),[s]=Tn("nextAction"),[a]=Ql(()=>{let c=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:c})});return yo(()=>{if(!n)return;let c=()=>{e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()},l=()=>{e.requestNvlSkip(o.id)==="typing"&&a.forceSkip()},u=e.events.on(E.EventTypes["event:state.player.stageClick"],c),d=e.events.on(E.EventTypes["event:state.player.skip"],l);return()=>{u.cancel(),d.cancel()}},[a,o.id,e,n]),yo(()=>{if(!n)return;let c=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",c);return()=>{u.cancel()}}let l=r.getLiveGame().onPlayerEvent("keydown",c);return()=>{l.cancel()}},[a,o.id,r,e,n,s]),yo(()=>{let c=a.events.on(Ne.Events.complete,l=>{n&&(e.completeNvlTyping(o.id),!a.isIdle()&&!l&&a.setIdle(!0))});return()=>{c.cancel()}},[a,o.id,e,n]),yo(()=>{let c=a.events.on(Ne.Events.simulateClick,()=>{if(!n)return;e.requestNvlAdvance(o.id)==="typing"&&a.requestComplete()});return()=>{c.cancel()}},[a,n]),a}function Xl(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),Xl(o,t))}function Va(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 Vn=new Map,Tr=new Set;function Jl(o,e){return Vn.set(o,e),Tr.delete(o),()=>{Vn.get(o)===e&&Vn.delete(o)}}function Zl(o){Vn.delete(o)}function _l(o){return Vn.get(o)??null}function br(o){if(!o)return null;if(typeof o!="string")return o;let e=Vn.get(o);return e||(Tr.has(o)||(Tr.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 Ar 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 xr(o,e){return To(o)?{writingMode:o,textOrientation:e??"mixed"}:o?{writingMode:o}:{}}var Cr=/[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;Cr.lastIndex=0;for(let i=Cr.exec(o);i;i=Cr.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 wr(){return{wordBreak:"normal",lineBreak:"strict",overflowWrap:"break-word"}}function kr(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?Ar.createElement("span",{key:s,style:{textCombineUpright:"all"}},r.text):Ar.createElement(Ar.Fragment,{key:s},r.text)):o}function*Dr(o){let e=[...o];for(let t=0;t<e.length;t++){let n=e[t];if($e.isPause(n.text)){yield $e.from(n.text);continue}if(at.isTextEvent(n.text)){yield n.text;continue}for(let i=0;i<n.text.length;i++){let r=n.text[i];r===`
|
|
49
49
|
`?yield`
|
|
50
|
-
`:yield{text:r,full:n.text,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function
|
|
50
|
+
`:yield{text:r,full:n.text,config:n.config,tag:t,tag2:i,cps:n.config.cps}}}}function Er(o){let e=Dr(o),t=[];for(let n of e)$e.isPause(n)||at.isTextEvent(n)||t.push(n);return t}function Wa(o,e){o(t=>{let n=t[t.length-1];return n&&n!==`
|
|
51
51
|
`&&e!==`
|
|
52
|
-
`&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function
|
|
53
|
-
`?y(
|
|
54
|
-
`&&
|
|
55
|
-
`)return
|
|
56
|
-
`?await
|
|
57
|
-
`)return Ve.createElement("br",{key:I});let ae=be(B);return Ve.createElement("span",{key:I,style:{...ae,...br()},className:yo("inline-block",B.config.className)},Ve.createElement(Ga,{word:B,vertical:Ae,tateChuYoko:f,done:!1,style:ae,renderer:yr(B.config.render)}))};return Ve.createElement("div",{...x,className:yo("whitespace-pre-wrap",u),style:{...Qe,...Tr(y,A),...d}},V.map(rt))}function Ha(o){return Ve.createElement(kr,{...o,key:o.dialog?.config.action.id})}function eu({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=fo({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Ve.createElement(kr,{...r,dialog:s,key:s.config.action.id})}function tu(o){let e=Ct();return Ve.createElement(kr,{...o,dialog:e,key:e.config.action.id})}function un(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Ve.createElement(eu,{...o}):Ve.createElement(tu,{...o})}var nu=un;import To,{useEffect as iu,useLayoutEffect as ou,useMemo as Va,useRef as ru,useState as su}from"react";import So from"react";var Pr=So.createContext(null);function Er(){let o=So.useContext(Pr);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var Dr=So.createContext(null);function Fa(){let o=So.useContext(Dr);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function bo({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let c=ru(null),{register:l,unregister:u,getIndex:d}=Fa(),[p,h]=su(-1),{choose:g,evaluated:m,gameState:y}=Er(),A=p===-1?null:m[p],f=Va(()=>Ce.getCtx({gameState:y}),[y]),{hidden:v,disabled:x}=Va(()=>{if(!A)return{hidden:!1,disabled:!1};let k=A.config.hidden?.evaluate(f)?.value??!1,D=!k&&(A.config.disabled?.evaluate(f)?.value??!1);return{hidden:k,disabled:D}},[A,f]);ou(()=>{if(!c.current)return;let k=c;l(k);let D=d(k);return h(D),c.current.dataset.index=D.toString(),()=>u(k)},[l,u,d]),iu(()=>{if(!t)return;let k=D=>{D.key.toLowerCase()===t.toLowerCase()&&!D.ctrlKey&&!D.metaKey&&(D.preventDefault(),D.stopPropagation(),T())};return window.addEventListener("keydown",k,!0),()=>{window.removeEventListener("keydown",k,!0)}},[t]);function T(){if(p===-1||!m[p]||v||x)return;let k=m[p];g({...k,evaluated:Z.getText(k.words||[])})}let b=A&&!v;return To.createElement(To.Fragment,null,To.createElement("button",{className:o,style:{...e,display:b?e?.display??void 0:"none"},onClick:T,ref:c,disabled:x},b&&To.createElement(Ha,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Me({useTypeEffect:!1,action:{sentence:A.prompt,words:A.words,character:null},gameState:y,evaluatedWords:A.words})})))}import Ao from"react";import{AnimatePresence as au}from"motion/react";function xo({children:o,...e}){let t=au;return Ao.createElement(Ao.Fragment,null,Ao.createElement("div",{...e},Ao.createElement(t,null,o)))}import Oa from"react";function Qt({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=Oa.useContext(yn),c=e??o?.character??a?.config.action.character??null,l=n??c?.config.color,u=i??t??c?.state.name;return Oa.createElement("div",{...s,style:{color:l?Cn(l):void 0,...r}},u)}import uu from"clsx";import pu from"react";import Lr,{createContext as cu,useContext as lu,useState as Ua}from"react";var Tn=class Tn{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(Tn.EventTypes["event:preloaded.add"],e),this.events.emit(Tn.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(Tn.EventTypes["event:preloaded.remove"],e),this.events.emit(Tn.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return De.getSrc(e)}};Tn.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 qe=Tn;var Co=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 Gs(e,{...n,signal:t})}static async decodeImage(e){if(typeof window>"u"||typeof window.Image>"u")return null;let t=new window.Image;if(t.src=e,typeof t.decode!="function")return null;try{await t.decode()}catch{return null}return t}has(e){return this.src.has(e)}add(e,t){return this.src.set(e,t),this}remove(e){return this.src.delete(e),this.decoded.delete(e),this}get(e){return this.src.get(e)}isDecoded(e){return this.decoded.has(e)}clear(){return this.src.clear(),this.decoded.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t,n){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let i=t,r={};this.game.hooks.rawTrigger("preloadImage",()=>[i,(p,h)=>{i=p,r={...r,...h}}]);let s=new AbortController,a=s.signal,c=[],u={promise:o.getImage(i,a,r).then(async p=>{if(this.preloadTasks.delete(t),p){this.add(t,p);let h=await o.decodeImage(p);h&&n?.retainDecoded&&this.src.get(t)===p&&this.decoded.set(t,h)}}).catch(p=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),c.forEach(h=>h(p))}),controller:s};this.preloadTasks.set(t,u);let d={abort:()=>{s.abort(),this.preloadTasks.delete(t)},onFinished:p=>(u.promise.then(p),d),onErrored:p=>(c.push(p),d)};return d}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){let t=new Set(e);for(let n of this.src.keys())t.has(n)||(this.src.delete(n),this.decoded.delete(n));for(let n of this.decoded.keys())t.has(n)||this.decoded.delete(n);return this}};var Rr=cu(null);function Wa({children:o}){let e=L(),[t]=Ua(()=>new qe),[n]=Ua(()=>new Co(e));return Lr.createElement(Lr.Fragment,null,Lr.createElement(Rr,{value:{preloaded:t,cacheManager:n}},o))}function Ut(){if(!Rr)throw new Error("usePreloaded must be used within a PreloadedProvider");return lu(Rr)}function Ba(){let o=Ct(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return fu(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?R.getSrcURL(s):null,c=s&&R.isTagSrc(s)?[...s.state.currentSrc]:null,l=ia({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=mu(l.source);return{visible:!!u,src:u,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function du({className:o,style:e,alt:t,...n}){let i=Ba(),{cacheManager:r}=Ut();if(!i.visible||!i.src)return null;let s=r.get(i.src)||i.src;return pu.createElement("img",{...n,"data-element-type":"dialog-avatar",className:uu("dialog-avatar",o),src:s,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function mu(o){return o?w.srcToURL(o):null}function fu(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var Ir=du;import{useEffect as hu}from"react";function gu(){let o=Ct(),[e]=se(o.deps),t=Z.getText(o.config.evaluatedWords);return hu(()=>o.events.on(Me.Events.onFlush,()=>{e()}).cancel,[o]),{done:o.isEnded(),text:t,isNarrator:o.config.action.character===null||o.config.action.character.state.name==="",metadata:o.config.action.sentence?.getMetadata()}}import{useCallback as wo,useEffect as Mr,useMemo as yu,useRef as vu,useState as Ka}from"react";function Su(){let o=Ct(),[e]=se(o.deps),[t,n]=Ka(!0),[i,r]=Ka(!0),s=vu(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;Mr(()=>o.events.on(Me.Events.onFlush,()=>{e()}).cancel,[o]);let u=yu(()=>{if(!c)return null;try{return it.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);Mr(()=>{s.current=null,r(!0)},[c]),Mr(()=>{let m=!1,y=null,A=null,f=null;if(!u){n(!0);return}n(!1);let v=()=>{m||n(!0)};y=a.audioManager.getToken(u),y&&(y.isPlaying()||n(!0),A=()=>v(),f=()=>v(),y.once("ended",A),y.once("stop",f));let x=a.events.on(E.EventTypes["event:state.player.lineEnd"],()=>{v()});return()=>{m=!0,x.cancel(),y&&A&&y.off("ended",A),y&&f&&y.off("stop",f)}},[a,u]);let d=wo(async m=>{let y=m??u;if(!y)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let A=y instanceof URL?ye.voice(y.toString()):typeof y=="string"?ye.voice(y):y,f=await a.getLiveGame().playSound(A);s.current=f;let v=()=>{r(!0)};return f.once("ended",v),f.once("stop",v),f},[a,u]),p=wo(()=>u,[u]),h=wo(()=>l,[l]),g=wo(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:d,getVoice:p,getVoiceId:h,getVoiceSrc:g}}import Nr,{createContext as Ru,useContext as Iu,useEffect as ja,useRef as Mu}from"react";import{useState as Tu}from"react";function ko(o){let[e]=Tu(o);return e}import{AnimatePresence as bu}from"motion/react";var Po=bu;import ui,{createContext as ku,useContext as Pu,useEffect as Eu,useRef as Du}from"react";import{useEffect as ai,useLayoutEffect as Au}from"react";function xu(){let o=Ft(),[e]=se();return ai(()=>o.onChange(e).cancel,[]),o.getPathname()}function Cu(){let{router:o,path:e}=li(),[t]=se();return ai(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function wu(){let o=Ft(),[e]=se();return ai(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Eo(o,e){let t=Ft();Au(()=>t.onUpdate(()=>o(t)).cancel,e),ai(()=>{o(t)},[])}function ci(){let o=Ft(),[e]=se();return ai(()=>o.onChange(e).cancel,[]),e}var za=ku(null);function pi({children:o,path:e,consumedBy:t}){let i={router:Ft(),path:e,consumedBy:t};return ui.createElement(za,{value:i},o)}function li(){let o=Pu(za);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new P(`Invalid useLayout call: Trying to access layout without a parent.
|
|
58
|
-
This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function Lu({children:o,name:e,propagate:t}){let n=L(),[i]=se(),{path:r,router:s,consumedBy:a}=li(),c=s.joinPath(r,e),l=ko(()=>s.createToken(c+"@layout")),u=s.getCurrentPath(),d=Du(!1),p=g=>{d.current=g,i()},h=s.matchPath(u,c);if(ci(),Eo(g=>{let m=g.matchPath(g.getCurrentPath(),c);if(d.current&&!m){if(!o){p(!1);return}g.registerUnmountingPath(l)}m&&g.isPathsUnmounting()&&g.unregisterUnmountingPath(l),m&&!d.current&&!g.isTransitioning()&&p(!0)},[h,o]),Eu(()=>{if(!h)return;let g=s.mount(c);return()=>{g.cancel()}},[c,s,h]),a)throw new P("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return ui.createElement(pi,{path:c},ui.createElement(Po,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),p(!1)}},h&&d.current&&o))}function $a({children:o}){return ci(),ui.createElement(pi,{path:cn.rootPath},ui.createElement(co,{"data-layout-path":cn.rootPath,key:cn.rootPath},o))}var Gr=Ru(null);function Nu(){return Iu(Gr)}function Gu({children:o,name:e}){let[t]=se(),{path:n,router:i,consumedBy:r}=li(),s=Nu(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,u=ko(()=>i.createToken(l+"@page")),d=i.getCurrentPath(),p=!a,h=Mu(!1),g=f=>{h.current=f,t()},m=p&&i.exactMatch(d,n)||i.exactMatch(d,l);if(r&&r!==c)throw new P("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");ci(),Eo(f=>{let v=p&&f.exactMatch(f.getCurrentPath(),n)||f.exactMatch(f.getCurrentPath(),l);if(h.current&&!v){if(!o){g(!1);return}f.registerUnmountingPath(u)}v&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(u),v&&!h.current&&!f.isTransitioning()&&g(!0)},[m,o]),ja(()=>{if(!m)return;let f=p?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{f.cancel()}},[l,m]),ja(()=>()=>{i.unregisterUnmountingPath(u),g(!1)},[]);let y=Nr.createElement(pi,{path:n,consumedBy:c},Nr.createElement(Po,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),g(!1)}},m&&h.current&&o));return(f=>s?Nr.createElement(Gr,{value:{name:null}},f):f)(y)}import Hr,{useCallback as Hu,useEffect as Fr,useImperativeHandle as Fu,useMemo as qa,useRef as Vr,useState as Vu}from"react";var Ou=50,Uu={position:"relative",width:"100%",height:"100%",overflow:"hidden"},Ya={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function Wu(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function Qa(o,e){return e==null?o:Math.max(o,e)}function Bu(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 Xa=Hr.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:u,children:d},p){let h=Vr(null),[g,m]=Vu({...Ya,width:"0px",height:"0px"}),y=Vr(u),A=Vr(null);Fr(()=>{y.current=u},[u]);let f=Hu(()=>{let T=h.current;if(!T)return;let b=T.clientWidth,k=T.clientHeight;if(b<=0||k<=0||e<=0)return;let D=Bu(b,k,e),W=Qa(D.width,n),ue=Qa(D.height,i),F=A.current;(!F||F.width!==W||F.height!==ue)&&(A.current={width:W,height:ue},m({...Ya,width:`${W}px`,height:`${ue}px`}));let Te=t>0?W/t:1;y.current?.({width:W,height:ue,scale:Te,containerWidth:b,containerHeight:k})},[e,t,n,i]),v=qa(()=>Ms(f,typeof r=="number"?r:Ou),[f,r]);Fr(()=>{f()},[f]),Fr(()=>{let T=new ResizeObserver(()=>{v()});h.current&&T.observe(h.current);let b=()=>{v()};return window.addEventListener("resize",b),()=>{T.disconnect(),window.removeEventListener("resize",b)}},[v]),Fu(p,()=>({requestUpdate:f}),[f]);let x=qa(()=>Wu(l),[l]);return Hr.createElement("div",{id:c,ref:h,style:Uu,...x},Hr.createElement("div",{className:s,style:{...g,...a}},d))}),Ja=Xa;function Ku(){return L().getLiveGame()}import Wr from"react";import zu,{createContext as $u,useContext as ju,useEffect as qu,useState as Za}from"react";var Yu={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},_a=$u({state:Yu,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function Wt(){return ju(_a)}function Or(){let{dialogs:o}=Wt();return o}function Qu(){let{isActive:o}=Wt();return o}function Xu(){let{isVisible:o}=Wt();return o}function Ur({children:o}){let t=L().getLiveGame().getGameState(),[n,i]=Za(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=Za(null);qu(()=>{let c=g=>({...g,dialogs:[...g.dialogs]}),l=t.events.on(E.EventTypes["event:state.nvl.enter"],(g,m)=>{i(c(t.getNvlState())),s(m?.showTransition||null)}),u=t.events.on(E.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState()))}),d=t.events.on(E.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),p=t.events.on(E.EventTypes["event:state.nvl.visibilityChange"],(g,m)=>{i(c(t.getNvlState())),s(m||null)}),h=t.events.on(E.EventTypes["event:state.nvl.change"],g=>{i(c(g))});return()=>{l.cancel(),u.cancel(),d.cancel(),p.cancel(),h.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return zu.createElement(_a.Provider,{value:a},o)}import{AnimatePresence as Ju,motion as Zu}from"motion/react";import _u from"clsx";function Br({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=Wt(),{ratio:r}=he(),s=L(),a=i?.duration?i.duration/1e3:.3;return Wr.createElement(Ju,null,n&&Wr.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},Wr.createElement(Zu.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:_u("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 bn from"react";function Kr({renderDialogItem:o,dialogs:e}){return bn.createElement(Br,{className:"bg-black/80 text-white p-16 inset-8"},bn.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?bn.createElement(Qt,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=bn.createElement(un,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return bn.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}):bn.createElement(bn.Fragment,null,r,s))})))}import yt,{useMemo as ep}from"react";import ec from"clsx";function tp({children:o,className:e,style:t,renderDialogItem:n}){let i=Or(),{state:r}=Wt();return yt.createElement("div",{"data-element-type":"nvl-dialog-list",className:ec("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>yt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},yt.createElement(np,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?yt.createElement(Qt,{className:"nvl-character-name font-bold mr-2"}):null,texts:yt.createElement(un,{className:"nvl-dialog-text"})}):o?yt.Children.map(o,c=>yt.isValidElement(c)?yt.cloneElement(c,{entry:s,index:a}):c):yt.createElement(tc,{entry:s,index:a})))))}function tc({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??yt.createElement(un,{className:"nvl-dialog-text"});return yt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:ec("nvl-dialog-item",t),style:n},r&&yt.createElement(Qt,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function np({entry:o,children:e}){let n=L().getLiveGame().getGameState(),i=ep(()=>o.sentence.evaluate(Ce.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=fo({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return yt.createElement(yn,{value:c},e)}import Do from"react";import{createPortal as ip}from"react-dom";var zr=Do.createContext(null),op={Portal:()=>null,measure:()=>null,container:null};function rp(){let o=Do.useContext(zr);return Do.useMemo(()=>{if(!o)return op;let e=t=>{let n=o.offsetWidth;return!n||!t.width?1:t.width/n};return{container:o,Portal:({children:t})=>ip(Do.createElement("div",{style:{position:"absolute",left:0,top:0,pointerEvents:"auto"}},t),o),measure:t=>{if(!t)return null;let n=o.getBoundingClientRect(),i=e(n),r=t.getBoundingClientRect(),s=(r.left-n.left)/i,a=(r.top-n.top)/i,c=r.width/i,l=r.height/i;return{left:s,top:a,width:c,height:l,right:s+c,bottom:a+l}}}},[o])}import{useEffect as sp}from"react";function ap(o){let e=L();sp(()=>{if(!o)return;let t=e.getLiveGame().getGameState();if(t)return t.suspendAdvance()},[o,e])}function ic({state:o}){let e=L(),t=Ft(),n=$r(null),i=$r(null),r=$r(!1),[s]=ln(oe.Preferences.skipDelay),[a]=ln(oe.Preferences.skipInterval),[c]=vn("skipAction");return lp(()=>{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(oe.Preferences.skip)&&!r.current){o.logger.verbose("KeyEventAnnouncer","Skipping");let g=()=>{n.current=setInterval(()=>{o.events.emit(E.EventTypes["event:state.player.skip"],!1)},a)};u(),o.events.emit(E.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?g():i.current=setTimeout(g,s)}},p=h=>{e.keyMap.match("skipAction",h.key)&&u()};if(e.config.useWindowListener){let h=e.getLiveGame().onWindowEvent("keydown",d).cancel,g=e.getLiveGame().onWindowEvent("keyup",p).cancel;return()=>{u(),h(),g()}}else{let h=e.getLiveGame().onPlayerEvent("keydown",d).cancel,g=e.getLiveGame().onPlayerEvent("keyup",p).cancel;return()=>{u(),h(),g()}}},[t,s,a,c]),nc.createElement(nc.Fragment,null)}import oc,{useEffect as up}from"react";function pp(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var rc=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],dp=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]','[data-element-type="interactive-word"]','[data-element-type="dialog-overlay"]'];function mp(o,e){return!o||e&&rc.some(t=>!!o.closest(t))?!1:[...dp,...rc].some(t=>!!o.closest(t))}function sc(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 ac({state:o}){let e=L();return up(()=>{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)||!sc(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!sc(i,s))||pp(r)||mp(r,o.isNvlMode())||o.isAdvanceSuspended()||(o.events.emit(E.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]),oc.createElement(oc.Fragment,null)}import{useEffect as cc}from"react";function jr({gameState:o}){let e=o.audioManager,[t,n]=ln("globalVolume");return cc(()=>{n(e.getGlobalVolume())},[]),cc(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as Lo,useRef as fp}from"react";function lc(o){let e=De.catSrc(o.srcManager?.src||[]),t=De.catSrc(o.srcManager?.getFutureSrc()||[]),n=[],i=[],r=new Set;for(let s of e.image){let a=De.getSrc(s);!a||r.has(a)||(r.add(a),n.push(a))}for(let s of t.image){let a=De.getSrc(s);!a||r.has(a)||(r.add(a),i.push(a))}return{critical:n,lookAhead:i,all:[...n,...i],criticalAudio:e.audio}}function uc({state:o}){let{preloaded:e,cacheManager:t}=Ut(),n=L(),i=fp(new Set),[r]=se(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function u(){o.logger.debug(s,"Preload unmounted"),e.events.emit(qe.EventTypes["event:preloaded.unmount"])}return Lo(()=>o.events.on(E.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),Lo(()=>{if(typeof fetch>"u")return e.events.emit(qe.EventTypes["event:preloaded.complete"]),e.events.emit(qe.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(qe.EventTypes["event:preloaded.complete"]),e.events.emit(qe.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),u;if(n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(s,"Cache cleared")),!l||!a)return l?o.logger.debug(s,"Scene not ready yet, waiting for scene before preload"):o.logger.weakWarn(s,"Story not found, skipping preload"),u;let d=performance.now(),p=lc(a),h=new xn(n.config.preloadConcurrency,0),g=new xn(n.config.preloadConcurrency,n.config.preloadDelay),m=o.logger.group(s,!0),y=!1;o.logger.debug(s,"preloading:",p,a);let A=(f,v,x,T)=>{v.forEach((b,k)=>{if(t.has(b)||t.isPreloading(b)){o.logger.debug(s,`Image already loaded (${x} ${k+1}/${v.length})`,b);return}f.addTask(()=>new Promise(D=>{t.preload(o,b,{retainDecoded:T}).onFinished(()=>{o.logger.debug(s,`Image loaded (${x} ${k+1}/${v.length})`,b),D()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${x} ${k+1}/${v.length})`,b),D()})}))})};A(h,p.critical,"first scene",!0),A(g,p.lookAhead,"look-ahead",!1);for(let f of p.criticalAudio)o.audioManager.preload(f);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(qe.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit(qe.EventTypes["event:preloaded.ready"]),!y&&(await g.start(),!y&&(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(qe.EventTypes["event:preloaded.ready"]),e.events.emit(qe.EventTypes["event:preloaded.mount"]),()=>{y=!0,u()}},[a,l]),Lo(()=>{i.current.clear()},[a]),Lo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let d=performance.now(),p=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(f=>De.getPreloadableSrc(l,f)).filter(function(f){return f!==null});p.filter(function(f){return f?.activeType==="scene"}).forEach(f=>{i.current.has(f)||i.current.add(f)});let g=De.catSrc([...i.current,...p]),m=new xn(n.config.preloadConcurrency,n.config.preloadDelay),y=[],A=o.logger.group(s);o.logger.debug(s,"preloading:",g);for(let f of g.image){let v=De.getSrc(f);if(v){if(y.push(v),t.has(v)||t.isPreloading(v)){o.logger.debug(s,`Image already loaded (${g.image.indexOf(f)+1}/${g.image.length})`,v);continue}m.addTask(()=>new Promise(x=>{t.preload(o,v).onFinished(()=>{o.logger.debug(s,`Image loaded (${g.image.indexOf(f)+1}/${g.image.length})`,v),x()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${g.image.indexOf(f)+1}/${g.image.length})`,v),x()})}))}}A.end(),m.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(y)})},[c,l]),null}import di from"react";import Ro from"react";import qr,{useEffect as Yr,useLayoutEffect as Qr,useRef as Xr,useState as Jr}from"react";function Bt({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c}){let[l,u]=Jr(null),[d,p]=Jr(null),h=qr.useRef(null),[g]=Jr(()=>new Pi("displayable.refGroup")),m=Xr(g.next()),y=Xr(Ye()),f=L().getLiveGame().getGameState(),v=typeof a=="function"?a(l):a,[x]=se([d,l,y]);Yr(()=>f.events.depends([f.events.on(E.EventTypes["event:state.player.skip"],Oe)]).cancel,[d,l,y]),Qr(()=>{if(k(),!l)return;if(y.current.some(([be])=>!be.current))throw new P("Displayable: Trying to access transition groups before they are mounted");let{controller:V,task:me}=l,O=be=>{y.current.forEach(([Ae],rt)=>{let B=me.resolve[rt],I=typeof B=="function"?B:B.resolver;if(!I)throw new P(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${rt}])`);let ae=I(...be),We=$(v[rt]||v[v.length-1]||{},ae);W(Ae,c?c(We):We)})},pe=V.onUpdate(O);O(me.animations.map(be=>be.start));let Qe=!1;return Promise.all(y.current.map(([be])=>{let Ae=be.current;return Ae?.waitForLoad?Ae.waitForLoad():Promise.resolve()})).then(()=>{Qe||V.start()}),()=>{Qe=!0,pe.cancel()}},[l]),Yr(()=>{if(!h.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),Qr(()=>{let V=e.toStyle(f,i);Object.assign(h.current.style,V),f.logger.debug("Displayable","Initial style applied",h.current,V)},[]);let T=Xr(()=>{});T.current=()=>{d||l||!h.current||(Object.assign(h.current.style,e.toStyle(f,i)),k())},Qr(()=>{T.current()});let{ratio:b}=he();Yr(()=>b.onUpdate(()=>{T.current(),requestAnimationFrame(()=>T.current())}),[b]);function k(){let V=typeof a=="function"?a(l):a;if(!y.current||!y.current.length)throw new P("Displayable: Transition group refs are not initialized correctly");y.current.some(([me])=>!me.current)||y.current.forEach(([me],O)=>{W(me,V[O]||V[V.length-1]||{})})}function D(V){f.logger.debug("Displayable","Transform applied",e.toStyle(f,i),h.current),x(),r?.(V)}function W(V,me){if(!V.current)throw new P("Displayable: Trying to assign properties to unmounted element");Ji(V.current,me,c)}function ue(V,me){d&&(d.abort(),p(null));let O=V.animate(e,{gameState:f,ref:h,overwrites:i}),pe=new we(O);return f.timelines.attachTimeline(pe),O.onSkipControllerRegister(Qe=>{Qe.onAbort(()=>{pe.abort(),p(null)})}),p(O),O.then(()=>{p(null),D(V),me()}),pe}function F(V,me){l&&l.controller.complete();let O=V.createTask(f),pe=V.requestAnimations(O.animations),Qe=new S().registerSkipController(new G(pe.cancel)),be=new we(Qe);Qe.skipController.onAbort(()=>{pe.cancel()}),pe.onCanceled(()=>{be.abort(),u(null),f.logger.debug("Displayable","Transition cancelled",V)}),pe.onComplete(()=>{Ue(),u(null),s?.(V),me(),Qe.resolve()}),f.timelines.attachTimeline(be),u({task:O,controller:pe,transition:V,resolve:me});let Ae;if(y.current=O.resolve.map(rt=>{let B=qr.createRef(),I=typeof rt=="function"?void 0:rt.key;if(!I)return[B,g.next()];if(I==="target")return Ae=g.next(),[B,Ae];if(I==="current")return[B,m.current];throw new P("Displayable: Invalid key type")}),!Ae)throw new P("Displayable: No target key found");return m.current=Ae,be}function Te(V){return f.logger.debug("initDisplayable",o),ue(_.immediate(e.get()),V)}function Oe(){t&&d&&(d.abort(),p(null),f.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),f.logger.debug("transition skipped"))}function Ye(){return[[qr.createRef(),m.current]]}function Ue(){y.current.forEach(([V])=>{V.current=null}),y.current=Ye()}return{transformRef:h,transitionRefs:y.current,transitionTask:l,initDisplayable:Te,applyTransform:ue,applyTransition:F,updateStyleSync:k,flush:x,deps:[d,l,y]}}import{useEffect as hp}from"react";function St(o,e,t=[]){let i=L().getLiveGame().getGameState();return hp(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function Zr({state:o,text:e}){let{ratio:t}=he(),[n]=se(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:u}=Bt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:d=>({width:"fit-content",transform:_.propToCSSTransform(o,d,{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 St(e,{initDisplayable:s,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...u]),Ro.createElement(Ot.Div,{"data-element-type":"text"},Ro.createElement(Ot.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([d,p])=>Ro.createElement("span",{key:p,ref:d,className:e.config.className},Ro.createElement("span",null,e.state.text)))))}import kt,{forwardRef as yp,useCallback as dc,useImperativeHandle as vp,useRef as No,useState as mc}from"react";import Io,{useEffect as _r,useRef as Fn,forwardRef as gp}from"react";var pc=gp(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=Fn(null),{ratio:a}=he(),[c,l]=Io.useState(0),[u,d]=Io.useState(0),p=Fn(null),h=Fn(null),g=L(),m=Fn(!1),y=Fn(null),A=Fn(null);Io.useImperativeHandle(r,()=>s.current,[]),_r(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>{let T=()=>{let b=s.current;return!b||typeof b.decode!="function"?Promise.resolve():b.decode().catch(()=>{})};return m.current?T():(y.current||(y.current=new Promise(b=>{A.current=b})),y.current.then(T))},configurable:!0}})},[]),_r(()=>(f(),a.onUpdate(f)),[o]),_r(()=>{let T=new MutationObserver(b=>{b.forEach(k=>{k.type==="attributes"&&k.attributeName==="src"&&s.current&&f()})});return s.current&&T.observe(s.current,{attributes:!0}),()=>{T.disconnect()}},[o]);function f(){if(s.current&&s.current.naturalWidth){let T,b,k;if(s.current.naturalWidth*s.current.naturalHeight===1)T=a.state.width,b=a.state.height,k=`${T} / ${b}`;else{let F=t?g.config.width/s.current.naturalWidth:1;T=s.current.naturalWidth*a.state.scale*F,b=s.current.naturalHeight*a.state.scale*F,k="auto"}let D=p.current,W=!D||D.w!==T||D.h!==b||D.ar!==k,ue=!!o&&h.current!==o;if(!W&&!ue)return;W&&(p.current={w:T,h:b,ar:k},l(T),d(b),s.current.style.aspectRatio=k),o&&(h.current=o,o(T,b))}}function v(){f(),m.current=!0,A.current&&(A.current(),A.current=null,y.current=null),e&&e()}function x(){m.current=!0,A.current&&(A.current(),A.current=null,y.current=null)}return Io.createElement("img",{ref:s,onLoad:v,onError:x,width:c,height:u,alt:"",src:n,style:i})});pc.displayName="AspectScaleImage";var Mo=pc;import fc from"clsx";import{motion as Sp}from"motion/react";var Tp={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"},hc=yp(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=No(null),a=No([]),c=o.findIndex(l=>l!==null);return vp(r,()=>Object.assign(s.current,{isLoaded:()=>a.current.every(l=>!l?.isLoaded||l.isLoaded()),waitForLoad:()=>Promise.all(a.current.map(l=>l?.waitForLoad?l.waitForLoad():Promise.resolve())).then(()=>{})}),[]),kt.createElement("div",{ref:s},o.map((l,u)=>l===null?null:kt.createElement(Mo,{key:"layer-"+u,ref:d=>{a.current[u]=d},src:t(l),style:Tp,autoFit:e,onSizeChanged:u===c?n:void 0,onLoad:u===c?i:void 0})))});hc.displayName="LayerStack";function bp(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 Ap(o){return R.isStaticSrc(o)?o.state.currentSrc:R.getSrcURL(o)??void 0}var xp={position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none"};function Cp({image:o,state:e}){let[t]=mc(()=>new Y),[n,i]=mc([]),{cacheManager:r}=Ut(),s=No([]),a=No(null),c=R.isLayeredSrc(o)?R.getSrcURLs(o):null;function l(T){return!w.isDataURI(T)&&!r.has(T)&&!r.isPreloading(T)&&!s.current.includes(T)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${T}".
|
|
52
|
+
`&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function iu(o,e,t){return t||(o!==void 0?de.formatStaticWord(o):e?e.text.flatMap(n=>typeof n.text=="function"?[]:new _(n.text,n.config)):[])}function ou(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 Oa(o,e){let t=Math.max(.01,o),n=Math.max(.01,e);return 1e3/(t*n)}function Ao(o){return o===void 0?void 0:kn(o)}function Ba(o){return typeof o.tag2=="number"?o.tag2>=o.full.length-1:o.text.length>=o.full.length}function Ka({word:o,vertical:e,tateChuYoko:t,done:n,style:i,renderer:r}){let s=o.config.ruby?Oe.createElement("ruby",{className:"align-bottom inline-block"},Oe.createElement("rt",{className:"block text-center"},o.config.ruby),kr(o.text,e,t)):kr(o.text,e,t);return r?Oe.createElement(r,{text:o.text,fullText:o.full,revealed:Ba(o),done:n,style:i,config:o.config,data:o.config.data},s):s}function ru(o,e){return!!e&&Ba(o)}function Lr({defaultColor:o,className:e,style:t,dialog:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,writingMode:c,textOrientation:l,tateChuYoko:u,...d}){let p=R(),h=p.getLiveGame().getGameState(),f=Ua(null),[m,y]=Pr(()=>n&&!n.config.useTypeEffect?Er(n.config.evaluatedWords):[]),[b,v]=ae();if(!n)throw new Error("Dialog state is required");bn(()=>{if(!(!n.config.action.sentence||f.current))return h.logger.info("Initializing the sentence",n,f.current),h.schedule(({onCleanup:V})=>{if(!n.config.useTypeEffect){Va(n.config.evaluatedWords,n.config.firedTextEvents??new Set,h),n.dispatchComplete();return}y([]),f.current=g(),b(),f.current.onComplete(()=>{n.dispatchComplete()}),V(()=>{f.current?.timeline?.abort()})},0)},[]),bn(()=>n.events.depends([n.events.on(Ne.Events.requestComplete,()=>{f.current?.interact()}),n.events.on(Ne.Events.forceSkip,()=>{n.isEnded()||f.current?.forceSkip()})]).cancel,[n,v]),bn(()=>n.onFlush(()=>{b()}).cancel,[n]),bn(()=>p.preference.events.depends([p.preference.onPreferenceChange(re.Preferences.gameSpeed,()=>{f.current?.update()}),p.preference.onPreferenceChange(re.Preferences.autoForward,()=>{f.current?.update()}),p.preference.onPreferenceChange(re.Preferences.cps,()=>{f.current?.update()})]).cancel,[]);function g(){let V=new S,fe=new xe(V).setGuard(h.guard),Ue=new Set,Ze=n.config.firedTextEvents??new Set,We=new Set,pt=new Set,Ct=Dr(n.config.evaluatedWords),L=null,ee=[],he=[],be=()=>{ee.forEach(te=>te()),ee.length=0},ke=()=>{if(he.length!==0)return{done:!1,value:he.shift()};let{done:te,value:Ee}=Ct.next();return{done:te,value:Ee}},Pe=te=>{let Ee=Be=>{te(Be),We.delete(Ee)};return We.add(Ee),{cancel:()=>{We.delete(Ee)}}},U=te=>{Wa(y,te)},M=(te=!1)=>{let Ee=!1;for(;!Ee;){let{done:Be,value:Ke}=ke();if(Be){Ee=!0;break}if($e.isPause(Ke)){if(te)continue;Ee=!0,he.push(Ke);break}else at.isTextEvent(Ke)?So(Ke,Ze,h):Ke===`
|
|
53
|
+
`?y(ot=>[...ot,Ke]):typeof Ke=="object"&&"text"in Ke&&!Ue.has(Ke)&&(Ue.add(Ke),U(Ke))}L&&!L.isSettled()?L.abort():(pt.forEach(Be=>Be()),V.resolve())};return h.schedule(async te=>{let Ee=!1,Be=!1;for(;!Ee;){let{done:Ke,value:ot}=ke();if(Ke){Ee=Be=!0;break}if(at.isTextEvent(ot)){So(ot,Ze,h);continue}let Ci=new S;if(h.timelines.attachTimeline(Ci),Ci.registerSkipController(new H(()=>{be(),Ee=!0,te.retry()})),Ci.onSettled(()=>{be()}),L=Ci,$e.isPause(ot)){let xi=$e.from(ot),wi=p.preference.getPreference(re.Preferences.gameSpeed);if(xi.config.duration){let ki=xi.config.duration/wi;await Gi(ki)}else{let ki=p.preference.getPreference(re.Preferences.autoForward),Pi=S.race([S.create(Zc=>{let _c=Pe(el=>{el(),Zc.resolve()});ee.push(()=>_c.cancel())}),...ki?[S.delay(p.config.autoForwardDefaultPause/wi)]:[]]);h.timelines.attachTimeline(Pi),await S.wait(Pi)}}else{if(ot!==`
|
|
54
|
+
`&&Ue.has(ot))continue;Ue.add(ot),U(ot);let{gameSpeed:xi,cps:wi}=p.preference.getPreferences(),Pi=1e3/((typeof ot=="object"&&"cps"in ot&&ot.cps!==void 0?ot.cps:wi)*xi);await Gi(Pi)}}Be&&(pt.forEach(Ke=>Ke()),V.resolve())},0),{getToken:()=>V,interact:()=>{let te=!1;We.forEach(Ee=>Ee(()=>te=!0)),!te&&M()},update:()=>{L&&L.abort()},forceSkip:()=>{M(!0)},timeline:fe,onComplete:te=>(pt.add(te),{cancel:()=>{pt.delete(te)}})}}let C=n.config.action.sentence;if(!C)return null;let T=s??"bold",A={fontWeight:C.config.bold?T:r,fontSize:C.config.fontSize??i,color:Ao(C.config.color??o),fontFamily:C.config.fontFamily??a,fontStyle:C.config.italic?"italic":void 0},P=V=>({fontWeight:V.config.bold||C.config.bold?T:r,fontSize:V.config.fontSize??C.config.fontSize??i,color:Ao(V.config.color??C.config.color??o),fontFamily:V.config.fontFamily??C.config.fontFamily??a,fontStyle:V.config.italic??C.config.italic?"italic":void 0}),D=To(c),W=n.isEnded(),pe=(V,fe)=>{if(V===`
|
|
55
|
+
`)return Oe.createElement("br",{key:fe});let Ue=P(V),Ze=br(V.config.render),We=ru(V,Ze);return Oe.createElement(Wt.Span,{tag:`say.word.${fe}`,key:fe,"data-element-type":We?"interactive-word":void 0,onClick:We?pt=>pt.stopPropagation():void 0,style:{...Ue,...wr(),...Hi(p.config.app.debug,{outline:"1px dashed red"})},className:bo("inline-block",V.config.className)},Oe.createElement(Ka,{word:V,vertical:D,tateChuYoko:u,done:W,style:Ue,renderer:Ze}))};return Oe.createElement("div",{...d,className:bo("whitespace-pre-wrap",e),style:{...A,...xr(c,l),...t}},m.map(pe))}function su({text:o,sentence:e,words:t,useTypeEffect:n=!0,loop:i=!0,restartDelay:r,cps:s,gameSpeed:a,pauseDuration:c,defaultColor:l,className:u,style:d,fontSize:p,fontWeight:h,fontWeightBold:f,fontFamily:m,writingMode:y,textOrientation:b,tateChuYoko:v,onCompleted:g,...C}){let T=wa(),[,A]=Pr(0),P=T?.config??re.DefaultConfig,D=T?.preference.getPreferences()??re.DefaultPreference,W=s??D.cps,pe=a??D.gameSpeed,V=c??P.autoForwardDefaultPause,fe=r??P.autoForwardDefaultPause,Ue=Oe.useMemo(()=>iu(o,e,t),[o,e,t]),Ze=Oe.useMemo(()=>ou(i,r,fe),[i,r,fe]),We=Ua(g),[pt,Ct]=Pr(()=>n?[]:Er(Ue));bn(()=>{if(T)return T.preference.onPreferenceChange(()=>{A(U=>U+1)}).cancel},[T]),bn(()=>{We.current=g},[g]),bn(()=>{let U=!1,M=[],Q=Math.max(.01,pe),ge=te=>new Promise(Ee=>{let Be=setTimeout(Ee,Math.max(0,te));M.push(Be)}),O=()=>{U||We.current?.()};return n?Ue.length===0?(Ct([]),()=>{U=!0}):((async()=>{do{let te=Dr(Ue);for(Ct([]);!U;){let{done:Ee,value:Be}=te.next();if(Ee)break;if($e.isPause(Be)){let Ke=$e.from(Be);await ge((Ke.config.duration??V)/Q)}else{if(at.isTextEvent(Be))continue;Wa(Ct,Be),Be===`
|
|
56
|
+
`?await ge(Oa(W,pe)):await ge(Oa(Be.cps??W,pe))}}if(U)return;O(),Ze.enabled&&await ge(Ze.delay)}while(!U&&Ze.enabled)})(),()=>{U=!0,M.forEach(te=>clearTimeout(te))}):(Ct(Er(Ue)),O(),()=>{U=!0})},[Ue,n,Ze,W,pe,V]);let L=e?.config,ee=f??"bold",he={fontWeight:L?.bold?ee:h,fontSize:L?.fontSize??p,color:Ao(L?.color??l),fontFamily:L?.fontFamily??m,fontStyle:L?.italic?"italic":void 0},be=U=>({fontWeight:U.config.bold||L?.bold?ee:h,fontSize:U.config.fontSize??L?.fontSize??p,color:Ao(U.config.color??L?.color??l),fontFamily:U.config.fontFamily??L?.fontFamily??m,fontStyle:U.config.italic??L?.italic?"italic":void 0}),ke=To(y),Pe=(U,M)=>{if(U===`
|
|
57
|
+
`)return Oe.createElement("br",{key:M});let Q=be(U);return Oe.createElement("span",{key:M,style:{...Q,...wr()},className:bo("inline-block",U.config.className)},Oe.createElement(Ka,{word:U,vertical:ke,tateChuYoko:v,done:!1,style:Q,renderer:br(U.config.render)}))};return Oe.createElement("div",{...C,className:bo("whitespace-pre-wrap",u),style:{...he,...xr(y,b),...d}},pt.map(Pe))}function za(o){return Oe.createElement(Lr,{...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 Oe.createElement(Lr,{...r,dialog:s,key:s.config.action.id})}function cu(o){let e=Pt();return Oe.createElement(Lr,{...o,dialog:e,key:e.config.action.id})}function pn(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Oe.createElement(au,{...o}):Oe.createElement(cu,{...o})}var lu=pn;import xo,{useEffect as uu,useLayoutEffect as pu,useMemo as ja,useRef as du,useState as mu}from"react";import Co from"react";var Rr=Co.createContext(null);function Ir(){let o=Co.useContext(Rr);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var Mr=Co.createContext(null);function $a(){let o=Co.useContext(Mr);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 c=du(null),{register:l,unregister:u,getIndex:d}=$a(),[p,h]=mu(-1),{choose:f,evaluated:m,gameState:y}=Ir(),b=p===-1?null:m[p],v=ja(()=>Ce.getCtx({gameState:y}),[y]),{hidden:g,disabled:C}=ja(()=>{if(!b)return{hidden:!1,disabled:!1};let P=b.config.hidden?.evaluate(v)?.value??!1,D=!P&&(b.config.disabled?.evaluate(v)?.value??!1);return{hidden:P,disabled:D}},[b,v]);pu(()=>{if(!c.current)return;let P=c;l(P);let D=d(P);return h(D),c.current.dataset.index=D.toString(),()=>u(P)},[l,u,d]),uu(()=>{if(!t)return;let P=D=>{D.key.toLowerCase()===t.toLowerCase()&&!D.ctrlKey&&!D.metaKey&&(D.preventDefault(),D.stopPropagation(),T())};return window.addEventListener("keydown",P,!0),()=>{window.removeEventListener("keydown",P,!0)}},[t]);function T(){if(p===-1||!m[p]||g||C)return;let P=m[p];f({...P,evaluated:_.getText(P.words||[])})}let A=b&&!g;return xo.createElement(xo.Fragment,null,xo.createElement("button",{className:o,style:{...e,display:A?e?.display??void 0:"none"},onClick:T,ref:c,disabled:C},A&&xo.createElement(za,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Ne({useTypeEffect:!1,action:{sentence:b.prompt,words:b.words,character:null},gameState:y,evaluatedWords:b.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 qa from"react";function Xt({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=qa.useContext(Sn),c=e??o?.character??a?.config.action.character??null,l=n??c?.config.color,u=i??t??c?.state.name;return qa.createElement("div",{...s,style:{color:l?kn(l):void 0,...r}},u)}import yu from"clsx";import vu from"react";import Nr,{createContext as hu,useContext as gu,useState as Ya}from"react";var An=class An{constructor(){this.preloaded=[];this.events=new q}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(An.EventTypes["event:preloaded.add"],e),this.events.emit(An.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(An.EventTypes["event:preloaded.remove"],e),this.events.emit(An.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Le.getSrc(e)}};An.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 qe=An;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,h)=>{i=p,r={...r,...h}}]);let s=new AbortController,a=s.signal,c=[],u={promise:o.getImage(i,a,r).then(async p=>{if(this.preloadTasks.delete(t),p){this.add(t,p);let h=await o.decodeImage(p);h&&n?.retainDecoded&&this.src.get(t)===p&&this.decoded.set(t,h)}}).catch(p=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),c.forEach(h=>h(p))}),controller:s};this.preloadTasks.set(t,u);let d={abort:()=>{s.abort(),this.preloadTasks.delete(t)},onFinished:p=>(u.promise.then(p),d),onErrored:p=>(c.push(p),d)};return d}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){let t=new Set(e);for(let n of this.src.keys())t.has(n)||(this.src.delete(n),this.decoded.delete(n));for(let n of this.decoded.keys())t.has(n)||this.decoded.delete(n);return this}};var Gr=hu(null);function Qa({children:o}){let e=R(),[t]=Ya(()=>new qe),[n]=Ya(()=>new Eo(e));return Nr.createElement(Nr.Fragment,null,Nr.createElement(Gr,{value:{preloaded:t,cacheManager:n}},o))}function Bt(){if(!Gr)throw new Error("usePreloaded must be used within a PreloadedProvider");return gu(Gr)}function Xa(){let o=Pt(),{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,c=s&&I.isTagSrc(s)?[...s.state.currentSrc]:null,l=ca({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),u=Tu(l.source);return{visible:!!u,src:u,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function Su({className:o,style:e,alt:t,...n}){let i=Xa(),{cacheManager:r}=Bt();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?w.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 Hr=Su;import{useEffect as Au}from"react";function Cu(){let o=Pt(),[e]=ae(o.deps),t=_.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 Fr,useMemo as xu,useRef as wu,useState as Ja}from"react";function ku(){let o=Pt(),[e]=ae(o.deps),[t,n]=Ja(!0),[i,r]=Ja(!0),s=wu(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;Fr(()=>o.events.on(Ne.Events.onFlush,()=>{e()}).cancel,[o]);let u=xu(()=>{if(!c)return null;try{return nt.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);Fr(()=>{s.current=null,r(!0)},[c]),Fr(()=>{let m=!1,y=null,b=null,v=null;if(!u){n(!0);return}n(!1);let g=()=>{m||n(!0)};y=a.audioManager.getToken(u),y&&(y.isPlaying()||n(!0),b=()=>g(),v=()=>g(),y.once("ended",b),y.once("stop",v));let C=a.events.on(E.EventTypes["event:state.player.lineEnd"],()=>{g()});return()=>{m=!0,C.cancel(),y&&b&&y.off("ended",b),y&&v&&y.off("stop",v)}},[a,u]);let d=Do(async m=>{let y=m??u;if(!y)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let b=y instanceof URL?ve.voice(y.toString()):typeof y=="string"?ve.voice(y):y,v=await a.getLiveGame().playSound(b);s.current=v;let g=()=>{r(!0)};return v.once("ended",g),v.once("stop",g),v},[a,u]),p=Do(()=>u,[u]),h=Do(()=>l,[l]),f=Do(()=>u?.getSrc()??null,[u]);return{done:t&&i,voice:u,playVoice:d,getVoice:p,getVoiceId:h,getVoiceSrc:f}}import Vr,{createContext as Vu,useContext as Ou,useEffect as ec,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 mi,{createContext as Mu,useContext as Nu,useEffect as Gu,useRef as Hu}from"react";import{useEffect as ui,useLayoutEffect as Du}from"react";function Lu(){let o=Ot(),[e]=ae();return ui(()=>o.onChange(e).cancel,[]),o.getPathname()}function Ru(){let{router:o,path:e}=di(),[t]=ae();return ui(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function Iu(){let o=Ot(),[e]=ae();return ui(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Io(o,e){let t=Ot();Du(()=>t.onUpdate(()=>o(t)).cancel,e),ui(()=>{o(t)},[])}function pi(){let o=Ot(),[e]=ae();return ui(()=>o.onChange(e).cancel,[]),e}var Za=Mu(null);function fi({children:o,path:e,consumedBy:t}){let i={router:Ot(),path:e,consumedBy:t};return mi.createElement(Za,{value:i},o)}function di(){let o=Nu(Za);if(!o)throw new Error("useLayout must be used within a LayoutRouterProvider");if(o.path===null)throw new k(`Invalid useLayout call: Trying to access layout without a parent.
|
|
58
|
+
This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function Fu({children:o,name:e,propagate:t}){let n=R(),[i]=ae(),{path:r,router:s,consumedBy:a}=di(),c=s.joinPath(r,e),l=Lo(()=>s.createToken(c+"@layout")),u=s.getCurrentPath(),d=Hu(!1),p=f=>{d.current=f,i()},h=s.matchPath(u,c);if(pi(),Io(f=>{let m=f.matchPath(f.getCurrentPath(),c);if(d.current&&!m){if(!o){p(!1);return}f.registerUnmountingPath(l)}m&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(l),m&&!d.current&&!f.isTransitioning()&&p(!0)},[h,o]),Gu(()=>{if(!h)return;let f=s.mount(c);return()=>{f.cancel()}},[c,s,h]),a)throw new k("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return mi.createElement(fi,{path:c},mi.createElement(Ro,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),p(!1)}},h&&d.current&&o))}function _a({children:o}){return pi(),mi.createElement(fi,{path:ln.rootPath},mi.createElement(mo,{"data-layout-path":ln.rootPath,key:ln.rootPath},o))}var Or=Vu(null);function Wu(){return Ou(Or)}function Bu({children:o,name:e}){let[t]=ae(),{path:n,router:i,consumedBy:r}=di(),s=Wu(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,u=Lo(()=>i.createToken(l+"@page")),d=i.getCurrentPath(),p=!a,h=Uu(!1),f=v=>{h.current=v,t()},m=p&&i.exactMatch(d,n)||i.exactMatch(d,l);if(r&&r!==c)throw new k("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");pi(),Io(v=>{let g=p&&v.exactMatch(v.getCurrentPath(),n)||v.exactMatch(v.getCurrentPath(),l);if(h.current&&!g){if(!o){f(!1);return}v.registerUnmountingPath(u)}g&&v.isPathsUnmounting()&&v.unregisterUnmountingPath(u),g&&!h.current&&!v.isTransitioning()&&f(!0)},[m,o]),ec(()=>{if(!m)return;let v=p?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{v.cancel()}},[l,m]),ec(()=>()=>{i.unregisterUnmountingPath(u),f(!1)},[]);let y=Vr.createElement(fi,{path:n,consumedBy:c},Vr.createElement(Ro,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(u),f(!1)}},m&&h.current&&o));return(v=>s?Vr.createElement(Or,{value:{name:null}},v):v)(y)}import Ur,{useCallback as Ku,useEffect as Wr,useImperativeHandle as zu,useMemo as tc,useRef as Br,useState as $u}from"react";var ju=50,qu={position:"relative",width:"100%",height:"100%",overflow:"hidden"},nc={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 ic(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 oc=Ur.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:u,children:d},p){let h=Br(null),[f,m]=$u({...nc,width:"0px",height:"0px"}),y=Br(u),b=Br(null);Wr(()=>{y.current=u},[u]);let v=Ku(()=>{let T=h.current;if(!T)return;let A=T.clientWidth,P=T.clientHeight;if(A<=0||P<=0||e<=0)return;let D=Qu(A,P,e),W=ic(D.width,n),pe=ic(D.height,i),V=b.current;(!V||V.width!==W||V.height!==pe)&&(b.current={width:W,height:pe},m({...nc,width:`${W}px`,height:`${pe}px`}));let fe=t>0?W/t:1;y.current?.({width:W,height:pe,scale:fe,containerWidth:A,containerHeight:P})},[e,t,n,i]),g=tc(()=>Vs(v,typeof r=="number"?r:ju),[v,r]);Wr(()=>{v()},[v]),Wr(()=>{let T=new ResizeObserver(()=>{g()});h.current&&T.observe(h.current);let A=()=>{g()};return window.addEventListener("resize",A),()=>{T.disconnect(),window.removeEventListener("resize",A)}},[g]),zu(p,()=>({requestUpdate:v}),[v]);let C=tc(()=>Yu(l),[l]);return Ur.createElement("div",{id:c,ref:h,style:qu,...C},Ur.createElement("div",{className:s,style:{...f,...a}},d))}),rc=oc;function Xu(){return R().getLiveGame()}import $r from"react";import Ju,{createContext as Zu,useContext as _u,useEffect as ep,useState as sc}from"react";var tp={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},ac=Zu({state:tp,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function Kt(){return _u(ac)}function Kr(){let{dialogs:o}=Kt();return o}function np(){let{isActive:o}=Kt();return o}function ip(){let{isVisible:o}=Kt();return o}function zr({children:o}){let t=R().getLiveGame().getGameState(),[n,i]=sc(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=sc(null);ep(()=>{let c=f=>({...f,dialogs:[...f.dialogs]}),l=t.events.on(E.EventTypes["event:state.nvl.enter"],(f,m)=>{i(c(t.getNvlState())),s(m?.showTransition||null)}),u=t.events.on(E.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState()))}),d=t.events.on(E.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),p=t.events.on(E.EventTypes["event:state.nvl.visibilityChange"],(f,m)=>{i(c(t.getNvlState())),s(m||null)}),h=t.events.on(E.EventTypes["event:state.nvl.change"],f=>{i(c(f))});return()=>{l.cancel(),u.cancel(),d.cancel(),p.cancel(),h.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return Ju.createElement(ac.Provider,{value:a},o)}import{AnimatePresence as op,motion as rp}from"motion/react";import sp from"clsx";function jr({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=Kt(),{ratio:r}=me(),s=R(),a=i?.duration?i.duration/1e3:.3;return $r.createElement(op,null,n&&$r.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},$r.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 Cn from"react";function qr({renderDialogItem:o,dialogs:e}){return Cn.createElement(jr,{className:"bg-black/80 text-white p-16 inset-8"},Cn.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?Cn.createElement(Xt,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=Cn.createElement(pn,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return Cn.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}):Cn.createElement(Cn.Fragment,null,r,s))})))}import vt,{useMemo as ap}from"react";import cc from"clsx";function cp({children:o,className:e,style:t,renderDialogItem:n}){let i=Kr(),{state:r}=Kt();return vt.createElement("div",{"data-element-type":"nvl-dialog-list",className:cc("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>vt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},vt.createElement(lp,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?vt.createElement(Xt,{className:"nvl-character-name font-bold mr-2"}):null,texts:vt.createElement(pn,{className:"nvl-dialog-text"})}):o?vt.Children.map(o,c=>vt.isValidElement(c)?vt.cloneElement(c,{entry:s,index:a}):c):vt.createElement(lc,{entry:s,index:a})))))}function lc({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??vt.createElement(pn,{className:"nvl-dialog-text"});return vt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:cc("nvl-dialog-item",t),style:n},r&&vt.createElement(Xt,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function lp({entry:o,children:e}){let n=R().getLiveGame().getGameState(),i=ap(()=>o.sentence.evaluate(Ce.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=vo({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return vt.createElement(Sn,{value:c},e)}import Mo from"react";import{createPortal as up}from"react-dom";var Yr=Mo.createContext(null),pp={Portal:()=>null,measure:()=>null,container:null};function dp(){let o=Mo.useContext(Yr);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,c=r.width/i,l=r.height/i;return{left:s,top:a,width:c,height:l,right:s+c,bottom:a+l}}}},[o])}import{useEffect as 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 pc({state:o}){let e=R(),t=Ot(),n=Qr(null),i=Qr(null),r=Qr(!1),[s]=un(re.Preferences.skipDelay),[a]=un(re.Preferences.skipInterval),[c]=Tn("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=h=>{if(!o.isAdvanceSuspended()&&e.keyMap.match("skipAction",h.key)&&e.preference.getPreference(re.Preferences.skip)&&!r.current){o.logger.verbose("KeyEventAnnouncer","Skipping");let f=()=>{n.current=setInterval(()=>{o.events.emit(E.EventTypes["event:state.player.skip"],!1)},a)};u(),o.events.emit(E.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?f():i.current=setTimeout(f,s)}},p=h=>{e.keyMap.match("skipAction",h.key)&&u()};if(e.config.useWindowListener){let h=e.getLiveGame().onWindowEvent("keydown",d).cancel,f=e.getLiveGame().onWindowEvent("keyup",p).cancel;return()=>{u(),h(),f()}}else{let h=e.getLiveGame().onPlayerEvent("keydown",d).cancel,f=e.getLiveGame().onPlayerEvent("keyup",p).cancel;return()=>{u(),h(),f()}}},[t,s,a,c]),uc.createElement(uc.Fragment,null)}import dc,{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 mc=['[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&&mc.some(t=>!!o.closest(t))?!1:[...Sp,...mc].some(t=>!!o.closest(t))}function fc(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 hc({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)||!fc(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!fc(i,s))||vp(r)||Tp(r,o.isNvlMode())||o.isAdvanceSuspended()||(o.events.emit(E.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]),dc.createElement(dc.Fragment,null)}import{useEffect as gc}from"react";function Xr({gameState:o}){let e=o.audioManager,[t,n]=un("globalVolume");return gc(()=>{n(e.getGlobalVolume())},[]),gc(()=>{e.setGlobalVolume(t)},[t]),null}import{useEffect as No,useRef as bp}from"react";function yc(o){let e=Le.catSrc(o.srcManager?.src||[]),t=Le.catSrc(o.srcManager?.getFutureSrc()||[]),n=[],i=[],r=new Set;for(let s of e.image){let a=Le.getSrc(s);!a||r.has(a)||(r.add(a),n.push(a))}for(let s of t.image){let a=Le.getSrc(s);!a||r.has(a)||(r.add(a),i.push(a))}return{critical:n,lookAhead:i,all:[...n,...i],criticalAudio:e.audio}}function vc({state:o}){let{preloaded:e,cacheManager:t}=Bt(),n=R(),i=bp(new Set),[r]=ae(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function u(){o.logger.debug(s,"Preload unmounted"),e.events.emit(qe.EventTypes["event:preloaded.unmount"])}return No(()=>o.events.on(E.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),No(()=>{if(typeof fetch>"u")return e.events.emit(qe.EventTypes["event:preloaded.complete"]),e.events.emit(qe.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(qe.EventTypes["event:preloaded.complete"]),e.events.emit(qe.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),u;if(n.config.forceClearCache&&(t.clear(),o.logger.weakWarn(s,"Cache cleared")),!l||!a)return l?o.logger.debug(s,"Scene not ready yet, waiting for scene before preload"):o.logger.weakWarn(s,"Story not found, skipping preload"),u;let d=performance.now(),p=yc(a),h=new wn(n.config.preloadConcurrency,0),f=new wn(n.config.preloadConcurrency,n.config.preloadDelay),m=o.logger.group(s,!0),y=!1;o.logger.debug(s,"preloading:",p,a);let b=(v,g,C,T)=>{g.forEach((A,P)=>{if(t.has(A)||t.isPreloading(A)){o.logger.debug(s,`Image already loaded (${C} ${P+1}/${g.length})`,A);return}v.addTask(()=>new Promise(D=>{t.preload(o,A,{retainDecoded:T}).onFinished(()=>{o.logger.debug(s,`Image loaded (${C} ${P+1}/${g.length})`,A),D()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${C} ${P+1}/${g.length})`,A),D()})}))})};b(h,p.critical,"first scene",!0),b(f,p.lookAhead,"look-ahead",!1);for(let v of p.criticalAudio)o.audioManager.preload(v);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(qe.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit(qe.EventTypes["event:preloaded.ready"]),!y&&(await f.start(),!y&&(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(qe.EventTypes["event:preloaded.ready"]),e.events.emit(qe.EventTypes["event:preloaded.mount"]),()=>{y=!0,u()}},[a,l]),No(()=>{i.current.clear()},[a]),No(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let d=performance.now(),p=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(v=>Le.getPreloadableSrc(l,v)).filter(function(v){return v!==null});p.filter(function(v){return v?.activeType==="scene"}).forEach(v=>{i.current.has(v)||i.current.add(v)});let f=Le.catSrc([...i.current,...p]),m=new wn(n.config.preloadConcurrency,n.config.preloadDelay),y=[],b=o.logger.group(s);o.logger.debug(s,"preloading:",f);for(let v of f.image){let g=Le.getSrc(v);if(g){if(y.push(g),t.has(g)||t.isPreloading(g)){o.logger.debug(s,`Image already loaded (${f.image.indexOf(v)+1}/${f.image.length})`,g);continue}m.addTask(()=>new Promise(C=>{t.preload(o,g).onFinished(()=>{o.logger.debug(s,`Image loaded (${f.image.indexOf(v)+1}/${f.image.length})`,g),C()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${f.image.indexOf(v)+1}/${f.image.length})`,g),C()})}))}}b.end(),m.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-d}ms`),t.filter(y)})},[c,l]),null}import hi from"react";import Go from"react";import Jr,{useEffect as Zr,useLayoutEffect as _r,useRef as es,useState as ts}from"react";function zt({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c,companionRefs:l}){let[u,d]=ts(null),[p,h]=ts(null),f=Jr.useRef(null),[m]=ts(()=>new Li("displayable.refGroup")),y=es(m.next()),b=es(pt()),g=R().getLiveGame().getGameState(),C=typeof a=="function"?a(u):a,[T]=ae([p,u,b]);Zr(()=>g.events.depends([g.events.on(E.EventTypes["event:state.player.skip"],We)]).cancel,[p,u,b]),_r(()=>{if(W(),!u)return;if(b.current.some(([Pe])=>!Pe.current))throw new k("Displayable: Trying to access transition groups before they are mounted");let{controller:L,task:ee}=u,he=Pe=>{b.current.forEach(([U],M)=>{let Q=ee.resolve[M],ge=typeof Q=="function"?Q:Q.resolver;if(!ge)throw new k(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${M}])`);let O=ge(...Pe),St=z(C[M]||C[C.length-1]||{},O);V(U,c?c(St):St)})},be=L.onUpdate(he);he(ee.animations.map(Pe=>Pe.start));let ke=!1;return Promise.all(b.current.map(([Pe])=>{let U=Pe.current;return U?.waitForLoad?U.waitForLoad():Promise.resolve()})).then(()=>{ke||L.start()}),()=>{ke=!0,be.cancel()}},[u]),Zr(()=>{if(!f.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),_r(()=>{let L=e.toStyle(g,i);Object.assign(f.current.style,L),D(),g.logger.debug("Displayable","Initial style applied",f.current,L)},[]);let A=es(()=>{});A.current=()=>{p||u||!f.current||(Object.assign(f.current.style,e.toStyle(g,i)),D(),W())},_r(()=>{A.current()});let{ratio:P}=me();Zr(()=>P.onUpdate(()=>{A.current(),requestAnimationFrame(()=>A.current())}),[P]);function D(){if(l)for(let{ref:L,project:ee}of l)L.current&&Object.assign(L.current.style,ee(e.get()))}function W(){let L=typeof a=="function"?a(u):a;if(!b.current||!b.current.length)throw new k("Displayable: Transition group refs are not initialized correctly");b.current.some(([ee])=>!ee.current)||b.current.forEach(([ee],he)=>{V(ee,L[he]||L[L.length-1]||{})})}function pe(L){g.logger.debug("Displayable","Transform applied",e.toStyle(g,i),f.current),T(),r?.(L)}function V(L,ee){if(!L.current)throw new k("Displayable: Trying to assign properties to unmounted element");to(L.current,ee,c)}function fe(L,ee){p&&(p.abort(),h(null));let he=L.animate(e,{gameState:g,ref:f,overwrites:i,companionRefs:l}),be=new xe(he);return g.timelines.attachTimeline(be),he.onSkipControllerRegister(ke=>{ke.onAbort(()=>{be.abort(),h(null)})}),h(he),he.then(()=>{h(null),pe(L),ee()}),be}function Ue(L,ee){u&&u.controller.complete();let he=L.createTask(g),be=L.requestAnimations(he.animations),ke=new S().registerSkipController(new H(be.cancel)),Pe=new xe(ke);ke.skipController.onAbort(()=>{be.cancel()}),be.onCanceled(()=>{Pe.abort(),d(null),g.logger.debug("Displayable","Transition cancelled",L)}),be.onComplete(()=>{Ct(),d(null),s?.(L),ee(),ke.resolve()}),g.timelines.attachTimeline(Pe),d({task:he,controller:be,transition:L,resolve:ee});let U;if(b.current=he.resolve.map(M=>{let Q=Jr.createRef(),ge=typeof M=="function"?void 0:M.key;if(!ge)return[Q,m.next()];if(ge==="target")return U=m.next(),[Q,U];if(ge==="current")return[Q,y.current];throw new k("Displayable: Invalid key type")}),!U)throw new k("Displayable: No target key found");return y.current=U,Pe}function Ze(L){return g.logger.debug("initDisplayable",o),fe(Z.immediate(e.get()),L)}function We(){t&&p&&(p.abort(),h(null),g.logger.debug("transform skipped")),n&&u&&(u.controller.complete(),g.logger.debug("transition skipped"))}function pt(){return[[Jr.createRef(),y.current]]}function Ct(){b.current.forEach(([L])=>{L.current=null}),b.current=pt()}return{transformRef:f,transitionRefs:b.current,transitionTask:u,initDisplayable:Ze,applyTransform:fe,applyTransition:Ue,updateStyleSync:W,flush:T,deps:[p,u,b]}}import{useEffect as Ap}from"react";function bt(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}=me(),[n]=ae(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:u}=zt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:d=>({width:"fit-content",transform:Z.propToCSSTransform(o,d,{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 bt(e,{initDisplayable:s,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...u]),Go.createElement(Wt.Div,{"data-element-type":"text"},Go.createElement(Wt.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([d,p])=>Go.createElement("span",{key:p,ref:d,className:e.config.className},Go.createElement("span",null,e.state.text)))))}import Dt,{forwardRef as xp,useCallback as Tc,useImperativeHandle as wp,useRef as Vo,useState as bc}from"react";import Ho,{useEffect as is,useRef as On,forwardRef as Cp}from"react";var Sc=Cp(({onSizeChanged:o,onLoad:e,autoFit:t=!1,src:n,style:i},r)=>{let s=On(null),{ratio:a}=me(),[c,l]=Ho.useState(0),[u,d]=Ho.useState(0),p=On(null),h=On(null),f=R(),m=On(!1),y=On(null),b=On(null);Ho.useImperativeHandle(r,()=>s.current,[]),is(()=>{s.current&&Object.defineProperties(s.current,{isLoaded:{value:()=>m.current,configurable:!0},waitForLoad:{value:()=>{let T=()=>{let A=s.current;return!A||typeof A.decode!="function"?Promise.resolve():A.decode().catch(()=>{})};return m.current?T():(y.current||(y.current=new Promise(A=>{b.current=A})),y.current.then(T))},configurable:!0}})},[]),is(()=>(v(),a.onUpdate(v)),[o]),is(()=>{let T=new MutationObserver(A=>{A.forEach(P=>{P.type==="attributes"&&P.attributeName==="src"&&s.current&&v()})});return s.current&&T.observe(s.current,{attributes:!0}),()=>{T.disconnect()}},[o]);function v(){if(s.current&&s.current.naturalWidth){let T,A,P;if(s.current.naturalWidth*s.current.naturalHeight===1)T=a.state.width,A=a.state.height,P=`${T} / ${A}`;else{let V=t?f.config.width/s.current.naturalWidth:1;T=s.current.naturalWidth*a.state.scale*V,A=s.current.naturalHeight*a.state.scale*V,P="auto"}let D=p.current,W=!D||D.w!==T||D.h!==A||D.ar!==P,pe=!!o&&h.current!==o;if(!W&&!pe)return;W&&(p.current={w:T,h:A,ar:P},l(T),d(A),s.current.style.aspectRatio=P),o&&(h.current=o,o(T,A))}}function g(){v(),m.current=!0,b.current&&(b.current(),b.current=null,y.current=null),e&&e()}function C(){m.current=!0,b.current&&(b.current(),b.current=null,y.current=null)}return Ho.createElement("img",{ref:s,onLoad:g,onError:C,width:c,height:u,alt:"",src:n,style:i})});Sc.displayName="AspectScaleImage";var Fo=Sc;import Ac 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"},Cc=xp(({src:o,autoFit:e,resolveSrc:t,onSizeChanged:n,onLoad:i},r)=>{let s=Vo(null),a=Vo([]),c=o.findIndex(l=>l!==null);return wp(r,()=>Object.assign(s.current,{isLoaded:()=>a.current.every(l=>!l?.isLoaded||l.isLoaded()),waitForLoad:()=>Promise.all(a.current.map(l=>l?.waitForLoad?l.waitForLoad():Promise.resolve())).then(()=>{})}),[]),Dt.createElement("div",{ref:s},o.map((l,u)=>l===null?null:Dt.createElement(Fo,{key:"layer-"+u,ref:d=>{a.current[u]=d},src:t(l),style:Pp,autoFit:e,onSizeChanged:u===c?n:void 0,onLoad:u===c?i:void 0})))});Cc.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]=bc(()=>new q),[n,i]=bc([]),{cacheManager:r}=Bt(),s=Vo([]),a=Vo(null),c=I.isLayeredSrc(o)?I.getSrcURLs(o):null;function l(T){return!w.isDataURI(T)&&!r.has(T)&&!r.isPreloading(T)&&!s.current.includes(T)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${T}".
|
|
59
59
|
This may be caused by complicated image action behavior that cannot be predicted.
|
|
60
|
-
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(T)),r.get(T)||T}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:h,applyTransition:g,applyTransform:m,updateStyleSync:y,flush:A,deps:f}=Bt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:T=>{if(c)return(T?T.task.resolve:[null]).map(D=>D&&typeof D=="function"?{style:xp}:{style:bp(o.state.darkness)});let b=T?T.transition._getCurrentSrc():Ap(o);return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:w.isColor(b)?w.colorToString(b):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:w.isImageSrc(b)?w.srcToURL(b):R.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:T=>T.src?{...T,src:l(T.src)}:T});St(o,{createWearable:T=>{i(b=>[...b,T])},disposeWearable:T=>{i(b=>b.filter(k=>k.getId()!==T.getId()))},initDisplayable:h,applyTransform:m,applyTransition:g,events:t,updateStyleSync:y,flush:A},[...f]);let v=dc((T,b)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${T}px`,height:`${b}px`}))},[t]),x=dc(()=>{t.emit("event:image.onLoad")},[t]);return kt.createElement(Sp.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},kt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?d.map(([T,b],k)=>{let D=p?p.task.resolve[k]:null;if(D&&typeof D=="function")return kt.createElement(Mo,{key:b,ref:T,autoFit:o.config.autoFit});let W=D?D.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():c;return kt.createElement(hc,{key:b,ref:T,src:W||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:k===0?v:void 0,onLoad:k===0?x:void 0})}):d.map(([T,b],k)=>kt.createElement(Mo,{key:b,ref:T,autoFit:o.config.autoFit,onSizeChanged:k===0?v:void 0,onLoad:k===0?x:void 0})),kt.createElement("div",{className:fc("w-full h-full top-0 left-0 absolute")},n.map(T=>kt.createElement("div",{className:fc("w-full h-full relative"),key:"wearable-"+T.getId()},kt.createElement(gc,{image:T,state:e}))))))}var gc=kt.memo(Cp),yc=gc;import Ho,{useEffect as Sc,useMemo as Dp,useRef as es}from"react";var wp=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/)/,kp=/^(?:[a-zA-Z][a-zA-Z\d+.-]*:)?\/\/[^/]*\/?/;function vc(o,e){if(typeof e!="string"||!e.length)return o;if(wp.test(e)||typeof o!="string"||o.startsWith("data:"))return e;let[t,n]=Pp(o.replace(/\\/g,"/")),i=n.replace(/[?#].*$/,""),r=i.slice(0,i.lastIndexOf("/")+1);return t+Ep(r+e.replace(/\\/g,"/"))}function Pp(o){let e=kp.exec(o);return e?[e[0],o.slice(e[0].length)]:o.startsWith("/")?["/",o.slice(1)]:["",o]}function Ep(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 Go=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 ts({state:o,puppet:e}){let[t]=se(),{cacheManager:n}=Ut(),i=es(null),r=Dp(()=>e._resolveSize({width:o.game.config.width,height:o.game.config.height}),[e,o.game.config.width,o.game.config.height]),s=es(r);s.current=r;let{transformRef:a,transitionRefs:c,initDisplayable:l,applyTransform:u,applyTransition:d,updateStyleSync:p,deps:h}=Bt({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`}}]});St(e,{initDisplayable:l,applyTransform:u,applyTransition:d,updateStyleSync:p,flush:t},[...h]),Sc(()=>{let y=i.current;if(!y)return;let A=o.game,f=e.config.backend,v=A.getPuppetBackend(f);if(!v)return e._setStatus("missing-backend"),A.getPuppetBackendRegistry().reportMissing(f,b=>{o.logger.warn("Puppet",b)}),()=>{e._setStatus("unmounted")};let x;try{x=v.mount(y,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:m,resolveSibling:b=>m(vc(e.config.src,b)),warn:(b,k)=>{o.logger.warn("Puppet",b,k)}})}catch(b){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${f}" threw while mounting "${e.config.src}"`,b),()=>{e._setStatus("unmounted")}}let T=!1;return e._attachInstance(x),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!T&&typeof x.ready=="function"?x.ready():void 0).then(()=>{T||e._setStatus("ready")}).catch(b=>{T||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${f}" failed to load "${e.config.src}"`,b))}),()=>{T=!0,e._attachInstance(null),e._setStatus("unmounted");try{x.dispose()}catch(b){o.logger.error("Puppet",`Backend "${f}" threw while disposing`,b)}}},[]);let g=es(r);Sc(()=>{let y=g.current;if(y.width===r.width&&y.height===r.height)return;g.current=r;let A=e._getInstance();if(!(!A||typeof A.resize!="function"))try{A.resize(r)}catch(f){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,f)}},[r]);function m(y){return w.isDataURI(y)?y:n.get(y)||y}return Ho.createElement(Ot.Div,{"data-element-type":"puppet"},Ho.createElement(Ot.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},c.map(([y,A])=>Ho.createElement("div",{key:A,ref:y,className:e.config.className},Ho.createElement("div",{ref:i,className:"w-full h-full","data-puppet-id":e.getId(),"data-puppet-backend":e.config.backend})))))}function ns({state:o,displayable:e}){return di.createElement(di.Fragment,null,e.map(t=>{if(t instanceof fn)return di.createElement(Zr,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof R)return di.createElement(yc,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof xt)return di.createElement(ts,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Fo,{useEffect as Lp}from"react";import{motion as Rp}from"motion/react";function Tc({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=Bt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return St(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),Lp(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Fo.createElement(Fo.Fragment,null,Fo.createElement(Rp.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([u,d])=>Fo.createElement("div",{className:"relative w-full h-full",ref:u,key:d},t))))}async function bc(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 Ip from"clsx";import{useEffect as is,useRef as Mp}from"react";import os from"react";function rs({state:o,className:e,elements:t}){let{scene:n,layers:i}=t,r=Mp(null);return is(()=>(o.stageTransition.registerScene(n,r.current),()=>{o.stageTransition.registerScene(n,null)}),[]),is(()=>n.events.depends([n.events.on(gt.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),is(()=>(n.events.emit(gt.EventTypes["event:scene.mount"]),o.events.emit(E.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(gt.EventTypes["event:scene.unmount"]),o.events.emit(E.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),St(n,{setBackgroundMusic(s,a){return bc(o,n,s,a)}}),os.createElement("div",{className:Ip(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])=>os.createElement(Tc,{state:o,layer:s,key:s.getId()},os.createElement(ns,{state:o,displayable:a}))))}import{AnimatePresence as Fp}from"motion/react";import{useEffect as Vp,useReducer as Op,useRef as mi}from"react";import Np from"clsx";import Kt,{useCallback as ss,useMemo as Gp,useRef as Hp}from"react";function as({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=L(),a=Hp([]),c=ss(g=>(a.current.push(g),a.current.indexOf(g)),[]),l=ss(g=>{let m=a.current.indexOf(g);m!==-1&&a.current.splice(m,1)},[]),u=ss(g=>a.current.indexOf(g),[]),d=s.config.menu,p=Gp(()=>e.map(g=>({...g,words:g.prompt.evaluate(Ce.getCtx({gameState:n}))})),[]);function h(g){t(g)}return Kt.createElement(Kt.Fragment,null,Kt.createElement(Pr,{value:{evaluated:p,choose:h,gameState:n}},Kt.createElement(Dr,{value:{register:c,unregister:l,getIndex:u}},Kt.createElement(Vt,{className:"absolute"},r&&o&&Kt.createElement(si,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),Kt.createElement(Ot.Div,{color:"green",border:"dashed",className:Np("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},Kt.createElement(d,{items:p.map((g,m)=>m)})))))}function Ac({items:o}){return Kt.createElement(lo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>Kt.createElement(bo,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import Up from"clsx";import fi from"react";var Wp=120;function cs({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=mi(!1),a=mi({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),c=mi([]),l=mi(null),u=mi(null),[,d]=Op(m=>m+1,0),p=()=>{u.current&&(clearTimeout(u.current),u.current=null)},h=()=>{let m=l.current;if(!m)return;let y=a.current;m.forEach(({slot:A,presenceKey:f})=>{y.slotKeys.get(A)===f&&y.slotKeys.delete(A),y.exitingKeys.add(f)}),l.current=null,u.current=null,c.current=[],d()};Vp(()=>()=>{p()},[]);let g=(()=>{let m=a.current,y=i.length>0?i.map(({action:v,onClick:x},T)=>({action:v,slot:T,useTypeEffect:!s.current,onFinished:b=>{b!==void 0&&(s.current=b),x(),o.events.emit(E.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((v,x)=>{if(!v.action.prompt||!v.action.words)return[];let T=m.menuPromptIds.get(v);return T||(T=`menu-prompt-${n.getId()}-${m.nextKey++}`,m.menuPromptIds.set(v,T)),[{action:{sentence:v.action.prompt,words:v.action.words,character:null,id:T},slot:x,useTypeEffect:!1}]});if(y.length===0)return!l.current&&c.current.length>0&&(l.current=c.current.map(v=>({...v,active:!1}))),l.current&&!u.current&&(u.current=setTimeout(h,Wp)),l.current??[];p(),l.current=null;let A=new Set(y.map(({slot:v})=>v));for(let[v,x]of Array.from(m.slotKeys))A.has(v)||(m.exitingKeys.add(x),m.slotKeys.delete(v));let f=y.map(({slot:v,...x})=>{let T=m.slotKeys.get(v);return(!T||m.exitingKeys.has(T))&&(T=`say-${n.getId()}-${m.nextKey++}`,m.slotKeys.set(v,T)),{...x,presenceKey:T,slot:v,active:!0}});return c.current=f,f})();return fi.createElement("div",{className:Up(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs"},fi.createElement(Fp,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{a.current.exitingKeys.clear()}},g.map(({action:m,onFinished:y,presenceKey:A,active:f,useTypeEffect:v})=>fi.createElement(si,{gameState:o,key:A,action:m,active:f,onFinished:y,useTypeEffect:v}))),r.map(({action:m,onClick:y},A)=>fi.createElement("div",{key:"menu-"+A,"data-element-type":"menu"},fi.createElement(as,{state:o,prompt:m.prompt,choices:m.choices,renderPrompt:!m.prompt,afterChoose:f=>{s.current=!1,y(f),o.stage.next()},words:m.words}))))}import xc,{useEffect as Bp}from"react";import{motion as Kp}from"motion/react";function Cc({state:o,camera:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=Bt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return St(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),Bp(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),xc.createElement(Kp.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"camera"},i.map(([u,d])=>xc.createElement("div",{className:"relative w-full h-full",ref:u,key:d},t)))}import zp from"react";import{useEffect as ls,useRef as $p}from"react";import{useCallback as wc}from"react";function kc(o){let e=wc(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=wc(()=>{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 us({gameState:o,video:e}){let t=$p(null),{show:n,hide:i}=kc(t);ls(()=>o.events.depends([o.events.on(E.EventTypes["event:state.player.skip"],()=>{o.game.config.allowSkipVideo&&(r(),o.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),ls(()=>{i(),e.state.display&&n()},[]),ls(()=>{if(!t.current)return;let s=t.current,a=!1,c=new Set,l=()=>new P(`Failed to add event listener, ref is not available
|
|
61
|
-
at Video.tsx: useEffect`),u=h=>{a||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw l();n()},hide:()=>{if(!t.current)throw l();i()},play:()=>{if(!t.current)throw l();let g=t.current;return h||g.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(g.currentTime=0,new Promise(m=>{let y=!1,A=null,f=[],v=()=>{y||(y=!0,c.delete(v),A&&A(),f.forEach(x=>x()),m())};c.add(v),A=o.schedule(({retry:x})=>{if(y)return;if(g.readyState<3){let D=()=>{g.removeEventListener("loadeddata",D),x()};g.addEventListener("loadeddata",D),f.push(()=>g.removeEventListener("loadeddata",D));return}let T=()=>v(),b=()=>v(),k=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),v()};g.addEventListener("ended",T),g.addEventListener("stopped",b),g.addEventListener("error",k),f.push(()=>{g.removeEventListener("ended",T),g.removeEventListener("stopped",b),g.removeEventListener("error",k)}),g.play().catch(D=>{o.logger.error("Failed to play video: "+D),v()})},10)}))},pause:()=>{if(!t.current)throw l();t.current.pause()},resume:()=>{if(!t.current)throw l();return t.current.play().catch(g=>{o.logger.error("Failed to resume video: "+g)})},stop:()=>{if(!t.current)throw l();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:g=>{if(!t.current)throw l();t.current.currentTime=g}}))},d=()=>u(!1),p=()=>{o.logger.error("NarraLeaf-React: Video",`Failed to load video source: ${e.config.src}`+(s.error?` (media error code ${s.error.code})`:"")),u(!0)};return s.addEventListener("canplay",d),s.addEventListener("error",p),s.readyState>=3?u(!1):s.error&&p(),()=>{s.removeEventListener("canplay",d),s.removeEventListener("error",p),c.forEach(h=>h()),s.currentTime>0&&s.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]);function r(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return zp.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 jp,{useEffect as qp,useRef as Yp}from"react";var Pc={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 Qp(o,e){return e===void 0?"linear":Array.isArray(e)?`cubic-bezier(${e.join(", ")})`:typeof e=="string"&&Pc[e]?Pc[e]:(o.logger.debug("NarraLeaf-React: Vfx",'Easing has no CSS equivalent, falling back to "ease"',e),"ease")}function ps({gameState:o,vfx:e}){let t=Yp(null);return qp(()=>{let n=t.current;if(!n)return;let i=!1,r=!1,s=0,a=!1,c=new Set,l=new Set,u=[],d=x=>{n.style.transition="",n.style.opacity=String(x)},p=()=>{n.play().catch(x=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+x)})},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(x=>{let T=!1,b=()=>D(),k=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),D()},D=()=>{T||(T=!0,l.delete(D),n.removeEventListener("loadeddata",b),n.removeEventListener("error",k),x())};l.add(D),n.addEventListener("loadeddata",b),n.addEventListener("error",k),(n.readyState>=2||n.error)&&D()}),g=(x,T,b)=>{let k=T?.duration??0,D=++s;return b.instant||k<=0?(d(x),Promise.resolve()):new Promise(W=>{let ue=!1,F=null,Te=()=>{ue||(ue=!0,l.delete(Te),F!==null&&clearTimeout(F),s===D&&t.current&&d(x),W())};l.add(Te),n.style.transition=`opacity ${k}ms ${Qp(o,T?.easing)}`,n.offsetWidth,n.style.opacity=String(x),F=setTimeout(Te,k)})},m=x=>{r||(r=!0,i=x,o.mountState(e,{show:async T=>{a=!0;let b={instant:!1};c.add(b);try{if(await h(),!t.current)return;e.state.paused||p(),await g(e.config.opacity,T,b)}finally{c.delete(b)}},hide:async T=>{a=!0;let b={instant:!1};c.add(b);try{await g(0,T,b),t.current&&n.pause()}finally{c.delete(b)}},pause:()=>{n.pause()},resume:()=>{p()},setRate:T=>{n.playbackRate=T}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&d(e.config.opacity)},0)))},y=()=>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)},f=o.events.on(E.EventTypes["event:state.player.skip"],()=>{c.size===0&&l.size===0||(c.forEach(x=>{x.instant=!0}),[...l].forEach(x=>x()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),v=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&t.current&&p()};return document.addEventListener("visibilitychange",v),n.style.opacity="0",n.playbackRate=e.config.playbackRate,e.config.muted||o.logger.weakWarn("NarraLeaf-React: Vfx","Vfx is not muted; autoplay may be rejected by the browser. (src: "+e.config.src+")"),e.state.display&&!e.state.paused&&p(),n.addEventListener("canplay",y),n.addEventListener("error",A),n.readyState>=3?m(!1):n.error&&A(),()=>{n.removeEventListener("canplay",y),n.removeEventListener("error",A),document.removeEventListener("visibilitychange",v),f.cancel(),u.forEach(x=>x()),[...l].forEach(x=>x()),n.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]),jp.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,mixBlendMode:e.config.blendMode,pointerEvents:"none"}})}import Xp from"clsx";import Jp,{useCallback as Zp,useEffect as Vo,useRef as _p}from"react";function ds({children:o,className:e,gameState:t}){let{ratio:n}=he(),i=L(),[r]=se(),s=_p(null),a=i.config.minWidth,c=i.config.minHeight,l=Zp(u=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(u.width,u.height,u.scale),n.updateMin(a,c),r()},[r,t.logger,c,a,n]);return Vo(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Vo(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Vo(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Vo(()=>t.events.on(E.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),Jp.createElement(Ja,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:Xp(e),onUpdate:l},o)}import Ec,{useEffect as ed,useRef as td,useState as Dc}from"react";function ms({src:o,width:e,height:t}){let[n,i]=Dc({x:0,y:0}),[r,s]=Dc(!1),a=td(null),{ratio:c}=he();return ed(()=>{let l=u=>{if(a.current){let d=a.current.getBoundingClientRect(),p=u.clientX-d.left,h=u.clientY-d.top;i({x:p,y:h}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),Ec.createElement(Vt,{ref:a,className:"overflow-hidden absolute"},Ec.createElement("img",{src:o,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:r?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import Lc from"react";import Xt from"react";function fs({error:o,errorInfo:e}){return L().config.app.debug?Xt.createElement("div",{className:"text-left"},Xt.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),Xt.createElement("p",{className:"text-red-700"},"Message: ",o.message),Xt.createElement("pre",null,"Error Stack: ",o?.stack),Xt.createElement("pre",null,"Component Stack: ",e?.componentStack),Xt.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):Xt.createElement("div",{className:"bg-white w-full h-full"},Xt.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),Xt.createElement("p",null,"Please contact the game developer for further assistance."))}var Oo=class extends Lc.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?Lc.createElement(fs,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import Mc from"clsx";import H,{useEffect as Pt,useReducer as Nc,useState as Vn}from"react";import{flushSync as Gc}from"react-dom";import{useRef as nd}from"react";import{useEffect as id}from"react";function Rc({gameState:o}){let e=nd(null);return id(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(E.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import hi,{useEffect as od}from"react";function hs({gameState:o}){let[e]=se(),{ratio:t}=he(),n=o.notificationMgr;od(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return hi.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"},hi.createElement(i,{notifications:n.toArray()}))}function Ic({notifications:o}){return hi.createElement(xo,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>hi.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},hi.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function Hc({story:o=ti.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:u,active:d=!0}){let[p,h]=Nc(I=>I+1,0),[g,m]=Nc(I=>I+1,0),[y,A]=Vn(0),f=L(),[v]=Vn(()=>new E(f,{update:h,forceUpdate:()=>{v.logger.weakWarn("Player","force update"),Gc(()=>{h()})},forceRemount:()=>{v.logger.weakWarn("Player","force remount"),Gc(()=>{A(I=>I+1),h()})},next:Ae})),x=H.createRef(),T=H.createRef(),[b,k]=Vn(!1),D=H.useRef(!1),W=H.useRef(null),ue=H.useRef(null),{preloaded:F}=Ut(),[Te,Oe]=Vn(!1),Ye=H.useRef(!1),[Ue,V]=Vn(!1),me=H.useRef(!1),O=H.useRef(null),pe=H.useRef(!1),[Qe]=Vn(new Map);function be(I){return{game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable(),scene:I}}function Ae(){let I=()=>{Qe.forEach(U=>U.cancel())};if(v.rollLock.isLocked())return;I();let ae=!1,We=0;for(;!ae;){if(We++>f.config.maxStackModelLoop)throw new P("Max stack model loop reached");let U=f.getLiveGame().next();if(!U){if(f.getLiveGame().stackModel&&!f.getLiveGame().stackModel.isEmpty())continue;break}if(S.isAwaitable(U)){if(W.current===U)break;W.current=U,U.onSettled(()=>{U.isFailed()||(W.current===U&&(W.current=null),Ae())}),U.onFailed(zt=>{W.current===U&&(W.current=null),v.logger.error("Player",zt)}),ae=!0;break}if(U instanceof An){if(ue.current===U)break;ue.current=U,U.nextUnlock().then(()=>{ue.current===U&&(ue.current=null),Ae()}),ae=!0;break}if(Ze.isCalledActionResult(U)&&U.wait&&Ze.isStackModelsAwaiting(U.wait.type,U.wait.stackModels)){if(W.current===U)break;if(W.current=U,U.wait){let zt=Ze.executeStackModelGroup(U.wait.type,U.wait.stackModels);zt.then(()=>{W.current===U&&(W.current=null),Ae()}),zt.onFailed(ee=>{W.current===U&&(W.current=null),v.logger.error("Player",ee)})}ae=!0;break}v.handle(U)}v.stage.update()}Pt(()=>{v.audioManager.initialize()},[]),Pt(()=>(f.getLiveGame().setGameState(v),o&&!f.getLiveGame().isPlaying()&&f.getLiveGame().loadStory(o),o?.entryScene&&!v.getPreloadingScene()&&!v.getLastScene()&&v.preloadScene(o.entryScene),v.playerCurrent=x.current,v.mainContentNode=T.current,()=>{f.getLiveGame().setGameState(void 0),v.playerCurrent=null}),[f,o]),Pt(()=>at(()=>{k(!0);let I=v.getLastScene(),ae=[];I?ae.push(I.events.once("event:scene.mount",()=>{v.stage.next()}).cancel):v.stage.next();let We=v.events.on(E.EventTypes["event:state.end"],()=>{c&&c({game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable()})});return v.stage.update(),()=>{I&&ae.forEach(U=>U()),We.cancel()}}),[]),Pt(()=>at(()=>{b&&i&&!D.current&&(D.current=!0,v.stage.forceUpdate(),f.hooks.trigger("init",[]),i({game:f,gameState:v,liveGame:f.getLiveGame(),storable:f.getLiveGame().getStorable()}))}),[b]),Pt(()=>at(()=>{if(Te&&s&&!Ye.current){Ye.current=!0;let I=O.current||v.getLastScene()||v.getPreloadingScene(),ae=be(I);s(ae)}}),[Te]),Pt(()=>at(()=>{if(Ue&&!me.current){me.current=!0;let I=O.current||v.getLastScene()||v.getPreloadingScene(),ae=be(I);f.markPreloadComplete(ae)&&r&&r(ae)}}),[Ue]),Pt(()=>v.events.on(E.EventTypes["event:state.scene.mount"],I=>{O.current||(O.current=I,m())}).cancel,[]),Pt(()=>{if(!Ue||!d||pe.current||f.isFirstSceneReady())return;let I=O.current||v.getLastScene();if(!I)return;let ae=null,We=null,U=!1;pe.current=!0;let zt=()=>{U=!0,pe.current=!1;let ee=be(I);f.markFirstSceneReady(ee)&&a&&a(ee)};return typeof requestAnimationFrame=="function"?ae=requestAnimationFrame(()=>{We=setTimeout(zt,0)}):We=setTimeout(zt,0),()=>{U||(pe.current=!1,ae!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(ae),We!==null&&clearTimeout(We))}},[d,g,p,Ue]),Pt(()=>F.events.depends([F.events.on(qe.EventTypes["event:preloaded.ready"],()=>{Oe(!0),v.stage.update(),o&&f.getLiveGame().isPlaying()&&Ae()}),F.events.on(qe.EventTypes["event:preloaded.complete"],()=>{V(!0)})]).cancel,[]),Pt(()=>{v.flushDep=p},[p]);let rt=e||f.config.width,B=t||f.config.height;return H.createElement(Oo,{onError:l},H.createElement("div",{style:{width:typeof rt=="number"?`${rt}px`:rt,height:typeof B=="number"?`${B}px`:B},className:Mc(n,"__narraleaf_content-player"),ref:x,tabIndex:0},H.createElement(ds,{className:Mc("flex-grow overflow-auto"),gameState:v},H.createElement(jr,{gameState:v}),H.createElement(Rc,{gameState:v}),H.createElement(Vt,{className:"absolute",ref:T,style:{cursor:v.game.config.cursor?"none":"auto",overflow:v.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},f.config.cursor&&H.createElement(ms,{src:f.config.cursor,width:f.config.cursorWidth,height:f.config.cursorHeight}),H.createElement(rd,{show:Te&&d,key:y},H.createElement(Ur,null,H.createElement(ic,{state:v}),H.createElement(ac,{state:v}),H.createElement(sd,{state:v},H.createElement("div",{className:"w-full h-full absolute",style:{isolation:"isolate"},"data-element-type":"scene-group"},v.getSceneElements().map(I=>H.createElement(rs,{key:"scene-"+I.scene.getId(),state:v,elements:I}))),H.createElement(ad,{state:v}),v.getVideos().map((I,ae)=>H.createElement("div",{className:"w-full h-full absolute",key:"video-"+ae,"data-element-type":"video"},H.createElement(us,{gameState:v,video:I}))),v.getVfx().map(I=>H.createElement("div",{className:"w-full h-full absolute",key:"vfx-"+I.getId(),"data-element-type":"vfx",style:{zIndex:I.config.zIndex}},H.createElement(ps,{gameState:v,vfx:I})))),v.getSceneElements().map(I=>H.createElement(cs,{key:"scene-dialogs-"+I.scene.getId(),state:v,elements:I})),H.createElement(cd,{NvlComponent:f.config.nvlDialog}))),H.createElement(uc,{state:v}),H.createElement($a,null,u),H.createElement(hs,{gameState:v})))))}function rd({children:o,show:e}){return H.createElement(H.Fragment,null,e?o:null)}function sd({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?H.createElement(Cc,{state:o,camera:t},e):H.createElement(H.Fragment,null,e)}function ad({state:o}){let e=H.useRef(null);return Pt(()=>(o.stageTransition.registerOverlayHost(e.current),()=>{o.stageTransition.registerOverlayHost(null)}),[]),H.createElement("div",{className:"w-full h-full absolute pointer-events-none",ref:e,"data-element-type":"stage-transition-overlay-host"})}function cd({NvlComponent:o}){let{dialogs:e,state:t}=Wt(),i=L().getLiveGame().getGameState(),r=H.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(Ce.getCtx({gameState:i})),l=t.activeDialogId===s.id,u=l&&t.phase==="typing";return{entry:s,index:a,isActive:l,gameState:i,words:c,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return H.createElement(o,{dialogs:r})}import"client-only";import On from"react";function Fc({children:o,game:e}){return On.createElement(On.Fragment,null,On.createElement(ba,null,On.createElement(ga,{game:e},On.createElement(Wa,null,On.createElement(Ta,null,o)))))}var ld=(c=>(c.image="narraleaf:image",c.text="narraleaf:text",c.layer="narraleaf:layer",c.scene="narraleaf:scene",c.video="narraleaf:video",c.vfx="narraleaf:vfx",c.camera="narraleaf:camera",c.puppet="narraleaf:puppet",c))(ld||{});import ud from"clsx";import Tt,{useEffect as Vc,useRef as pd,useState as dd}from"react";import{motion as md,useIsPresent as fd}from"motion/react";var hd={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function gd({children:o,initial:e,transition:t,...n}){let i=L(),r=Ct(),{ratio:s}=he(),[a]=ln(oe.Preferences.showDialog),c=pd(null),[l]=vn("nextAction"),u=fd(),[d,p]=dd(null);function h(){r.config.gameState.isAdvanceSuspended()||r.requestComplete()}return Vc(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
62
|
-
at Say.tsx: onElementClick`);return}let g=y=>{y.repeat||r.config.gameState.isAdvanceSuspended()||i.keyMap.match("nextAction",y.key)&&r.requestComplete()};window.addEventListener("keydown",g);let m=r.events.on(Me.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",g),m.cancel()}},[r,l]),Vc(()=>{let g=i.preference.onPreferenceChange(oe.Preferences.autoForward,m=>{m&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{g.cancel()}},[r]),Tt.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},Tt.createElement("div",{className:ud("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:h,style:{...Mi(i.config.useAspectScale,{maxWidth:i.config.dialogWidth,maxHeight:i.config.dialogHeight,transform:`scale(${s.state.scale})`,transformOrigin:"bottom left",width:i.config.width,height:i.config.height})},ref:c},Tt.createElement(zr,{value:d},Tt.createElement(md.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)),Tt.createElement("div",{"data-element-type":"dialog-overlay",className:"absolute inset-0 pointer-events-none",ref:p})))}function Oc({children:o,...e}){let t=Ct();return!t.config.action.sentence||!t.config.action.words?null:Tt.createElement(gd,{...e},o)}var cp=Oc;function Uc(){return Tt.createElement(Oc,null,Tt.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},Tt.createElement(Ir,null),Tt.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},Tt.createElement(Qt,null),Tt.createElement(un,{...hd}))))}var gi={say:Uc,menu:Ac,notification:Ic,nvlDialog:Kr};var Uo=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 yi=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 Wc=(e=>(e.game="game",e))(Wc||{}),_e=class _e{constructor(e){this.hooks=new Di;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new oi(_e.DefaultPreference);this.audioBuses=new Yn(()=>this.config.audioBuses??[],Js(this.preference));this.keyMap=new yi({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new Y;this.puppetBackends=new Go;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=$(_e.DefaultConfig,e),this.plugins=new Uo(this),this.router=new cn(this)}configure(e){let[t,n]=Us(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=$(this.config,t),Object.prototype.hasOwnProperty.call(t,"audioBuses")&&this.audioBuses.invalidate(),this.getLiveGame().getGameState()?.events.emit(E.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(_e.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(_e.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(_e.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(_e.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(_e.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(_e.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 Mt(this)}};_e.defaultSettings={volume:1},_e.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},_e.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"},_e.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:gi.notification,menu:gi.menu,dialog:gi.say,nvlDialog:gi.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100,audioBuses:[]},_e.GameSettingsNamespace=Wc,_e.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var oe=_e;var Wo=class Wo extends j{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===te.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===te.doAsync){if(r.length===0)return super.executeAction(t,n);let s=Wo.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===te.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===te.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===te.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===te.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let c=Ze.createCountLoop(t.game.getLiveGame(),a,this.checkActionChain(s));return t.logger.debug("ControlAction","repeat",s,a),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===te.while){let[s,a]=this.contentNode.getContent();if(s.length===0)return super.executeAction(t,n);if(!a.evaluate({gameState:t}).value)return super.executeAction(t,n);let c=Ze.createConditionLoop(t.game.getLiveGame(),a,this.getId(),this.checkActionChain(s));return t.logger.debug("ControlAction","while",s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===te.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===te.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=S.delay(s):S.isAwaitable(s)?a=s:a=S.fromPromise(s);let c=new S,l=new we(a);return t.timelines.attachTimeline(l),a.then(()=>{c.resolve({type:this.type,node:this.contentNode.getChild()})}),c.onSkipControllerRegister(u=>{u.onAbort(()=>{l.abort()})}),c}else if(this.type===te.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new S,a=new S,c=new we(a);t.timelines.attachTimeline(c);let l=t.game.preference,u=l.getPreference(oe.Preferences.autoForward),d=l.getPreference(oe.Preferences.gameSpeed),p=u?t.game.config.autoForwardDelay/d:null,h=!1,g=null,m=null,y=null,A=()=>{m?.cancel(),y?.cancel(),g&&(clearTimeout(g),g=null)},f=()=>{h||(h=!0,A(),a.resolve())};return m=t.events.on(E.EventTypes["event:state.player.stageClick"],f),y=t.events.on(E.EventTypes["event:state.player.skip"],f),p!==null&&(g=setTimeout(f,p)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(v=>{v.onAbort(()=>{h||(h=!0,A(),c.abort())})}),s}else{if(this.type===te.label)return super.executeAction(t,n);if(this.type===te.jump){let s=this._jumpTarget;if(!s){let[l]=this.contentNode.getContent();throw new Fe(`Jump target label "${l}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),c=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(l,u)},[c]),a.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===te.break||this.type===te.waitForClick||this.type===te.label||this.type===te.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===te.break)return super.stringifyWithContent("Control","break");if(this.type===te.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===te.label||this.type===te.jump){let[a]=this.contentNode.getContent(),c=this.type===te.label?"label":"jump";return super.stringifyWithContent("Control",`${c}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};Wo.ActionTypes=te;var ie=Wo;var je=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(ie.ActionTypes.do,t)}doAsync(t){return this.push(ie.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(ie.ActionTypes.any,t)}all(t){return this.pushUnchained(ie.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(ie.ActionTypes.allAsync,t)}repeat(t,n){return this.pushUnchained(ie.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=q.from(t);return this.pushWithLambda(ie.ActionTypes.while,n,i)}breakLoop(){let t=new ie(this.chain(),ie.ActionTypes.break,new C().setContent([]));return this.chain(t)}sleep(t){return this.push(ie.ActionTypes.sleep,[],t)}waitForClick(){let t=new ie(this.chain(),ie.ActionTypes.waitForClick,new C().setContent([]));return this.chain(t)}label(t){let n=new ie(this.chain(),ie.ActionTypes.label,new C().setContent([t]));return this.chain(n)}jump(t){let n=new ie(this.chain(),ie.ActionTypes.jump,new C().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new ie(this.chain(),t,new C().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new ie(this.chain(),t,new C().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new ie(this.chain(),t,new C().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?qt.say(n).getActions():ze.toActions([n]))}};var z=class z extends ut{static get DefaultUserConfig(){return z._defaultUserConfig??(z._defaultUserConfig=new K({name:"(anonymous)",autoInit:!0,src:z.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...X.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 w.isStaticImageData(t)?w.srcToURL(t):w.isColor(t)?t:w.isImageSrc(t)?w.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&&!w.isImageSrc(e)&&!w.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)&&(w.isImageSrc(t)||w.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)?w.isStaticImageData(e.state.currentSrc)?w.srcToURL(e.state.currentSrc):w.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 je,n=>{if(w.isImageSrc(e)||w.isColor(e)){if(w.isColor(e)&&!this.config.isBackground)throw new Error("Color src is not allowed for non-background image");return n.chain(this._setSrc(n,e,t))}else{let i=new ve(n,ve.ActionTypes.setAppearance,new C().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new je,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:X.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=z.StateSerializer.deserialize(e.state),this.transformState=X.deserialize(e.transformState),this}_applyTransition(e,t){return new Re(this.chain(),ge.applyTransition,new C().setContent([e,t]))}_init(e,t){return new Re(this.chain(),ge.init,new C().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new ve(this.chain(),ve.ActionTypes.initWearable,new C().setContent([e]))}_flush(){return new ve(this.chain(),ve.ActionTypes.flush,new C)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!z.isTagSrc(this))throw new Error(`Tag not defined
|
|
63
|
-
Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),i=new Map,r=[];this.config.src.groups.forEach(a=>{i.set(a,null)});let s=a=>{a.forEach(c=>{let l=n.get(c);l&&i.set(l,c)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let c=i.get(a);if(!c)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(c)}),r}_setAppearanceSync(e){if(w.isImageSrc(e)||w.isColor(e)){if(w.isColor(e)&&!this.config.isBackground)throw new
|
|
60
|
+
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(T)),r.get(T)||T}let{transformRef:u,transitionRefs:d,transitionTask:p,initDisplayable:h,applyTransition:f,applyTransform:m,updateStyleSync:y,flush:b,deps:v}=zt({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:T=>{if(c)return(T?T.task.resolve:[null]).map(D=>D&&typeof D=="function"?{style:Lp}:{style:Ep(o.state.darkness)});let A=T?T.transition._getCurrentSrc():Dp(o);return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:w.isColor(A)?w.colorToString(A):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:w.isImageSrc(A)?w.srcToURL(A):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:T=>T.src?{...T,src:l(T.src)}:T});bt(o,{createWearable:T=>{i(A=>[...A,T])},disposeWearable:T=>{i(A=>A.filter(P=>P.getId()!==T.getId()))},initDisplayable:h,applyTransform:m,applyTransition:f,events:t,updateStyleSync:y,flush:b},[...v]);let g=Tc((T,A)=>{a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${T}px`,height:`${A}px`}))},[t]),C=Tc(()=>{t.emit("event:image.onLoad")},[t]);return Dt.createElement(kp.div,{ref:u,className:"absolute w-max h-max","data-element-type":"image"},Dt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},c?d.map(([T,A],P)=>{let D=p?p.task.resolve[P]:null;if(D&&typeof D=="function")return Dt.createElement(Fo,{key:A,ref:T,autoFit:o.config.autoFit});let W=D?D.key==="target"?p.transition._getTargetLayers():p.transition._getPrevLayers():c;return Dt.createElement(Cc,{key:A,ref:T,src:W||c,autoFit:o.config.autoFit,resolveSrc:l,onSizeChanged:P===0?g:void 0,onLoad:P===0?C:void 0})}):d.map(([T,A],P)=>Dt.createElement(Fo,{key:A,ref:T,autoFit:o.config.autoFit,onSizeChanged:P===0?g:void 0,onLoad:P===0?C:void 0})),Dt.createElement("div",{className:Ac("w-full h-full top-0 left-0 absolute")},n.map(T=>Dt.createElement("div",{className:Ac("w-full h-full relative"),key:"wearable-"+T.getId()},Dt.createElement(xc,{image:T,state:e}))))))}var xc=Dt.memo(Rp),wc=xc;import Uo,{useEffect as Pc,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 kc(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 Oo=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]=ae(),{cacheManager:n}=Bt(),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:c,initDisplayable:l,applyTransform:u,applyTransition:d,updateStyleSync:p,deps:h}=zt({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`}}]});bt(e,{initDisplayable:l,applyTransform:u,applyTransition:d,updateStyleSync:p,flush:t},[...h]),Pc(()=>{let y=i.current;if(!y)return;let b=o.game,v=e.config.backend,g=b.getPuppetBackend(v);if(!g)return e._setStatus("missing-backend"),b.getPuppetBackendRegistry().reportMissing(v,A=>{o.logger.warn("Puppet",A)}),()=>{e._setStatus("unmounted")};let C;try{C=g.mount(y,{src:e.config.src,options:e.config.options,size:s.current,resolveSrc:m,resolveSibling:A=>m(kc(e.config.src,A)),warn:(A,P)=>{o.logger.warn("Puppet",A,P)}})}catch(A){return e._setStatus("error"),o.logger.error("Puppet",`Backend "${v}" threw while mounting "${e.config.src}"`,A),()=>{e._setStatus("unmounted")}}let T=!1;return e._attachInstance(C),e._setStatus("loading"),Promise.resolve().then(()=>e._applyState()).then(()=>!T&&typeof C.ready=="function"?C.ready():void 0).then(()=>{T||e._setStatus("ready")}).catch(A=>{T||(e._setStatus("error"),o.logger.error("Puppet",`Backend "${v}" failed to load "${e.config.src}"`,A))}),()=>{T=!0,e._attachInstance(null),e._setStatus("unmounted");try{C.dispose()}catch(A){o.logger.error("Puppet",`Backend "${v}" threw while disposing`,A)}}},[]);let f=os(r);Pc(()=>{let y=f.current;if(y.width===r.width&&y.height===r.height)return;f.current=r;let b=e._getInstance();if(!(!b||typeof b.resize!="function"))try{b.resize(r)}catch(v){o.logger.error("Puppet",`Backend "${e.config.backend}" threw while resizing`,v)}},[r]);function m(y){return w.isDataURI(y)?y:n.get(y)||y}return Uo.createElement(Wt.Div,{"data-element-type":"puppet"},Uo.createElement(Wt.mDiv,{tag:"puppet.container",color:"blue",border:"dashed",ref:a,className:"absolute"},c.map(([y,b])=>Uo.createElement("div",{key:b,ref:y,className:e.config.className},Uo.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 hi.createElement(hi.Fragment,null,e.map(t=>{if(t instanceof gn)return hi.createElement(ns,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof I)return hi.createElement(wc,{state:o,image:t,key:"image-"+t.getId()});if(t instanceof kt)return hi.createElement(rs,{state:o,puppet:t,key:"puppet-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Wo,{useEffect as Fp}from"react";import{motion as Vp}from"motion/react";function Ec({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=zt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return bt(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),Fp(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Wo.createElement(Wo.Fragment,null,Wo.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(([u,d])=>Wo.createElement("div",{className:"relative w-full h-full",ref:u,key:d},t))))}async function Dc(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 Op from"clsx";import{useEffect as as,useRef as Up}from"react";import cs from"react";function ls({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(gt.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),as(()=>(n.events.emit(gt.EventTypes["event:scene.mount"]),o.events.emit(E.EventTypes["event:state.scene.mount"],n),o.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(gt.EventTypes["event:scene.unmount"]),o.events.emit(E.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),bt(n,{setBackgroundMusic(s,a){return Dc(o,n,s,a)}}),cs.createElement("div",{className:Op(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])=>cs.createElement(Ec,{state:o,layer:s,key:s.getId()},cs.createElement(ss,{state:o,displayable:a}))))}import{AnimatePresence as zp}from"motion/react";import{useEffect as $p,useReducer as jp,useRef as gi}from"react";import Wp from"clsx";import $t,{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([]),c=us(f=>(a.current.push(f),a.current.indexOf(f)),[]),l=us(f=>{let m=a.current.indexOf(f);m!==-1&&a.current.splice(m,1)},[]),u=us(f=>a.current.indexOf(f),[]),d=s.config.menu,p=Bp(()=>e.map(f=>({...f,words:f.prompt.evaluate(Ce.getCtx({gameState:n}))})),[]);function h(f){t(f)}return $t.createElement($t.Fragment,null,$t.createElement(Rr,{value:{evaluated:p,choose:h,gameState:n}},$t.createElement(Mr,{value:{register:c,unregister:l,getIndex:u}},$t.createElement(Ut,{className:"absolute"},r&&o&&$t.createElement(li,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),$t.createElement(Wt.Div,{color:"green",border:"dashed",className:Wp("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},$t.createElement(d,{items:p.map((f,m)=>m)})))))}function Lc({items:o}){return $t.createElement(fo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>$t.createElement(wo,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import qp from"clsx";import yi from"react";var Yp=120;function ds({state:o,className:e,elements:t}){let{scene:n,texts:i,menus:r}=t,s=gi(!1),a=gi({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),c=gi([]),l=gi(null),u=gi(null),[,d]=jp(m=>m+1,0),p=()=>{u.current&&(clearTimeout(u.current),u.current=null)},h=()=>{let m=l.current;if(!m)return;let y=a.current;m.forEach(({slot:b,presenceKey:v})=>{y.slotKeys.get(b)===v&&y.slotKeys.delete(b),y.exitingKeys.add(v)}),l.current=null,u.current=null,c.current=[],d()};$p(()=>()=>{p()},[]);let f=(()=>{let m=a.current,y=i.length>0?i.map(({action:g,onClick:C},T)=>({action:g,slot:T,useTypeEffect:!s.current,onFinished:A=>{A!==void 0&&(s.current=A),C(),o.events.emit(E.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):r.flatMap((g,C)=>{if(!g.action.prompt||!g.action.words)return[];let T=m.menuPromptIds.get(g);return T||(T=`menu-prompt-${n.getId()}-${m.nextKey++}`,m.menuPromptIds.set(g,T)),[{action:{sentence:g.action.prompt,words:g.action.words,character:null,id:T},slot:C,useTypeEffect:!1}]});if(y.length===0)return!l.current&&c.current.length>0&&(l.current=c.current.map(g=>({...g,active:!1}))),l.current&&!u.current&&(u.current=setTimeout(h,Yp)),l.current??[];p(),l.current=null;let b=new Set(y.map(({slot:g})=>g));for(let[g,C]of Array.from(m.slotKeys))b.has(g)||(m.exitingKeys.add(C),m.slotKeys.delete(g));let v=y.map(({slot:g,...C})=>{let T=m.slotKeys.get(g);return(!T||m.exitingKeys.has(T))&&(T=`say-${n.getId()}-${m.nextKey++}`,m.slotKeys.set(g,T)),{...C,presenceKey:T,slot:g,active:!0}});return c.current=v,v})();return yi.createElement("div",{className:qp(e,"w-full h-full absolute"),"data-element-type":"scene-dialogs"},yi.createElement(zp,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{a.current.exitingKeys.clear()}},f.map(({action:m,onFinished:y,presenceKey:b,active:v,useTypeEffect:g})=>yi.createElement(li,{gameState:o,key:b,action:m,active:v,onFinished:y,useTypeEffect:g}))),r.map(({action:m,onClick:y},b)=>yi.createElement("div",{key:"menu-"+b,"data-element-type":"menu"},yi.createElement(ps,{state:o,prompt:m.prompt,choices:m.choices,renderPrompt:!m.prompt,afterChoose:v=>{s.current=!1,y(v),o.stage.next()},words:m.words}))))}import dn,{useEffect as Qp,useRef as ms}from"react";import{motion as Xp}from"motion/react";function Rc({state:o,camera:e,children:t}){let n=ms(null),i=ms(null),r=ms(null),{transformRef:s,transitionRefs:a,initDisplayable:c,applyTransition:l,applyTransform:u,updateStyleSync:d,deps:p}=zt({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,companionRefs:[{ref:n,project:Sa},{ref:i,project:ya},{ref:r,project:va}],transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center",overflow:"hidden"}}]});return bt(e,{initDisplayable:c,applyTransition:l,applyTransform:u,updateStyleSync:d},[...p]),Qp(()=>(o.logger.debug("Camera","Camera mounted",e.getId()),()=>{o.logger.debug("Camera","Camera unmounted",e.getId())}),[]),dn.createElement(dn.Fragment,null,dn.createElement(Xp.div,{className:"absolute w-full h-full",ref:s,"data-element-type":"camera"},a.map(([h,f])=>dn.createElement("div",{className:"relative w-full h-full",ref:h,key:f},t))),dn.createElement("div",{className:"absolute w-full h-full","data-element-type":"camera-lens",style:{pointerEvents:"none"}},dn.createElement("div",{className:"absolute w-full h-full",ref:n,"data-element-type":"camera-lens-vignette"}),dn.createElement("div",{className:"absolute w-full h-full",ref:i,"data-element-type":"camera-lens-shutter-top"}),dn.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 Ic}from"react";function Mc(o){let e=Ic(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=Ic(()=>{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}=Mc(t);fs(()=>o.events.depends([o.events.on(E.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,c=new Set,l=()=>new k(`Failed to add event listener, ref is not available
|
|
61
|
+
at Video.tsx: useEffect`),u=h=>{a||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw l();n()},hide:()=>{if(!t.current)throw l();i()},play:()=>{if(!t.current)throw l();let f=t.current;return h||f.error?(o.logger.error("NarraLeaf-React: Video","Cannot play a video whose source failed to load: "+e.config.src),Promise.resolve()):(f.currentTime=0,new Promise(m=>{let y=!1,b=null,v=[],g=()=>{y||(y=!0,c.delete(g),b&&b(),v.forEach(C=>C()),m())};c.add(g),b=o.schedule(({retry:C})=>{if(y)return;if(f.readyState<3){let D=()=>{f.removeEventListener("loadeddata",D),C()};f.addEventListener("loadeddata",D),v.push(()=>f.removeEventListener("loadeddata",D));return}let T=()=>g(),A=()=>g(),P=()=>{o.logger.error("NarraLeaf-React: Video","Video playback error: "+e.config.src),g()};f.addEventListener("ended",T),f.addEventListener("stopped",A),f.addEventListener("error",P),v.push(()=>{f.removeEventListener("ended",T),f.removeEventListener("stopped",A),f.removeEventListener("error",P)}),f.play().catch(D=>{o.logger.error("Failed to play video: "+D),g()})},10)}))},pause:()=>{if(!t.current)throw l();t.current.pause()},resume:()=>{if(!t.current)throw l();return t.current.play().catch(f=>{o.logger.error("Failed to resume video: "+f)})},stop:()=>{if(!t.current)throw l();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:f=>{if(!t.current)throw l();t.current.currentTime=f}}))},d=()=>u(!1),p=()=>{o.logger.error("NarraLeaf-React: Video",`Failed to load video source: ${e.config.src}`+(s.error?` (media error code ${s.error.code})`:"")),u(!0)};return s.addEventListener("canplay",d),s.addEventListener("error",p),s.readyState>=3?u(!1):s.error&&p(),()=>{s.removeEventListener("canplay",d),s.removeEventListener("error",p),c.forEach(h=>h()),s.currentTime>0&&s.pause(),o.isStateMounted(e)&&o.unMountState(e)}},[o,e]);function r(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return 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 Nc={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"&&Nc[e]?Nc[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,c=new Set,l=new Set,u=[],d=C=>{n.style.transition="",n.style.opacity=String(C)},p=()=>{n.play().catch(C=>{o.logger.weakWarn("NarraLeaf-React: Vfx","Failed to play vfx video: "+C)})},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(C=>{let T=!1,A=()=>D(),P=()=>{o.logger.error("NarraLeaf-React: Vfx","Failed to load vfx source: "+e.config.src),D()},D=()=>{T||(T=!0,l.delete(D),n.removeEventListener("loadeddata",A),n.removeEventListener("error",P),C())};l.add(D),n.addEventListener("loadeddata",A),n.addEventListener("error",P),(n.readyState>=2||n.error)&&D()}),f=(C,T,A)=>{let P=T?.duration??0,D=++s;return A.instant||P<=0?(d(C),Promise.resolve()):new Promise(W=>{let pe=!1,V=null,fe=()=>{pe||(pe=!0,l.delete(fe),V!==null&&clearTimeout(V),s===D&&t.current&&d(C),W())};l.add(fe),n.style.transition=`opacity ${P}ms ${nd(o,T?.easing)}`,n.offsetWidth,n.style.opacity=String(C),V=setTimeout(fe,P)})},m=C=>{r||(r=!0,i=C,o.mountState(e,{show:async T=>{a=!0;let A={instant:!1};c.add(A);try{if(await h(),!t.current)return;e.state.paused||p(),await f(e.config.opacity,T,A)}finally{c.delete(A)}},hide:async T=>{a=!0;let A={instant:!1};c.add(A);try{await f(0,T,A),t.current&&n.pause()}finally{c.delete(A)}},pause:()=>{n.pause()},resume:()=>{p()},setRate:T=>{n.playbackRate=T}}),e.state.display&&u.push(o.schedule(()=>{!a&&t.current&&d(e.config.opacity)},0)))},y=()=>m(!1),b=()=>{o.logger.error("NarraLeaf-React: Vfx",`Failed to load vfx source: ${e.config.src}`+(n.error?` (media error code ${n.error.code})`:"")),m(!0)},v=o.events.on(E.EventTypes["event:state.player.skip"],()=>{c.size===0&&l.size===0||(c.forEach(C=>{C.instant=!0}),[...l].forEach(C=>C()),o.logger.log("NarraLeaf-React: Vfx","Fade skipped"))}),g=()=>{document.visibilityState==="visible"&&e.state.display&&!e.state.paused&&t.current&&p()};return document.addEventListener("visibilitychange",g),n.style.opacity="0",n.playbackRate=e.config.playbackRate,e.config.muted||o.logger.weakWarn("NarraLeaf-React: Vfx","Vfx is not muted; autoplay may be rejected by the browser. (src: "+e.config.src+")"),e.state.display&&!e.state.paused&&p(),n.addEventListener("canplay",y),n.addEventListener("error",b),n.readyState>=3?m(!1):n.error&&b(),()=>{n.removeEventListener("canplay",y),n.removeEventListener("error",b),document.removeEventListener("visibilitychange",g),v.cancel(),u.forEach(C=>C()),[...l].forEach(C=>C()),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,mixBlendMode:e.config.blendMode,pointerEvents:"none"}})}import id from"clsx";import od,{useCallback as rd,useEffect as Bo,useRef as sd}from"react";function ys({children:o,className:e,gameState:t}){let{ratio:n}=me(),i=R(),[r]=ae(),s=sd(null),a=i.config.minWidth,c=i.config.minHeight,l=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,c),r()},[r,t.logger,c,a,n]);return Bo(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Bo(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Bo(()=>{let u=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(u)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Bo(()=>t.events.on(E.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),od.createElement(rc,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:id(e),onUpdate:l},o)}import Gc,{useEffect as ad,useRef as cd,useState as Hc}from"react";function vs({src:o,width:e,height:t}){let[n,i]=Hc({x:0,y:0}),[r,s]=Hc(!1),a=cd(null),{ratio:c}=me();return ad(()=>{let l=u=>{if(a.current){let d=a.current.getBoundingClientRect(),p=u.clientX-d.left,h=u.clientY-d.top;i({x:p,y:h}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),Gc.createElement(Ut,{ref:a,className:"overflow-hidden absolute"},Gc.createElement("img",{src:o,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:r?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import Fc from"react";import Jt from"react";function Ss({error:o,errorInfo:e}){return R().config.app.debug?Jt.createElement("div",{className:"text-left"},Jt.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),Jt.createElement("p",{className:"text-red-700"},"Message: ",o.message),Jt.createElement("pre",null,"Error Stack: ",o?.stack),Jt.createElement("pre",null,"Component Stack: ",e?.componentStack),Jt.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):Jt.createElement("div",{className:"bg-white w-full h-full"},Jt.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),Jt.createElement("p",null,"Please contact the game developer for further assistance."))}var Ko=class extends Fc.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?Fc.createElement(Ss,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import Uc from"clsx";import F,{useEffect as Lt,useReducer as Wc,useState as Un}from"react";import{flushSync as Bc}from"react-dom";import{useRef as ld}from"react";import{useEffect as ud}from"react";function Vc({gameState:o}){let e=ld(null);return ud(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(E.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import vi,{useEffect as pd}from"react";function Ts({gameState:o}){let[e]=ae(),{ratio:t}=me(),n=o.notificationMgr;pd(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return vi.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"},vi.createElement(i,{notifications:n.toArray()}))}function Oc({notifications:o}){return vi.createElement(Po,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>vi.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},vi.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function Kc({story:o=oi.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:u,active:d=!0}){let[p,h]=Wc(M=>M+1,0),[f,m]=Wc(M=>M+1,0),[y,b]=Un(0),v=R(),[g]=Un(()=>new E(v,{update:h,forceUpdate:()=>{g.logger.weakWarn("Player","force update"),Bc(()=>{h()})},forceRemount:()=>{g.logger.weakWarn("Player","force remount"),Bc(()=>{b(M=>M+1),h()})},next:ke})),C=F.createRef(),T=F.createRef(),[A,P]=Un(!1),D=F.useRef(!1),W=F.useRef(null),pe=F.useRef(null),{preloaded:V}=Bt(),[fe,Ue]=Un(!1),Ze=F.useRef(!1),[We,pt]=Un(!1),Ct=F.useRef(!1),L=F.useRef(null),ee=F.useRef(!1),[he]=Un(new Map);function be(M){return{game:v,gameState:g,liveGame:v.getLiveGame(),storable:v.getLiveGame().getStorable(),scene:M}}function ke(){let M=()=>{he.forEach(O=>O.cancel())};if(g.rollLock.isLocked())return;M();let Q=!1,ge=0;for(;!Q;){if(ge++>v.config.maxStackModelLoop)throw new k("Max stack model loop reached");let O=v.getLiveGame().next();if(!O){if(v.getLiveGame().stackModel&&!v.getLiveGame().stackModel.isEmpty())continue;break}if(S.isAwaitable(O)){if(W.current===O)break;W.current=O,O.onSettled(()=>{O.isFailed()||(W.current===O&&(W.current=null),ke())}),O.onFailed(St=>{W.current===O&&(W.current=null),g.logger.error("Player",St)}),Q=!0;break}if(O instanceof xn){if(pe.current===O)break;pe.current=O,O.nextUnlock().then(()=>{pe.current===O&&(pe.current=null),ke()}),Q=!0;break}if(Xe.isCalledActionResult(O)&&O.wait&&Xe.isStackModelsAwaiting(O.wait.type,O.wait.stackModels)){if(W.current===O)break;if(W.current=O,O.wait){let St=Xe.executeStackModelGroup(O.wait.type,O.wait.stackModels);St.then(()=>{W.current===O&&(W.current=null),ke()}),St.onFailed(te=>{W.current===O&&(W.current=null),g.logger.error("Player",te)})}Q=!0;break}g.handle(O)}g.stage.update()}Lt(()=>{g.audioManager.initialize()},[]),Lt(()=>(v.getLiveGame().setGameState(g),o&&!v.getLiveGame().isPlaying()&&v.getLiveGame().loadStory(o),o?.entryScene&&!g.getPreloadingScene()&&!g.getLastScene()&&g.preloadScene(o.entryScene),g.playerCurrent=C.current,g.mainContentNode=T.current,()=>{v.getLiveGame().setGameState(void 0),g.playerCurrent=null}),[v,o]),Lt(()=>rt(()=>{P(!0);let M=g.getLastScene(),Q=[];M?Q.push(M.events.once("event:scene.mount",()=>{g.stage.next()}).cancel):g.stage.next();let ge=g.events.on(E.EventTypes["event:state.end"],()=>{c&&c({game:v,gameState:g,liveGame:v.getLiveGame(),storable:v.getLiveGame().getStorable()})});return g.stage.update(),()=>{M&&Q.forEach(O=>O()),ge.cancel()}}),[]),Lt(()=>rt(()=>{A&&i&&!D.current&&(D.current=!0,g.stage.forceUpdate(),v.hooks.trigger("init",[]),i({game:v,gameState:g,liveGame:v.getLiveGame(),storable:v.getLiveGame().getStorable()}))}),[A]),Lt(()=>rt(()=>{if(fe&&s&&!Ze.current){Ze.current=!0;let M=L.current||g.getLastScene()||g.getPreloadingScene(),Q=be(M);s(Q)}}),[fe]),Lt(()=>rt(()=>{if(We&&!Ct.current){Ct.current=!0;let M=L.current||g.getLastScene()||g.getPreloadingScene(),Q=be(M);v.markPreloadComplete(Q)&&r&&r(Q)}}),[We]),Lt(()=>g.events.on(E.EventTypes["event:state.scene.mount"],M=>{L.current||(L.current=M,m())}).cancel,[]),Lt(()=>{if(!We||!d||ee.current||v.isFirstSceneReady())return;let M=L.current||g.getLastScene();if(!M)return;let Q=null,ge=null,O=!1;ee.current=!0;let St=()=>{O=!0,ee.current=!1;let te=be(M);v.markFirstSceneReady(te)&&a&&a(te)};return typeof requestAnimationFrame=="function"?Q=requestAnimationFrame(()=>{ge=setTimeout(St,0)}):ge=setTimeout(St,0),()=>{O||(ee.current=!1,Q!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Q),ge!==null&&clearTimeout(ge))}},[d,f,p,We]),Lt(()=>V.events.depends([V.events.on(qe.EventTypes["event:preloaded.ready"],()=>{Ue(!0),g.stage.update(),o&&v.getLiveGame().isPlaying()&&ke()}),V.events.on(qe.EventTypes["event:preloaded.complete"],()=>{pt(!0)})]).cancel,[]),Lt(()=>{g.flushDep=p},[p]);let Pe=e||v.config.width,U=t||v.config.height;return F.createElement(Ko,{onError:l},F.createElement("div",{style:{width:typeof Pe=="number"?`${Pe}px`:Pe,height:typeof U=="number"?`${U}px`:U},className:Uc(n,"__narraleaf_content-player"),ref:C,tabIndex:0},F.createElement(ys,{className:Uc("flex-grow overflow-auto"),gameState:g},F.createElement(Xr,{gameState:g}),F.createElement(Vc,{gameState:g}),F.createElement(Ut,{className:"absolute",ref:T,style:{cursor:g.game.config.cursor?"none":"auto",overflow:g.game.config.showOverflow?"visible":"hidden",isolation:"isolate"}},v.config.cursor&&F.createElement(vs,{src:v.config.cursor,width:v.config.cursorWidth,height:v.config.cursorHeight}),F.createElement(dd,{show:fe&&d,key:y},F.createElement(zr,null,F.createElement(pc,{state:g}),F.createElement(hc,{state:g}),F.createElement(md,{state:g},F.createElement("div",{className:"w-full h-full absolute",style:{isolation:"isolate"},"data-element-type":"scene-group"},g.getSceneElements().map(M=>F.createElement(ls,{key:"scene-"+M.scene.getId(),state:g,elements:M}))),F.createElement(fd,{state:g}),g.getVideos().map((M,Q)=>F.createElement("div",{className:"w-full h-full absolute",key:"video-"+Q,"data-element-type":"video"},F.createElement(hs,{gameState:g,video:M}))),g.getVfx().map(M=>F.createElement("div",{className:"w-full h-full absolute",key:"vfx-"+M.getId(),"data-element-type":"vfx",style:{zIndex:M.config.zIndex}},F.createElement(gs,{gameState:g,vfx:M})))),g.getSceneElements().map(M=>F.createElement(ds,{key:"scene-dialogs-"+M.scene.getId(),state:g,elements:M})),F.createElement(hd,{NvlComponent:v.config.nvlDialog}))),F.createElement(vc,{state:g}),F.createElement(_a,null,u),F.createElement(Ts,{gameState:g})))))}function dd({children:o,show:e}){return F.createElement(F.Fragment,null,e?o:null)}function md({state:o,children:e}){let t=o.getLiveGame().story?.camera??null;return t?F.createElement(Rc,{state:o,camera:t},e):F.createElement(F.Fragment,null,e)}function fd({state:o}){let e=F.useRef(null);return Lt(()=>(o.stageTransition.registerOverlayHost(e.current),()=>{o.stageTransition.registerOverlayHost(null)}),[]),F.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=R().getLiveGame().getGameState(),r=F.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(Ce.getCtx({gameState:i})),l=t.activeDialogId===s.id,u=l&&t.phase==="typing";return{entry:s,index:a,isActive:l,gameState:i,words:c,useTypeEffect:u}}),[e,i,t.activeDialogId,t.phase]);return F.createElement(o,{dialogs:r})}import"client-only";import Wn from"react";function zc({children:o,game:e}){return Wn.createElement(Wn.Fragment,null,Wn.createElement(Da,null,Wn.createElement(xa,{game:e},Wn.createElement(Qa,null,Wn.createElement(Ea,null,o)))))}var gd=(c=>(c.image="narraleaf:image",c.text="narraleaf:text",c.layer="narraleaf:layer",c.scene="narraleaf:scene",c.video="narraleaf:video",c.vfx="narraleaf:vfx",c.camera="narraleaf:camera",c.puppet="narraleaf:puppet",c))(gd||{});import yd from"clsx";import At,{useEffect as $c,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=Pt(),{ratio:s}=me(),[a]=un(re.Preferences.showDialog),c=vd(null),[l]=Tn("nextAction"),u=bd(),[d,p]=Sd(null);function h(){r.config.gameState.isAdvanceSuspended()||r.requestComplete()}return $c(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
62
|
+
at Say.tsx: onElementClick`);return}let f=y=>{y.repeat||r.config.gameState.isAdvanceSuspended()||i.keyMap.match("nextAction",y.key)&&r.requestComplete()};window.addEventListener("keydown",f);let m=r.events.on(Ne.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keydown",f),m.cancel()}},[r,l]),$c(()=>{let f=i.preference.onPreferenceChange(re.Preferences.autoForward,m=>{m&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{f.cancel()}},[r]),At.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},At.createElement("div",{className:yd("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:h,style:{...Hi(i.config.useAspectScale,{maxWidth:i.config.dialogWidth,maxHeight:i.config.dialogHeight,transform:`scale(${s.state.scale})`,transformOrigin:"bottom left",width:i.config.width,height:i.config.height})},ref:c},At.createElement(Yr,{value:d},At.createElement(Td.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&u?{duration:0}:t},o)),At.createElement("div",{"data-element-type":"dialog-overlay",className:"absolute inset-0 pointer-events-none",ref:p})))}function jc({children:o,...e}){let t=Pt();return!t.config.action.sentence||!t.config.action.words?null:At.createElement(Cd,{...e},o)}var hp=jc;function qc(){return At.createElement(jc,null,At.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},At.createElement(Hr,null),At.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},At.createElement(Xt,null),At.createElement(pn,{...Ad}))))}var Si={say:qc,menu:Lc,notification:Oc,nvlDialog:qr};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 Ti=class{constructor(e={}){this.keyMap=e;this.events=new q}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 Yc=(e=>(e.game="game",e))(Yc||{}),Je=class Je{constructor(e){this.hooks=new Ii;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new ai(Je.DefaultPreference);this.audioBuses=new Xn(()=>this.config.audioBuses??[],na(this.preference));this.keyMap=new Ti({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new q;this.puppetBackends=new Oo;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=z(Je.DefaultConfig,e),this.plugins=new zo(this),this.router=new ln(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=z(this.config,t),Object.prototype.hasOwnProperty.call(t,"audioBuses")&&this.audioBuses.invalidate(),this.getLiveGame().getGameState()?.events.emit(E.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:Si.notification,menu:Si.menu,dialog:Si.say,nvlDialog:Si.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100,audioBuses:[]},Je.GameSettingsNamespace=Yc,Je.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var re=Je;var $o=class $o 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===ne.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===ne.doAsync){if(r.length===0)return super.executeAction(t,n);let s=$o.executeActionsAsync(t,r[0]);return t.timelines.attachTimeline(s),super.executeAction(t,n)}else if(this.type===ne.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===ne.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===ne.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===ne.repeat){let[s,a]=this.contentNode.getContent();if(a<=0||s.length===0)return super.executeAction(t,n);let c=Xe.createCountLoop(t.game.getLiveGame(),a,this.checkActionChain(s));return t.logger.debug("ControlAction","repeat",s,a),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===ne.while){let[s,a]=this.contentNode.getContent();if(s.length===0)return super.executeAction(t,n);if(!a.evaluate({gameState:t}).value)return super.executeAction(t,n);let c=Xe.createConditionLoop(t.game.getLiveGame(),a,this.getId(),this.checkActionChain(s));return t.logger.debug("ControlAction","while",s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[c]}}}else if(this.type===ne.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===ne.sleep){let[,s]=this.contentNode.getContent();if(t.isFastForwarding())return{type:this.type,node:this.contentNode.getChild()};let a;typeof s=="number"?a=S.delay(s):S.isAwaitable(s)?a=s:a=S.fromPromise(s);let c=new S,l=new xe(a);return t.timelines.attachTimeline(l),a.then(()=>{c.resolve({type:this.type,node:this.contentNode.getChild()})}),c.onSkipControllerRegister(u=>{u.onAbort(()=>{l.abort()})}),c}else if(this.type===ne.waitForClick){if(t.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let s=new S,a=new S,c=new xe(a);t.timelines.attachTimeline(c);let l=t.game.preference,u=l.getPreference(re.Preferences.autoForward),d=l.getPreference(re.Preferences.gameSpeed),p=u?t.game.config.autoForwardDelay/d:null,h=!1,f=null,m=null,y=null,b=()=>{m?.cancel(),y?.cancel(),f&&(clearTimeout(f),f=null)},v=()=>{h||(h=!0,b(),a.resolve())};return m=t.events.on(E.EventTypes["event:state.player.stageClick"],v),y=t.events.on(E.EventTypes["event:state.player.skip"],v),p!==null&&(f=setTimeout(v,p)),a.then(()=>{s.resolve({type:this.type,node:this.contentNode.getChild()})}),s.onSkipControllerRegister(g=>{g.onAbort(()=>{h||(h=!0,b(),c.abort())})}),s}else{if(this.type===ne.label)return super.executeAction(t,n);if(this.type===ne.jump){let s=this._jumpTarget;if(!s){let[l]=this.contentNode.getContent();throw new Ve(`Jump target label "${l}" was not resolved. This usually means the story was not constructed before playing.`)}let a=t.getLiveGame(),c=a.getStackModelForce().serialize();return t.actionHistory.push({action:this,stackModel:n.stackModel},l=>{let[u]=a.constructMaps();a.getStackModelForce().deserialize(l,u)},[c]),a.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===ne.break||this.type===ne.waitForClick||this.type===ne.label||this.type===ne.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===ne.break)return super.stringifyWithContent("Control","break");if(this.type===ne.waitForClick)return super.stringifyWithContent("Control","waitForClick");if(this.type===ne.label||this.type===ne.jump){let[a]=this.contentNode.getContent(),c=this.type===ne.label?"label":"jump";return super.stringifyWithContent("Control",`${c}(${a})`)}let r=this.contentNode,[s]=r.getContent();return super.stringifyWithContent("Control",s.map(a=>a.stringify(t,n,i)).join(";"))}};$o.ActionTypes=ne;var oe=$o;var je=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=j.from(t);return this.pushWithLambda(oe.ActionTypes.while,n,i)}breakLoop(){let t=new oe(this.chain(),oe.ActionTypes.break,new x().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 x().setContent([]));return this.chain(t)}label(t){let n=new oe(this.chain(),oe.ActionTypes.label,new x().setContent([t]));return this.chain(n)}jump(t){let n=new oe(this.chain(),oe.ActionTypes.jump,new x().setContent([t]));return this.chain(n)}push(t,n,...i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new x().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 x().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new oe(this.chain(),t,new x().setContent([r,i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?Yt.say(n).getActions():ze.toActions([n]))}};var K=class K extends ct{static get DefaultUserConfig(){return K._defaultUserConfig??(K._defaultUserConfig=new B({name:"(anonymous)",autoInit:!0,src:K.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...J.DefaultTransformState.getDefaultConfig()},{position:e=>N.tryParsePosition(e)}))}static getInitialSrc(e){if(this.isLayeredDefinition(e.src)||this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return w.isStaticImageData(t)?w.srcToURL(t):w.isColor(t)?t:w.isImageSrc(t)?w.srcToURL(t):K.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&&!w.isImageSrc(e)&&!w.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)&&(w.isImageSrc(t)||w.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:K.isLayeredSrc(e)?null:K.isTagSrc(e)&&e.config.src.resolve?K.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):K.isStaticSrc(e)?w.isStaticImageData(e.state.currentSrc)?w.srcToURL(e.state.currentSrc):w.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=>K.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(K.isLayerVariants(i))for(let r of Object.values(i))r!==null&&n.push(r);return n}static fromSrc(e){return new K({src:e})}constructor(e={}){super();let t=K.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 je,n=>{if(w.isImageSrc(e)||w.isColor(e)){if(w.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 x().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new je,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:K.StateSerializer.serialize(this.state),transformState:J.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=K.StateSerializer.deserialize(e.state),this.transformState=J.deserialize(e.transformState),this}_applyTransition(e,t){return new Ie(this.chain(),ye.applyTransition,new x().setContent([e,t]))}_init(e,t){return new Ie(this.chain(),ye.init,new x().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new Se(this.chain(),Se.ActionTypes.initWearable,new x().setContent([e]))}_flush(){return new Se(this.chain(),Se.ActionTypes.flush,new x)}reset(){return super.reset(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!K.isTagSrc(this))throw new Error(`Tag not defined
|
|
63
|
+
Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),i=new Map,r=[];this.config.src.groups.forEach(a=>{i.set(a,null)});let s=a=>{a.forEach(c=>{let l=n.get(c);l&&i.set(l,c)})};return s(e),s(t),this.config.src.groups.forEach(a=>{let c=i.get(a);if(!c)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);r.push(c)}),r}_setAppearanceSync(e){if(w.isImageSrc(e)||w.isColor(e)){if(w.isColor(e)&&!this.config.isBackground)throw new ie("Color src is not allowed for non-background image");this.state.currentSrc=e;return}if(!K.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
|
|
64
64
|
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
|
|
65
65
|
Wearable must be an Image with isWearable set to true
|
|
66
66
|
It seems like you are trying to add a non-wearable image to wearables
|
|
67
67
|
Image below violates the rule:
|
|
68
68
|
`+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?`
|
|
69
69
|
Tag "${e}" belongs to more than one group.`:"")+(t?`
|
|
70
|
-
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(
|
|
70
|
+
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 x().setContent([t]))}_setIsBackground(e){return Object.assign(this.config,{isBackground:e}),this}registerSrc(){let e=this.config.src;return e?.slots?K.getAllLayerSrc(this).forEach(t=>this.srcManager.registerRawSrc(t)):e?.resolve?this.srcManager.registerRawSrc(K.getSrcFromTags(e.defaults,e.resolve)):w.isImageSrc(this.state.currentSrc)&&this.srcManager.registerRawSrc(w.srcToURL(this.state.currentSrc)),this}static collectLayerGroups(e){let t=[],n=new Set;for(let i of e){if(!K.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 K.isLayeredDefinition(e)?{groups:K.collectLayerGroups(e.layers),defaults:[...e.defaults],resolve:null,slots:e.layers}:K.isTagDefinition(e)?{groups:e.groups,defaults:[...e.defaults],resolve:e.resolve,slots:null}:null}createImageConfig(e){let t=e.get();return K.DefaultImageConfig.create({...t,src:K.normalizeSrcDefinition(t.src)})}getInitialState(){return K.DefaultImageState.create().assign({currentSrc:K.getInitialSrc(this.userConfig.get())}).get()}getInitialTransformState(e){let[t]=e.extract(J.DefaultTransformState.keys());return new J(J.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(K.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
|
|
71
71
|
Tag "${r}" is conflicting with another tag
|
|
72
72
|
Error found in config.tag.defaults`);if(!n.has(r))throw new Error(`Tag not found
|
|
73
73
|
Tag "${r}" is not defined in tagDefinitions
|
|
74
|
-
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
|
|
75
|
-
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
|
|
74
|
+
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
|
|
75
|
+
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 x().setContent([t,n,i]))}};K.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",K.StateSerializer=new Qe,K._defaultUserConfig=null,K.DefaultImageConfig=new B({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),K.DefaultImageState=new B({currentSrc:K.DefaultImagePlaceholder,darkness:0});var I=K;var Te=class extends Ft{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)=>z(t(...n),this._srcToProps(this._prevSrc)))}asTarget(t){return super.asTarget((...n)=>z(t(...n),this._srcToProps(this._targetSrc)))}_srcToProps(t){if(this._isLayered()||this._detached)return{};if(w.isColor(t))return{src:I.DefaultImagePlaceholder,style:{backgroundColor:w.isRGBAColor(t)?w.RGBAColorToHex(t):t}};if(w.isImageSrc(t))return{src:w.srcToURL(t)};throw new ie("Image transition src cannot be identified, using: "+t)}};var bi=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 Ai=class Ai extends ${static resolveTagSrc(e,t){if(!I.isTagSrc(e)||!e.config.src.resolve)throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return I.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(I.isLayeredSrc(e))throw e._mixedSrcError();if(I.isStaticSrc(e))return w.isImageSrc(e.state.currentSrc)?w.srcToURL(e.state.currentSrc):e.state.currentSrc;if(I.isTagSrc(e)&&e.config.src.resolve)return I.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===dt.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===dt.setSrc){let n=this.contentNode.getContent()[0];if(w.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===dt.flush)return super.executeAction(e,t);if(this.type===dt.setAppearance){let[n,i]=this.contentNode.getContent();if(!I.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],c=()=>{this.callee.state.currentSrc=a};if(I.isLayeredSrc(this.callee)){if(e.logger.debug("Image - Set Appearance (layered)",s),i){let d=new S(m=>m).registerSkipController(new H(()=>super.executeAction(e,t)));i._setPrevLayers(I.getSrcURLs(this.callee))._setTargetLayers(I.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},c,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},c),e.stage.update(),e.getExposedState(this.callee)?.flush(),super.executeAction(e,t)}let l=this.callee.config.src.resolve;if(!l)throw this.callee._invalidSrcHandlerError();let u=I.getSrcFromTags(s,l);if(e.logger.debug("Image - Set Appearance",s,u),i){let d=new S(m=>m).registerSkipController(new H(()=>super.executeAction(e,t)));i._setPrevSrc(Ai.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},c,[]),d}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},c),e.stage.update(),e.getExposedState(this.callee)?.updateStyleSync(),super.executeAction(e,t)}else if(this.type===dt.setDarkness){let[n,i,r]=this.contentNode.getContent(),s=this.callee.state.darkness,a=()=>{this.callee.state.darkness=s},c=e.getExposedStateForce(this.callee);if(i){let l=new S(h=>h),u=new bi({from:s,to:n,duration:i,easing:r});if(I.isLayeredSrc(this.callee)){let h=I.getSrcURLs(this.callee);u._setPrevLayers(h)._setTargetLayers(h)}else{let h=Ai.resolveCurrentSrc(this.callee);u._setPrevSrc(h)._setTargetSrc(h)}let d=c.applyTransition(u,()=>{this.callee.state.darkness=n,l.resolve(super.executeAction(e,t))}),p=e.timelines.attachTimeline(l).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:p},()=>{l.isSettled()||l.abort(),d.abort(),a()}),l}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};Ai.ActionTypes=dt;var Se=Ai;var bs=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)}},Rt=class Rt{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)||Rt.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return Rt.isHexString(e)||Rt.isNamedColor(e)||Rt.isRGBAColor(e)}static isNamedColor(e){return Bs(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(Rt.isHexString(e))return e;if(Rt.isNamedColor(e))return e;if(Rt.isRGBAColor(e))return Rt.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,c=this.calc(i,s),l=this.calc(r,a),u=n.invertX?{right:c}:{left:c},d=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...u,...d}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let i=typeof t=="string"?"+":t<0?"-":"+",r=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${i} ${r})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};Rt.RGBColor=bs;var w=Rt,As=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 As{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},so=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,i=[],r=new Set,s=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!s.length)return null;for(i.push(s[0]);i.length;){let a=i.shift();this.checkAction(e,a,{imageStates:t,scenes:n},r);let c=a.contentNode.getChild();c&&c.action&&i.push(c.action)}return t}checkAction(e,t,{imageStates:n,scenes:i},r){if(t instanceof Se)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof se){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
|
|
76
76
|
Scene: ${s.config.name}
|
|
77
77
|
|
|
78
|
-
At: ${t.__stack}`;throw new
|
|
78
|
+
At: ${t.__stack}`;throw new He(a)}}else i.set(s.config.name,s);if(t.type===X.jumpTo){let a=t.contentNode.getContent()[0],c=e.getScene(a,!0);if(r.has(c))return;r.add(c)}}}checkImage(e,t){if(t.type===dt.setSrc){let i=t.contentNode.getContent()[0];w.isImageURL(i)&&w.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`
|
|
79
79
|
Using action (id: ${e.getId()})
|
|
80
|
-
at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},P=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Fe=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function yd(o,e){return Z.color(o,e)}function vd(o){return Z.bold(o)}function Sd(o){return Z.italic(o)}var vs=class o extends Se{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 Ss=class o extends Se{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 Q(o){return o<0?0:o>1?1:o}function Bc(o,e="100% 100%",t="no-repeat"){return{maskImage:o,WebkitMaskImage:o,maskSize:e,WebkitMaskSize:e,maskRepeat:t,WebkitMaskRepeat:t}}function Ts(o){return{position:"absolute",top:"50%",left:"50%",width:"100%",height:"100%",transform:"translate(-50%, -50%)",backgroundColor:o}}function Kc(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 zc(o){return o==="vertical"?"to right":"to bottom"}var bs=class o extends Se{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-Q(t),filter:`blur(${e*Q(t)}px)`}})),this.asTarget(t=>({style:{opacity:Q(t),filter:`blur(${e*(1-Q(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var As=class o extends Se{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*Q(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-Q(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};var xs=class o extends Se{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=Q(e);if(t<=0)return{filter:"none"};let n=Q(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-Q(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 N(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function Bo(o,e,t){return o<e?e:o>t?t:o}var Jt=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${N(t)}deg`:Kc(t);return{mask:(r,s)=>{let a=-n+(s?1-Q(r):Q(r))*(100+n);return s?`linear-gradient(${i}, transparent ${N(a)}%, #000 ${N(a+n)}%)`:`linear-gradient(${i}, #000 ${N(a)}%, transparent ${N(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${N(t)}deg`,`${N(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let c=-n+Q(s)*(50+n);if(!a){let l=u=>`linear-gradient(${u}, #000 ${N(c)}%, transparent ${N(c+n)}%)`;return`${l(i)}, ${l(r)}`}if(c<0){let l=Q((c+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${N(50-c-n)}%, rgba(0,0,0,${N(l)}) 50%, transparent ${N(50+c+n)}%)`}return`linear-gradient(${i}, transparent ${N(50-c-n)}%, #000 ${N(50-c)}%, #000 ${N(50+c)}%, transparent ${N(50+c+n)}%)`}}}static iris(e={}){let t=e.center??"50% 50%",n=Math.max(0,e.feather??12),i=e.shape??"circle";return{mask:(r,s)=>{if(s){let c=(1-Q(r))*150;return`radial-gradient(${i} at ${t}, transparent ${N(c-n)}%, #000 ${N(c)}%)`}let a=Q(r)*150;return`radial-gradient(${i} at ${t}, #000 ${N(a-n)}%, transparent ${N(a)}%)`}}}static clock(e={}){let t=e.center??"50% 50%",n=e.from??0,i=Math.max(0,e.feather??24),r=e.direction??"clockwise";return{mask:(s,a)=>{let c=r==="counterclockwise"!=!!a,l=-i+Q(s)*(360+i);if(c){let d=Math.max(0,360-l-i),p=Math.max(d,360-l);return`conic-gradient(from ${N(n)}deg at ${t}, transparent ${N(d)}deg, #000 ${N(p)}deg)`}let u=Math.max(0,l);return`conic-gradient(from ${N(n)}deg at ${t}, #000 ${N(u)}deg, transparent ${N(Math.max(u,l+i))}deg)`}}}static fan(e={}){let t=Math.max(1,Math.round(e.blades??4)),n=e.center??"50% 50%",i=e.from??0,r=Math.max(0,e.feather??10),s=360/t;return{mask:(a,c)=>{let l=-r+(c?1-Q(a):Q(a))*(s+r),u=Bo(l,0,s),d=Bo(l+r,0,s),p=`repeating-conic-gradient(from ${N(i)}deg at ${n}`;return c?`${p}, transparent 0deg, transparent ${N(u)}deg, #000 ${N(d)}deg, #000 ${N(s)}deg)`:`${p}, #000 0deg, #000 ${N(u)}deg, transparent ${N(d)}deg, transparent ${N(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"?`${N(t)}deg`:zc(t),s=100/n;return{mask:(a,c)=>{let l=-i+(c?1-Q(a):Q(a))*(s+i),u=Bo(l,0,s),d=Bo(l+i,0,s);return c?`repeating-linear-gradient(${r}, transparent 0, transparent ${N(u)}%, #000 ${N(d)}%, #000 ${N(s)}%)`:`repeating-linear-gradient(${r}, #000 0, #000 ${N(u)}%, transparent ${N(d)}%, transparent ${N(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=Q(e.stagger??0)*.5,a=(c,l,u)=>{let d=-i+Q(l)*(100+i);return u?`radial-gradient(circle farthest-corner at ${c}, transparent ${N(d)}%, #000 ${N(d+i)}%)`:`radial-gradient(circle farthest-corner at ${c}, #000 ${N(d)}%, transparent ${N(d+i)}%)`};return{size:`${N(100/n)}% ${N(100/t)}%`,repeat:"repeat",mask:(c,l)=>{let u=l?1-Q(c):Q(c);if(s<=0)return a("50% 50%",u,l);let d=Q(u/(1-s)),p=Q((u-s)/(1-s));return l?`${a("50% 50%",p,!0)}, ${a("0% 0%",d,!0)}`:`${a("50% 50%",d)}, ${a("0% 0%",p)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return Bc(e.mask(t,n),e.size,e.repeat)}};var Cs=class o extends Se{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{...Ts(this.color),opacity:Q(e)};let n={...Ts(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...Jt.toStyle(this.pattern,e,!this.inverted)}:{...n,...Jt.toStyle(this.uncover,e)}:{...n,...Jt.toStyle(this.pattern,e,this.inverted)}}createTask(){let t=(1-Q(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:R.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 ws=class o extends Se{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:Jt.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var Un="http://www.w3.org/2000/svg",Td="http://www.w3.org/1999/xlink",bd=.002,Ad=1,xd=.12,Cd=0,ks=class o extends Se{constructor(t){super();this.filterId=null;this.host=null;this.cut=null;this.duration=t.duration,this.rule=w.srcToURL(t.rule),this.feather=Math.min(Ad,Math.max(bd,t.feather??xd)),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-${++Cd}`,n=document.createElementNS(Un,"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(Un,"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(Un,"feImage");r.setAttribute("href",this.rule),r.setAttributeNS(Td,"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(Un,"feColorMatrix");s.setAttribute("in","rule"),s.setAttribute("type","luminanceToAlpha"),s.setAttribute("result","lum");let a=document.createElementNS(Un,"feComposite");a.setAttribute("in","lum"),a.setAttribute("in2","lum"),a.setAttribute("operator","arithmetic"),a.setAttribute("k1","0"),a.setAttribute("k2","0"),a.setAttribute("k3","0"),a.setAttribute("k4","0"),a.setAttribute("result","cut");let c=document.createElementNS(Un,"feComposite");return c.setAttribute("in","SourceGraphic"),c.setAttribute("in2","cut"),c.setAttribute("operator","in"),i.append(r,s,a,c),n.appendChild(i),document.body.appendChild(n),this.filterId=t,this.host=n,this.cut=a,t}dispose(){this.host?.remove(),this.host=null,this.cut=null,this.filterId=null}};var Ps=class extends ni{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new q(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,i)=>{let r={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable,$:t.$},s=typeof i=="function"?i(r):i;this.unlocked[n]=s}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};var Ko=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=ze.isChained(e)?e.getActions():e;return je.do(t)}static getNamespaceName(e){return e.getNamespaceName()}static getCurrentScene(e){return e.getCurrentScene()}static getLayerSrcs(e,t){return R.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 xt.normalizeState(e.state)}static setPuppetState(e,t,n,i={}){t.state=i.merge===!1?xt.normalizeState(n):xt.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(E.EventTypes["event:state.dialog.change"],t),e.events.on(E.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};Ko.DynamicPersistent=Ln;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
|
|
80
|
+
at: ${e.__stack}`}constructor(e,t){super(o.toMessage(e,t)),this.name="RuntimeScriptError"}},k=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},Ve=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function xd(o,e){return _.color(o,e)}function wd(o){return _.bold(o)}function kd(o){return _.italic(o)}var Cs=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 xs=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 Y(o){return o<0?0:o>1?1:o}function Qc(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 Xc(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 Jc(o){return o==="vertical"?"to right":"to bottom"}var ks=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-Y(t),filter:`blur(${e*Y(t)}px)`}})),this.asTarget(t=>({style:{opacity:Y(t),filter:`blur(${e*(1-Y(t))}px)`}}))]}}copy(){return new o({duration:this.duration,blur:this.blur,easing:this.easing})}};var Ps=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*Y(t))})),this.asTarget(t=>({style:this.translate(-e*100*(1-Y(t)))}))]}}copy(){return new o({duration:this.duration,direction:this.direction,easing:this.easing})}};var Es=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=Y(e);if(t<=0)return{filter:"none"};let n=Y(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-Y(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 G(o){return Number.isInteger(o)?String(o):o.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}function jo(o,e,t){return o<e?e:o>t?t:o}var Zt=class{constructor(){}static wipe(e={}){let t=e.direction??"left",n=Math.max(0,e.feather??12),i=typeof t=="number"?`${G(t)}deg`:Xc(t);return{mask:(r,s)=>{let a=-n+(s?1-Y(r):Y(r))*(100+n);return s?`linear-gradient(${i}, transparent ${G(a)}%, #000 ${G(a+n)}%)`:`linear-gradient(${i}, #000 ${G(a)}%, transparent ${G(a+n)}%)`}}}static barnDoor(e={}){let t=e.axis??"horizontal",n=Math.max(0,e.feather??12),[i,r]=typeof t=="number"?[`${G(t)}deg`,`${G(t+180)}deg`]:t==="vertical"?["to bottom","to top"]:["to right","to left"];return{mask:(s,a)=>{let c=-n+Y(s)*(50+n);if(!a){let l=u=>`linear-gradient(${u}, #000 ${G(c)}%, transparent ${G(c+n)}%)`;return`${l(i)}, ${l(r)}`}if(c<0){let l=Y((c+n)/Math.max(n,1e-6));return`linear-gradient(${i}, transparent ${G(50-c-n)}%, rgba(0,0,0,${G(l)}) 50%, transparent ${G(50+c+n)}%)`}return`linear-gradient(${i}, transparent ${G(50-c-n)}%, #000 ${G(50-c)}%, #000 ${G(50+c)}%, transparent ${G(50+c+n)}%)`}}}static iris(e={}){let t=e.center??"50% 50%",n=Math.max(0,e.feather??12),i=e.shape??"circle";return{mask:(r,s)=>{if(s){let c=(1-Y(r))*150;return`radial-gradient(${i} at ${t}, transparent ${G(c-n)}%, #000 ${G(c)}%)`}let a=Y(r)*150;return`radial-gradient(${i} at ${t}, #000 ${G(a-n)}%, transparent ${G(a)}%)`}}}static clock(e={}){let t=e.center??"50% 50%",n=e.from??0,i=Math.max(0,e.feather??24),r=e.direction??"clockwise";return{mask:(s,a)=>{let c=r==="counterclockwise"!=!!a,l=-i+Y(s)*(360+i);if(c){let d=Math.max(0,360-l-i),p=Math.max(d,360-l);return`conic-gradient(from ${G(n)}deg at ${t}, transparent ${G(d)}deg, #000 ${G(p)}deg)`}let u=Math.max(0,l);return`conic-gradient(from ${G(n)}deg at ${t}, #000 ${G(u)}deg, transparent ${G(Math.max(u,l+i))}deg)`}}}static fan(e={}){let t=Math.max(1,Math.round(e.blades??4)),n=e.center??"50% 50%",i=e.from??0,r=Math.max(0,e.feather??10),s=360/t;return{mask:(a,c)=>{let l=-r+(c?1-Y(a):Y(a))*(s+r),u=jo(l,0,s),d=jo(l+r,0,s),p=`repeating-conic-gradient(from ${G(i)}deg at ${n}`;return c?`${p}, transparent 0deg, transparent ${G(u)}deg, #000 ${G(d)}deg, #000 ${G(s)}deg)`:`${p}, #000 0deg, #000 ${G(u)}deg, transparent ${G(d)}deg, transparent ${G(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"?`${G(t)}deg`:Jc(t),s=100/n;return{mask:(a,c)=>{let l=-i+(c?1-Y(a):Y(a))*(s+i),u=jo(l,0,s),d=jo(l+i,0,s);return c?`repeating-linear-gradient(${r}, transparent 0, transparent ${G(u)}%, #000 ${G(d)}%, #000 ${G(s)}%)`:`repeating-linear-gradient(${r}, #000 0, #000 ${G(u)}%, transparent ${G(d)}%, transparent ${G(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=Y(e.stagger??0)*.5,a=(c,l,u)=>{let d=-i+Y(l)*(100+i);return u?`radial-gradient(circle farthest-corner at ${c}, transparent ${G(d)}%, #000 ${G(d+i)}%)`:`radial-gradient(circle farthest-corner at ${c}, #000 ${G(d)}%, transparent ${G(d+i)}%)`};return{size:`${G(100/n)}% ${G(100/t)}%`,repeat:"repeat",mask:(c,l)=>{let u=l?1-Y(c):Y(c);if(s<=0)return a("50% 50%",u,l);let d=Y(u/(1-s)),p=Y((u-s)/(1-s));return l?`${a("50% 50%",p,!0)}, ${a("0% 0%",d,!0)}`:`${a("50% 50%",d)}, ${a("0% 0%",p)}`}}}static invert(e){return{...e,mask:(t,n)=>e.mask(t,!n)}}static toStyle(e,t,n=!1){return Qc(e.mask(t,n),e.size,e.repeat)}};var Ds=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{...ws(this.color),opacity:Y(e)};let n={...ws(this.color),opacity:1};return t&&this.uncover!=="retreat"?this.uncover==="continue"?{...n,...Zt.toStyle(this.pattern,e,!this.inverted)}:{...n,...Zt.toStyle(this.uncover,e)}:{...n,...Zt.toStyle(this.pattern,e,this.inverted)}}createTask(){let t=(1-Y(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 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:Zt.toStyle(this.pattern,e)}))]}}copy(){return new o({duration:this.duration,pattern:this.pattern,easing:this.easing})}};var Bn="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 Te{constructor(t){super();this.filterId=null;this.host=null;this.cut=null;this.duration=t.duration,this.rule=w.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(Bn,"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(Bn,"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(Bn,"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(Bn,"feColorMatrix");s.setAttribute("in","rule"),s.setAttribute("type","luminanceToAlpha"),s.setAttribute("result","lum");let a=document.createElementNS(Bn,"feComposite");a.setAttribute("in","lum"),a.setAttribute("in2","lum"),a.setAttribute("operator","arithmetic"),a.setAttribute("k1","0"),a.setAttribute("k2","0"),a.setAttribute("k3","0"),a.setAttribute("k4","0"),a.setAttribute("result","cut");let c=document.createElementNS(Bn,"feComposite");return c.setAttribute("in","SourceGraphic"),c.setAttribute("in2","cut"),c.setAttribute("operator","in"),i.append(r,s,a,c),n.appendChild(i),document.body.appendChild(n),this.filterId=t,this.host=n,this.cut=a,t}dispose(){this.host?.remove(),this.host=null,this.cut=null,this.filterId=null}};var Is=class extends ri{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 qo=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=ze.isChained(e)?e.getActions():e;return je.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(E.EventTypes["event:state.dialog.change"],t),e.events.on(E.EventTypes["event:state.nvl.change"],t)];return{cancel:()=>{for(let i of n)i.cancel()}}}};qo.DynamicPersistent=In;if(typeof document<"u"){let o=document.createElement("style");o.textContent=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */
|
|
81
81
|
@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
|
|
82
|
-
`,document.head.appendChild(o)}export{
|
|
82
|
+
`,document.head.appendChild(o)}export{fn as Align,tn as AudioBusError,Xn as AudioBusMixer,Qn as AudioBusTree,Hr as Avatar,ks as BlurDissolve,ii as Camera,Qi as Character,st as CommonPosition,Pn as CommonPositionType,cr as Condition,je as Control,ft as Coord2D,bi as Darkness,tt as DefaultAudioBusIds,qr as DefaultNvlContainer,lc as DefaultNvlDialogItem,qo as DevTools,hp as Dialog,Cs as Dissolve,gd as ExposedStateType,Es as Exposure,xs as FadeIn,oc as FixedAspectRatioContainer,Is as Gallery,re as Game,fo as GameMenu,zc as GameProviders,E as GameState,I as Image,Te as ImageTransition,Ut as Isolated,wo as Item,Fn as KeyBindingType,Ti as KeyMap,j as Lambda,Nn as Layer,Fu as Layout,fi as LayoutRouterProvider,Ht as LiveGame,Zt as Mask,Ki as MaxAudioBusDepth,lr as Menu,ti as NVLToken,Gt as Namespace,Xt as Nametag,Yt as Narrator,Po as Notifications,jr as NvlContainer,cp as NvlDialogList,zr as NvlProvider,Bu as Page,Or as PageInjectContext,$e as Pause,Rn as Persistent,Kc as Player,ai as Preference,kt as Puppet,Ps as Push,Ls as Reveal,Pa as RootPath,Rs as RuleReveal,gt as Scene,Ce as Script,ta as SeededBusPreferenceKeys,de as Sentence,ri as Service,ve as Sound,ia as SoundType,Nl as Stage,qn as Storable,oi as Story,gn as Text,at as TextEvent,Zn as TextTransition,lu as Texts,su as TextsPreview,Ds as ThroughColor,Z as Transform,Ft as Transition,fr as Vfx,mr as Video,_ as Word,zi as acceptsAudioBus,wd as b,xd as c,rr as getActiveAudioBusTree,_l as getWordRenderer,kd as i,Jl as registerWordRenderer,Zl as unregisterWordRenderer,Xa as useAvatar,Cu as useDialog,dp as useDialogOverlay,R as useGame,np as useIsNvlMode,ip as useIsNvlVisible,Tn as useKeyBinding,Xu as useLiveGame,Kt as useNvl,Kr as useNvlDialogs,Ru as useParams,Lu as usePathname,un as usePreference,Iu as useQueryParams,Ot as useRouter,fp as useSuspendAdvance,Ir as useUIMenuContext,ku as useVoiceState};
|