narraleaf-react 0.12.1 → 0.12.2
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.
|
@@ -8,6 +8,14 @@ export type PreloadedToken = {
|
|
|
8
8
|
export declare class ImageCacheManager {
|
|
9
9
|
private readonly game;
|
|
10
10
|
static getImage(src: string, abortSignal?: AbortSignal, options?: RequestInit): Promise<string>;
|
|
11
|
+
/**
|
|
12
|
+
* Decode an image source off-screen so the browser's decoded-image cache is warm before
|
|
13
|
+
* the source is ever attached to a visible `<img>`. Without this, "preloaded" only means
|
|
14
|
+
* the bytes are cached — the first reveal still pays the (async) decode cost and can paint
|
|
15
|
+
* a blank frame. Decode failures are ignored: the image then simply decodes lazily on
|
|
16
|
+
* first paint, exactly as before.
|
|
17
|
+
*/
|
|
18
|
+
private static decodeImage;
|
|
11
19
|
private src;
|
|
12
20
|
private preloadTasks;
|
|
13
21
|
constructor(game: Game);
|
package/dist/main.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
var Pe={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",init:"displayable:init"},_t={say:"character:say",action:"character:action",setName:"character:setName"},B={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 Je={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},Cr={action:"condition:action"},Ar={action:"script:action"},xr={action:"menu:action"},wt={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume",mute:"sound:mute"},Ae={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"},Xn={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},Sn={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},Vt={action:"layer:action",setZIndex:"layer:setZIndex"},en={action:"video:action",show:"video:show",hide:"video:hide",play:"video:play",pause:"video:pause",resume:"video:resume",stop:"video:stop",seek:"video:seek"};var wr=(d=>(d[d.string=0]="string",d[d.number=1]="number",d[d.boolean=2]="boolean",d[d.object=3]="object",d[d.array=4]="array",d[d.function=5]="function",d[d.symbol=6]="symbol",d[d.undefined=7]="undefined",d[d.null=8]="null",d[d.date=9]="date",d[d.regexp=10]="regexp",d[d.other=11]="other",d))(wr||{}),io=(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});io.DataTypes=wr;function U(o,e,...t){let n=(s,a)=>Object.prototype.hasOwnProperty.call(s,a),i={},r=(s,a,c)=>io(a)===3&&io(c)===3?a.constructor!==Object||c.constructor!==Object?c||a:U(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]=U({},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 U(i,s,...a)}return i}var He=class He{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=oo()}static isAwaitable(e){return e instanceof He}static fromPromise(e){let t=new He;return e.then(n=>t.resolve(n)).catch(n=>t.fail(n)),t}static resolve(e){let t=new He;return t.resolve(e),t}static delay(e){let t=new He;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new He;return e(t),t}static wait(e){let t=new He;return e.then(()=>t.resolve()),e.onFailed(n=>t.fail(n)),t}static race(e){let t=new He;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 He().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 He;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 He;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>=He.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>=He.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()}}};He.nothing=e=>e,He.maxListeners=8;var v=He;function kr(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 nn(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 oo(o=1){let e=new Error().stack;return e?e.split(`
|
|
2
2
|
`).slice(o+1).join(`
|
|
3
|
-
`).trim():""}function ni(o){return new Promise(e=>setTimeout(e,o))}var ti=class ti{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(ti.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};ti.EventTypes={"event:skipController.abort":"event:skipController.abort"};var H=ti;var Tn=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}},tn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Tn;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 ii(o,e,t={}){return o?e:t}function Pr(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var Yn=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 Er(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 Dr(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 bn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}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())),await ni(this.delay),await e()};await e()}};function je(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function Lr(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var $e=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 Ir(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 Rr(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function ro(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function so(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"&&!so(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Jn=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Nr(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 Mr(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Zn=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},_n=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 ei=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 Gr(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 Hr(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,p=r*c+s*a>>>0,u=s*c+(p>>>0)>>>0;e=l,t=u}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Cn=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=oo(),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]:[]}};Cn.ActionTypes={action:"action"};var z=class extends Cn{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 v(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 ao=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},b=class o extends ao{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 ga}from"motion/react";var An=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(An||{}),Ur={left:"33.33%",center:"50%",right:"66.66%"},Ze=class Ze{static isUnknown(e){return e===Ze.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||Ze.isUnknown(e))return"auto";let i=!(t===void 0||Ze.isUnknown(t));if(typeof n=="number"&&n>0){let s=Ze.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(nt.isCommonPositionType(e))return _e.fromCommonPosition(e);if(_e.isCoord2DPosition(e))return e;if(Wt.isAlignPosition(e))return _e.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 Ze.isUnknown(e)||e===void 0?Ze.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return _e.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:Ze.isUnknown(t.x)?0:t.x,y:Ze.isUnknown(t.y)?0:t.y,xoffset:Ze.isUnknown(t.xoffset)?0:t.xoffset,yoffset:Ze.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(An).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 nt||e instanceof _e||e instanceof Wt}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return _e.fromCommonPosition(new nt(e));if(this.isRawAlignPosition(e))return _e.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new _e(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}}};Ze.Unknown=Symbol("Unknown");var L=Ze,ri=class ri{static isCommonPositionType(e){return e instanceof ri}constructor(e){this.position=e}toCSS(){return{x:Ur[this.position],y:"50%",xoffset:0,yoffset:0}}};ri.Positions=An;var nt=ri,_e=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:Ur[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||L.isUnknown(n)?L.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:L.isUnknown(t.x)?e.x:t.x,y:L.isUnknown(t.y)?e.y:t.y,xoffset:L.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:L.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=L.orUnknown(e.x),this.y=L.orUnknown(e.y),this.xoffset=L.orUnknown(e.xoffset),this.yoffset=L.orUnknown(e.yoffset)):(this.x=L.orUnknown(e),this.y=L.orUnknown(t),this.xoffset=L.Unknown,this.yoffset=L.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}}},Wt=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=L.orUnknown(e.xalign),this.yalign=L.orUnknown(e.yalign),this.xoffset=L.orUnknown(e.xoffset),this.yoffset=L.orUnknown(e.yoffset)):(this.xalign=L.orUnknown(e),this.yalign=L.orUnknown(t),this.xoffset=L.Unknown,this.yoffset=L.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:L.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:L.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var X=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new co(this.mergeWithDefaultConfig(e))}copy(){return new o(U({},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)?U({},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}},co=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(U({},this.config))}join(e){let t=Lr(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 ya={[oi.left]:"25.33%",[oi.center]:"50%",[oi.right]:"75.66%"},rt=class rt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new rt(rt.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?L.toCoord2D(L.tryParsePosition(e||t)):L.mergePosition(L.tryParsePosition(e),L.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=rt.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 ro(Y.constructStyle(e,this.state,t))}toStyle(e,t){return ro(Y.constructStyle(e,this.state,t))}serialize(){return rt.TransformStateSerializer.serialize(this.state)}clone(){return new rt(rt.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=rt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};rt.DefaultTransformState=new X({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new nt("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}),rt.TransformStateSerializer=new $e({position:e=>L.serializePosition(L.tryParsePosition(e))},{position:e=>L.toCoord2D(e)});var be=rt,Te=class Te{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},Te.defaultConfig,t||{});else{let[n,i]=[e,t||Te.defaultOptions];this.sequences.push({props:n,options:i||Te.defaultOptions}),this.config=Object.assign({},Te.defaultConfig)}}static isPosition(e){return nt.isCommonPositionType(e)||_e.isCoord2DPosition(e)||Wt.isAlignPosition(e)}static immediate(e){return new Te(e,{duration:0,ease:"linear"})}static left(e,t){return new Te({position:nt.Positions.Left},{duration:e,ease:t})}static right(e,t){return new Te({position:nt.Positions.Right},{duration:e,ease:t})}static center(e,t){return new Te({position:nt.Positions.Center},{duration:e,ease:t})}static create(e){return new Te([],e)}static positionToCSS(e,t,n,i){return e?L.isRawPosition(e)?L.D2PositionToCSS(L.rawPositionToCoord2D(e),n,t,i):L.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?L.toCoord2D(L.tryParsePosition(e||t)):L.mergePosition(L.tryParsePosition(e),L.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...U(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(d,g,f){return typeof d>"u"?typeof f<"u"?g(f):"":g(d)},l=s[0]||(r?"":"-")+"50%",p=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${p})`,c(t.rotation,d=>`rotate(${d}deg)`,0),c(t.scaleX,d=>`scaleX(${d*a})`,1),c(t.scaleY,d=>`scaleY(${d*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{...Te.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?nn(t.fontColor):void 0,transform:Te.propToCSSTransform(e,t),...Te.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(),p=ga(s,a),u=()=>{e.overwrite(l,r.get()).unlock(l),p.complete(),c=!0},d=new v().registerSkipController(new H(u)),g=()=>{c||e.overwrite(l,r.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),d.resolve()};return p.then(g,(f=>{t.logger.error("Failed to animate transform. "+(f?.toString?.()||""));try{g()}catch{d.resolve()}})),p.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:r,sequences:s,options:a},this),d}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...Te.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 p=r.assign(s,c).toFramesDefinition(e,n);return[i,p,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 Te(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 he("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 he("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};Te.defaultConfig={sync:!0},Te.defaultOptions={duration:0,ease:"linear"},Te.CommonImagePositionMap=ya;var Y=Te;var si=class{constructor(){this.id=""}setId(e){this.id=e}getId(){return this.id}reset(){}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 Fr=Symbol("_Chained"),Or;Or=Fr;var lo=class lo{constructor(e){this[Or]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Fr]}static toActions(e){return e.flat(2).map(t=>lo.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()}},Ee=lo,on=class extends si{chain(e){let t=Ee.isChained(this)?this:this.proxy(this,new Ee(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 oe=class extends on{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var pt=class extends z{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)}}`:""}`)}};pt.ActionTypes=Cr;var dt=class o{static isSerializable(e){return["number","string","boolean"].includes(typeof e)||e instanceof Date||e==null?!0:Array.isArray(e)?e.every(o.isSerializable):typeof e=="object"?Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(o.isSerializable):!1}constructor(e,t,n){this.name=e,this.key=n||e,this.content=U({},t),this.defaultContent=t}set(e,t){return o.isSerializable(t)?(this.content[e]=t,this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
|
|
3
|
+
`).trim():""}function ni(o){return new Promise(e=>setTimeout(e,o))}var ti=class ti{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(ti.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};ti.EventTypes={"event:skipController.abort":"event:skipController.abort"};var H=ti;var Tn=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}},tn=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Tn;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 ii(o,e,t={}){return o?e:t}function Pr(o,e){if(e<=0)return o;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{o(...n)},e)}}var Yn=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 Er(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 Dr(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 bn=class{constructor(e,t){this.concurrency=e;this.delay=t;this.tasks=[]}addTask(e){this.tasks.push(e)}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())),await ni(this.delay),await e()};await e()}};function je(o){let e,t=Promise.resolve().then(()=>{e=o()});return()=>{t.then(()=>{e&&e()})}}function Lr(o,e){let t={};for(let n in o)e.includes(n)||(t[n]=o[n]);return t}var $e=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 Ir(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 Rr(o){return o.constructor.name==="AsyncFunction"||Object.prototype.toString.call(o)==="[object AsyncFunction]"}function ro(o){let e={};for(let t in o)o[t]!==void 0&&(e[t]=o[t]);return e}function so(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"&&!so(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Jn=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Nr(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 Mr(o=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<o;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Zn=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},_n=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 ei=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 Gr(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 Hr(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,p=r*c+s*a>>>0,u=s*c+(p>>>0)>>>0;e=l,t=u}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Cn=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=oo(),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]:[]}};Cn.ActionTypes={action:"action"};var z=class extends Cn{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 v(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 ao=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},b=class o extends ao{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 ga}from"motion/react";var An=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(An||{}),Ur={left:"33.33%",center:"50%",right:"66.66%"},Ze=class Ze{static isUnknown(e){return e===Ze.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||Ze.isUnknown(e))return"auto";let i=!(t===void 0||Ze.isUnknown(t));if(typeof n=="number"&&n>0){let s=Ze.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(nt.isCommonPositionType(e))return _e.fromCommonPosition(e);if(_e.isCoord2DPosition(e))return e;if(Wt.isAlignPosition(e))return _e.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 Ze.isUnknown(e)||e===void 0?Ze.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),i=this.toCoord2D(t);return _e.merge(n,i)}static serializePosition(e){let t=this.toCoord2D(e);return{x:Ze.isUnknown(t.x)?0:t.x,y:Ze.isUnknown(t.y)?0:t.y,xoffset:Ze.isUnknown(t.xoffset)?0:t.xoffset,yoffset:Ze.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(An).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 nt||e instanceof _e||e instanceof Wt}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return _e.fromCommonPosition(new nt(e));if(this.isRawAlignPosition(e))return _e.fromAlignPosition(e);if(this.isRawCoord2DPosition(e))return new _e(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}}};Ze.Unknown=Symbol("Unknown");var D=Ze,ri=class ri{static isCommonPositionType(e){return e instanceof ri}constructor(e){this.position=e}toCSS(){return{x:Ur[this.position],y:"50%",xoffset:0,yoffset:0}}};ri.Positions=An;var nt=ri,_e=class o{static isCoord2DPosition(e){return e instanceof o}static fromCommonPosition(e){return new o({x:Ur[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||D.isUnknown(n)?D.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:D.isUnknown(t.x)?e.x:t.x,y:D.isUnknown(t.y)?e.y:t.y,xoffset:D.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:D.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=D.orUnknown(e.x),this.y=D.orUnknown(e.y),this.xoffset=D.orUnknown(e.xoffset),this.yoffset=D.orUnknown(e.yoffset)):(this.x=D.orUnknown(e),this.y=D.orUnknown(t),this.xoffset=D.Unknown,this.yoffset=D.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}}},Wt=class o{static isAlignPosition(e){return e instanceof o}constructor(e,t){typeof e=="object"?(this.xalign=D.orUnknown(e.xalign),this.yalign=D.orUnknown(e.yalign),this.xoffset=D.orUnknown(e.xoffset),this.yoffset=D.orUnknown(e.yoffset)):(this.xalign=D.orUnknown(e),this.yalign=D.orUnknown(t),this.xoffset=D.Unknown,this.yoffset=D.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:D.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:D.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var X=class o{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new co(this.mergeWithDefaultConfig(e))}copy(){return new o(U({},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)?U({},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}},co=class o{constructor(e){this.config=e}get(){return this.config}copy(){return new o(U({},this.config))}join(e){let t=Lr(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 ya={[oi.left]:"25.33%",[oi.center]:"50%",[oi.right]:"75.66%"},rt=class rt{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new rt(rt.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?D.toCoord2D(D.tryParsePosition(e||t)):D.mergePosition(D.tryParsePosition(e),D.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=rt.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 ro(Y.constructStyle(e,this.state,t))}toStyle(e,t){return ro(Y.constructStyle(e,this.state,t))}serialize(){return rt.TransformStateSerializer.serialize(this.state)}clone(){return new rt(rt.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=rt.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};rt.DefaultTransformState=new X({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new nt("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}),rt.TransformStateSerializer=new $e({position:e=>D.serializePosition(D.tryParsePosition(e))},{position:e=>D.toCoord2D(e)});var be=rt,Te=class Te{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},Te.defaultConfig,t||{});else{let[n,i]=[e,t||Te.defaultOptions];this.sequences.push({props:n,options:i||Te.defaultOptions}),this.config=Object.assign({},Te.defaultConfig)}}static isPosition(e){return nt.isCommonPositionType(e)||_e.isCoord2DPosition(e)||Wt.isAlignPosition(e)}static immediate(e){return new Te(e,{duration:0,ease:"linear"})}static left(e,t){return new Te({position:nt.Positions.Left},{duration:e,ease:t})}static right(e,t){return new Te({position:nt.Positions.Right},{duration:e,ease:t})}static center(e,t){return new Te({position:nt.Positions.Center},{duration:e,ease:t})}static create(e){return new Te([],e)}static positionToCSS(e,t,n,i){return e?D.isRawPosition(e)?D.D2PositionToCSS(D.rawPositionToCoord2D(e),n,t,i):D.D2PositionToCSS(e.toCSS(),n,t,i):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?D.toCoord2D(D.tryParsePosition(e||t)):D.mergePosition(D.tryParsePosition(e),D.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...U(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(d,g,f){return typeof d>"u"?typeof f<"u"?g(f):"":g(d)},l=s[0]||(r?"":"-")+"50%",p=s[1]||(i?"":"-")+"50%";return[`translate(${l}, ${p})`,c(t.rotation,d=>`rotate(${d}deg)`,0),c(t.scaleX,d=>`scaleX(${d*a})`,1),c(t.scaleY,d=>`scaleY(${d*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{...Te.positionToCSS(t.position,i,r,c),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?nn(t.fontColor):void 0,transform:Te.propToCSSTransform(e,t),...Te.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(),p=ga(s,a),u=()=>{e.overwrite(l,r.get()).unlock(l),p.complete(),c=!0},d=new v().registerSkipController(new H(u)),g=()=>{c||e.overwrite(l,r.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,i)),d.resolve()};return p.then(g,(f=>{t.logger.error("Failed to animate transform. "+(f?.toString?.()||""));try{g()}catch{d.resolve()}})),p.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:r,sequences:s,options:a},this),d}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...Te.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 p=r.assign(s,c).toFramesDefinition(e,n);return[i,p,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 Te(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 he("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 he("Invalid number in at definition.");let c=a/1e3;return r==="+"?`+${c}`:`-${c}`}};Te.defaultConfig={sync:!0},Te.defaultOptions={duration:0,ease:"linear"},Te.CommonImagePositionMap=ya;var Y=Te;var si=class{constructor(){this.id=""}setId(e){this.id=e}getId(){return this.id}reset(){}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 Fr=Symbol("_Chained"),Or;Or=Fr;var lo=class lo{constructor(e){this[Or]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[Fr]}static toActions(e){return e.flat(2).map(t=>lo.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()}},Ee=lo,on=class extends si{chain(e){let t=Ee.isChained(this)?this:this.proxy(this,new Ee(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 oe=class extends on{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var pt=class extends z{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)}}`:""}`)}};pt.ActionTypes=Cr;var dt=class o{static isSerializable(e){return["number","string","boolean"].includes(typeof e)||e instanceof Date||e==null?!0:Array.isArray(e)?e.every(o.isSerializable):typeof e=="object"?Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(o.isSerializable):!1}constructor(e,t,n){this.name=e,this.key=n||e,this.content=U({},t),this.defaultContent=t}set(e,t){return o.isSerializable(t)?(this.content[e]=t,this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
|
|
4
4
|
at namespace "${this.name}"`),this.content[e]=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(){return this.content=U({},this.defaultContent),this}getContent(){return this.content}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content=e}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)})}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e){let t={any:i=>({type:"any",data:i}),date:i=>({type:"date",data:i.toString()})},n=this.toTypeName(e);return t[n](e)}unwrap(e){return{any:n=>n.data,date:n=>new Date(n.data)}[e.type](e)}},xn=class{constructor(){this.namespaces={}}static createNamespace(e,t,n){return new dt(e,t,n)}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,this}getNamespace(e){if(!this.namespaces[e])throw new k(`Namespace ${e} is not initialized, did you forget to register it?
|
|
5
5
|
Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]=t,this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return 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)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.namespaces[t]?this.namespaces[t].load(n):this.namespaces[t]=new dt(t,n)})}clear(){return this.namespaces={},this}};var qe=class extends z{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===wt.play){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.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===wt.stop){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.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===wt.setVolume){let[i,r]=this.contentNode.getContent(),s=this.callee.toData(),a=v.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===wt.setRate){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.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===wt.pause){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.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===wt.resume){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.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===wt.mute){let[i]=this.contentNode.getContent(),r=this.callee.toData(),s=v.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")}};qe.ActionTypes=wt;var Nt=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(Nt||{}),ve=class ve extends oe{static toSound(e){return e==null?null:typeof e=="string"?new ve({src:e}):e}static isSound(e){return e instanceof ve}static voice(e){let t=typeof e=="string"?{src:e}:e;return new ve({...t,type:"voice"})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new ve({...t,type:"bgm"})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new ve({...t,type:"sound"})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=ve.DefaultUserConfig.create(t),[i]=n.extract(ve.DefaultConfig.keys());this.config=i.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){if(this.config.type==="bgm")throw new xe(`Sound (src: ${this.config.src}) is marked as bgm, but it is being played as a normal sound.
|
|
6
6
|
To prevent unintended behavior, the sound marked as bgm cannot be played using \`play()\`.`);return this.pushAction(qe.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(qe.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(qe.ActionTypes.setVolume,[e,t||0])}mute(e=!0){return this.pushAction(qe.ActionTypes.mute,[e])}unmute(){return this.mute(!1)}setRate(e){return this.pushAction(qe.ActionTypes.setRate,[e])}pause(e){return this.pushAction(qe.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(qe.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}getSrc(){return this.config.src}toData(){return{state:ve.StateSerializer.serialize(this.state)}}fromData(e){return this.state=ve.StateSerializer.deserialize(e.state),this}copy(){return new ve(this.userConfig.get())}reset(){return this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return ve.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new qe(this.chain(),e,new b().setContent(t)))}};ve.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",ve.DefaultUserConfig=new X({src:ve.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,type:"sound"}),ve.DefaultConfig=new X({src:ve.noSound,loop:!1,streaming:!1,seek:0,type:"sound"}),ve.DefaultState=new X({volume:1,rate:1,paused:!1,muted:!1}),ve.StateSerializer=new $e;var pe=ve;var Ju={};var rn=class extends on{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 Bt=class Bt{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===Bt.SrcTypes.image?t.add(s):r===Bt.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 M?M.getSrcURL(e):e.type==="image"?M.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(ee,B.jumpTo)){let n=t.contentNode.getContent()[0],r=e.getScene(n,!0).state.backgroundImage;if(C.isImageURL(r.config.src))return{type:"image",src:r.config.src,activeType:"once"}}else if(t instanceof re){let n=t;if(t.is(re,Je.setSrc)){let i=t.contentNode.getContent()[0];if(C.isImageSrc(i))return{type:"image",src:C.srcToURL(i),activeType:"scene"}}else{if(t.type===Je.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===Je.setAppearance){let i=t.contentNode.getContent()[0];if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(M.isTagSrc(n.callee)&&i.length===n.callee.config.src.groups.length)return{type:"image",src:M.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 pe){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof M||C.isStaticImageData(e)){if(e instanceof M){if(!C.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(M.getSrcURL(e)))return this}else if(this.isSrcRegistered(C.srcToURL(e.src)))return this;this.src.push({type:"image",src:C.isStaticImageData(e)?C.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 pe?t:new pe({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 pe?e.getSrc():e;return this.src.some(n=>n.type===Bt.SrcTypes.audio?t===n.src.getSrc():n.type===Bt.SrcTypes.image?t===M.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)}};Bt.SrcTypes={image:"image",video:"video",audio:"audio"};var Ue=Bt;var Mt=class extends z{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Xn.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===Xn.setFontSize){let i=this.callee.state.fontSize;return this.callee.state.fontSize=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,r=>{this.callee.state.fontSize=r},[i]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};Mt.ActionTypes=Xn;var De=class extends z{executeAction(e,t){if(this.type===Pe.applyTransform){let[n]=this.contentNode.getContent(),i=this.callee;return this.applyTransform(e,i,n,t)}else if(this.type===Pe.applyTransition){let[n,i]=this.contentNode.getContent(),r=this.callee,s=i?i(n):n;return this.applyTransition(e,r,s,t)}else if(this.type===Pe.init){let[n,i,r]=this.contentNode.getContent(),s=this.callee;return this.initDisplayable(e,n,s,i||null,r,t)}throw this.unknownTypeError()}applyTransform(e,t,n,i,r){let s=new v().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(),p=c.applyTransform(n,a),u=e.timelines.attachTimeline(s).attachChild(p);return p.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:u},d=>{s.isSettled()||s.abort(),p.abort(),t.transformState.forceOverwrite(d.state)},[l]),s}applyTransition(e,t,n,i,r){let s=new v().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),p=e.timelines.attachTimeline(s).attachChild(l);return l.onCancelled(a),e.actionHistory.push({action:this,stackModel:i.stackModel,timeline:p},()=>{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 v().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}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};De.ActionTypes=Pe;var mt=class o extends oe{constructor(){super(...arguments);this.srcManager=new Ue}pos(t,n,i){return this.transform(new Y({position:t},{duration:n,ease:i}))}zoom(t,n,i){return this.transform(new Y({zoom:t},{duration:n,ease:i}))}scaleX(t,n,i){return this.transform(new Y({scaleX:t},{duration:n,ease:i}))}scaleY(t,n,i){return this.transform(new Y({scaleY:t},{duration:n,ease:i}))}scale(t,n,i,r){return this.transform(new Y({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 Y({rotation:t},{duration:n,ease:i}))}opacity(t,n,i){return this.transform(new Y({opacity:t},{duration:n,ease:i}))}effect(t,n){return this.registerEffectSrc(t),this.transform(new Y(t,n))}mask(t,n={}){let i=C.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,p={duration:a,ease:c,...l},u=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),p]]);return s?this.combineActions(new Le,d=>d.transform(u).clearClip({duration:0})):this.transform(u)}circleClose(t={}){let{center:n="50% 50%",from:i=150,to:r=0,clearClip:s=!1,duration:a=600,ease:c="easeInOut",...l}=t,p={duration:a,ease:c,...l},u=o.createClipPathTransform([[o.circleClipPath(i,n),{duration:0}],[o.circleClipPath(r,n),p]]);return s?this.combineActions(new Le,d=>d.transform(u).clearClip({duration:0})):this.transform(u)}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},p=o.wipeClipPath(n,100),u=o.wipeClipPath(n,0),d=o.createClipPathTransform([[i?u:p,{duration:0}],[i?p:u,l]]);return r?this.combineActions(new Le,g=>g.transform(d).clearClip({duration:0})):this.transform(d)}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 De(n,Pe.applyTransform,new b().setContent([t.copy()]));return n.chain(i)}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 Y(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 Y?t.copy():new Y({opacity:1},t),r=new De(n,Pe.applyTransform,new b().setContent([i]));return n.chain(r)}hide(t){let n=this.chain(),i=t instanceof Y?t.copy():new Y({opacity:0},t),r=new De(n,Pe.applyTransform,new b().setContent([i]));return n.chain(r)}};var Qe=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(Qe||{});import{animate as va}from"motion/react";var ft=class{requestAnimations(e){let t=e.map(u=>u.start),n=[],i=0,r=[],s=[],a=[];return{onUpdate:u=>(r.push(u),{cancel:()=>{let d=r.indexOf(u);d!==-1&&r.splice(d,1)}}),onComplete:u=>(s.push(u),{cancel:()=>{let d=s.indexOf(u);d!==-1&&s.splice(d,1)}}),onCanceled:u=>(a.push(u),{cancel:()=>{let d=a.indexOf(u);d!==-1&&a.splice(d,1)}}),complete:()=>{i!==e.length&&n.forEach(u=>u.complete())},start:()=>{if(n.length>0)throw new Error("Animation controllers are already started");e.forEach((u,d)=>{n.push(this.requestMotion(u,{onComplete:()=>{t[d]=u.end,r.forEach(g=>g(t)),i++,i===e.length&&s.forEach(g=>g())},onUpdate:g=>{t[d]=g,r.forEach(f=>f(t))}}))})},cancel:()=>{n.forEach(u=>u.cancel()),a.forEach(u=>u())}}}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 va(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=Qe;var wn=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
|
|
7
7
|
This should not happen, please report this issue to the developers`);return this._element.state}};var ai=class o extends wn{constructor(t,n,i){super();this.textSize=t;this.duration=n;this.easing=i}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.textSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{fontSize:`${t}px`}}))]}}copy(){return new o(this.textSize,this.duration,this.easing)}};var Xe=class Xe extends mt{constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,i=Xe.DefaultUserConfig.create(n),r=Xe.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 Mt(t,Mt.ActionTypes.setText,new b().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new Y({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Le,i=>{if(t){let s=new ai(e,t,n);i.chain(this._applyTransition(i,s))}let r=new Mt(i,Mt.ActionTypes.setFontSize,new b().setContent([e]));return i.chain(r)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:Xe.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=Xe.StateSerializer.deserialize(e.state),this.transformState=be.deserialize(e.transformState),this}_init(e){return new De(this.chain(),Pe.init,new b().setContent([e||null,this.config.layer||null]))}reset(){this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(Xe.DefaultTextTransformState.keys());return new be(Xe.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new De(e,Pe.applyTransition,new b().setContent([t,n=>n._setElement(this)]))}getInitialState(){return Xe.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};Xe.DefaultUserConfig=new X({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:""}),Xe.DefaultTextConfig=new X({alignX:"center",alignY:"center",className:"",layer:void 0}),Xe.DefaultTextState=new X({fontSize:16,display:!1,text:""}),Xe.DefaultTextTransformState=new X({fontColor:"#000000",...be.DefaultTransformState.getDefaultConfig()}),Xe.StateSerializer=new $e;var zt=Xe;var kn=class kn extends z{executeAction(e,t){let n=this;if(n.is(kn,"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(kn,"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")}};kn.ActionTypes=Sn;var ci=kn;var Ie=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 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 getText(e){return e.filter(t=>!t.isPause()).map(t=>t.toString()).join("")}constructor(e,t={}){this.text=e,this.config=U(Re.defaultConfig,t)}evaluate(e){if(Ie.isPause(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=U(this.config,e),this}copy(){return new Re(this.text,this.config)}isPause(){return Ie.isPause(this.text)}toString(){return typeof this.text=="string"?this.text:""}};Re.defaultConfig={},Re.defaultColor="#000";var $=Re;var Ye=class Ye{static isSentence(e){return e instanceof Ye}static toSentence(e){return Ye.isSentence(e)?e:new Ye(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(Ye.isSingleWord):Ye.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||$.isWord(e)||Ie.isPause(e)||typeof e=="function"}getMetadata(){return this.config.metadata}constructor(e,t={}){this.text=Ye.format(e),this.config=U(Ye.defaultConfig,{...t,voice:typeof t.voice=="string"?pe.voice(t.voice):pe.toSound(t.voice)}),this.state=kr(Ye.defaultState)}toData(){return null}fromData(e){return this.state=U(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(...Ye.formatStaticWord(i))}return t}copy(){return new Ye([...this.text],this.config)}};Ye.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},Ye.defaultState={};var ce=Ye;var Gt=class extends z{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")}};Gt.ActionTypes=Ar;var Se=class o extends oe{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 Gt(t,Gt.ActionTypes.action,new b().setContent(this));return this.chain(n)}execute({gameState:e}){return this.handler(o.getCtx({gameState:e}))}fromChained(e){return[new Gt(this.chain(),Gt.ActionTypes.action,new b().setContent(e))]}};var li=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()}),je(()=>{this.preventAttach()})}static proxy(e){let t=new v,n=new v,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 v,n=new v,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 v,n=new v,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 v,s=()=>{if(i){let a;i.onSkipControllerRegister(c=>{a=c.onAbort(()=>{r.abort()})}),i.then(c=>{a?.cancel(),n=c,i=e(c),i?je(()=>s()):r.resolve(n)})}else r.resolve(n)};return r.registerSkipController(new H(()=>(i&&i.abort(),t))),i=e(t),i?je(()=>s()):je(()=>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()?je(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.
|
|
8
8
|
Timeline attaching is only allowed synchronously after the timeline is created.
|
|
9
|
-
Current _ableToAttach: `+this._ableToAttach);let t=v.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())}},ui=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 sn=class sn extends z{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:pe.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)}executeAction(e,t){if(this.type===_t.say){let n=null,i="",r=null,s=new v(h=>h).registerSkipController(new H(()=>{n?.()})),a=new we(s),c=this.contentNode.getContent(),l=e.isNvlMode(),p=e.getLiveGame(),u=e.createPresentationSnapshot(),d=p.lastDialog?{sentence:p.lastDialog.sentence,speaker:p.lastDialog.speaker}:null,g=sn.getVoice(e,c);if(g){let h=e.audioManager.play(g);a.attachChild(h)}let f=g?e.events.on(E.EventTypes["event:state.player.lineEnd"],()=>{let h=sn.endVoiceWithPreference(e,g);h&&e.timelines.attachTimeline(h),f?.cancel()}):null;if(l){let h=this.getId(),m=(e.getActiveNvlDialogForAction(h)||e.getLatestNvlDialogForAction(h))?.id||e.allocateNvlDialogId(h),
|
|
9
|
+
Current _ableToAttach: `+this._ableToAttach);let t=v.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())}},ui=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 sn=class sn extends z{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:pe.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)}executeAction(e,t){if(this.type===_t.say){let n=null,i="",r=null,s=new v(h=>h).registerSkipController(new H(()=>{n?.()})),a=new we(s),c=this.contentNode.getContent(),l=e.isNvlMode(),p=e.getLiveGame(),u=e.createPresentationSnapshot(),d=p.lastDialog?{sentence:p.lastDialog.sentence,speaker:p.lastDialog.speaker}:null,g=sn.getVoice(e,c);if(g){let h=e.audioManager.play(g);a.attachChild(h)}let f=g?e.events.on(E.EventTypes["event:state.player.lineEnd"],()=>{let h=sn.endVoiceWithPreference(e,g);h&&e.timelines.attachTimeline(h),f?.cancel()}):null;if(l){let h=this.getId(),m=(e.getActiveNvlDialogForAction(h)||e.getLatestNvlDialogForAction(h))?.id||e.allocateNvlDialogId(h),S=c.evaluate(Se.getCtx({gameState:e}));i=$.getText(S),p.events.emit(ht.EventTypes["event:character.prompt"],{character:c.config.character,sentence:c,text:i});let L=!1,O=()=>{L||(L=!0,e.events.emit(E.EventTypes["event:state.player.lineEnd"]),e.gameHistory.resolvePending(T),s.resolve({type:this.type,node:this.contentNode.getChild()}))},{created:A}=e.ensureNvlDialog({id:m,actionId:h,character:this.callee,sentence:c,text:i});r=m;let R=e.consumeNvlTypingSuppression(),j=A&&!R?"typing":"awaitAdvance";e.activateNvlDialog(m,j,!A);let K=e.waitForNvlAdvance(m,()=>{e.settleNvlDialog(m),O()});n=()=>{K.cancel()}}else{let h=e.idManager.generateId(),y=e.createDialog(h,c,()=>{e.gameHistory.resolvePending(T),s.resolve({type:this.type,node:this.contentNode.getChild()})});i=y.text,n=y.cancel}p.setLastDialog(i,this.callee.state.name),e.timelines.attachTimeline(a);let{id:T}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:a},()=>{if(f?.cancel(),g&&e.audioManager.isPlaying(g)){let h=sn.endVoiceWithPreference(e,g);h&&a.attachChild(h)}n?.(),r&&(e.removeNvlDialog(r),e.settleNvlDialog(r)),e.restorePresentationSnapshot(u),d?p.setLastDialog(d.sentence,d.speaker):p.lastDialog=null});return e.gameHistory.push({token:T,action:this,element:{type:"say",text:i,voice:g?g.getSrc():null,character:this.callee.state.name},isPending:!0}),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")}};sn.ActionTypes=_t;var st=sn;var Pn=class Pn extends oe{constructor(e,t={}){super(),this.config=U(Pn.defaultConfig,t),this.state={name:e||""};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=>ce.isSingleWord(c))){let c=e,l=ce.format([t,...n]),p=new ce(Er(c,l),{character:this}),u=new st(this.chain(),st.ActionTypes.say,new b().setContent(p));return this.chain(u)}let i=t||{},r=e,s=Array.isArray(r)?new ce(r,{...i,character:this}):(ce.isSentence(r)?r:new ce(r,{...i,character:this})).copy();s.setCharacter(this);let a=new st(this.chain(),st.ActionTypes.say,new b().setContent(s));return this.chain(a)}setName(e){let t=new st(this.chain(),st.ActionTypes.setName,new b().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&&ce.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):ce.isSentence(e)?this.say(e):this.say(e,t)}};Pn.defaultCharacterColor="#000",Pn.defaultConfig={portraits:[]};var pi=Pn,kt=new pi(null);var F=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()})`}},uo=class o extends oe{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 xe(`ELSE condition already set
|
|
10
10
|
You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:F.from(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new xe(`ELSE condition already set
|
|
11
11
|
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(pt,[this,pt.ActionTypes.action,new b().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 Ee.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=F.from(t),this.conditions.If.action=this.construct(n);let i=this.chain(),r=new pt(i,pt.ActionTypes.action,new b().setContent(this.conditions));return i.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?kt.say(n).getActions():Ee.toActions([n]))}};var di=class di extends oe{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new dt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Sn.set,[e,t]))}assign(e){return this.chain(this.createAction(Sn.assign,[e]))}equals(e,t){return new F(n=>{let i=n.storable.getNamespace(this.namespace),r=F.isLambda(t)||F.isLambdaHandler(t)?F.from(t).evaluate(n).value:t;return i.equals(e,r)})}notEquals(e,t){return new F(n=>{let i=n.storable.getNamespace(this.namespace),r=F.isLambda(t)||F.isLambdaHandler(t)?F.from(t).evaluate(n).value:t;return!i.equals(e,r)})}isTrue(e){return new F(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new F(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new F(({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=>F.from(e).evaluate(i).value?t:n)}evaluate(e,t){return new F(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=di.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new ci(this.chain(),e,b.create(t))}};di.NamespacePrefix="persistent";var an=di,mi=class mi extends an{constructor(e){super(e,{}),this.namespace=this.prefix(e,mi.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new dt(this.namespace,this.defaultContent))}};mi.LocalNamespacePrefix="local";var cn=mi;var ln=class extends z{executeAction(e,t){if(this.type===Vt.action)return super.executeAction(e,t);if(this.type===Vt.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")}};ln.ActionTypes=Vt;var it=class it extends mt{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 ln(this.chain(),Vt.setZIndex,new b().setContent([e])))}toData(){return{state:it.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=it.StateSerializer.deserialize(e.state),this.transformState=be.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 ln(this.chain(),Vt.action,new b),new De(this.chain(),Pe.init,new b().setContent([e,null,!1]))]}getInitialState(){return it.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(be.DefaultTransformState.keys());return new be(be.DefaultTransformState.create(e.get()).get())}};it.DefaultUserConfig=new X({zIndex:0,...be.DefaultTransformState.getDefaultConfig(),opacity:1}),it.DefaultConfig=new X({name:"(anonymous)",zIndex:0}),it.StateSerializer=new $e,it.DefaultState=new X({zIndex:0});var un=it;var En=class extends oe{constructor(e){super(),this.scene=e}show(e){let t=new ee(this.scene.chain(),B.nvlShow,new b().setContent([e]));return this.chain(t)}hide(e){let t=new ee(this.scene.chain(),B.nvlHide,new b().setContent([e]));return this.chain(t)}end(){let e=new ee(this.scene.chain(),B.nvlEnd,new b().setContent([]));return this.chain(e)}};var Ve=class Ve extends rn{constructor(t,n){super();this.srcManager=new Ue;this.events=new Q;this.actions=[];this._futureActions_=[];let i=Ve.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),r=Ve.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),s=Ve.DefaultUserConfig.create(n),a=Ve.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 cn(t)}static validateVoice(t){if(t.config.type!=="voice"&&t.config.type!=="sound")throw new xe(`Voice must be a voice, but got ${t.config.type}.
|
|
12
12
|
To prevent unintended behavior and unexpected results, the sound have to be marked as voice. Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof Ve}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new $e({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(Le.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new Le({allowFutureScene:!1}),i=>{let s=U({},n instanceof ft?{transition:n}:n);return i.chain(new ee(i,"scene:preUnmount",new b().setContent([]))).chain(this._initScene(t))._transitionToScene(s.transition,t.state.backgroundImage.state.currentSrc).chain(this._exit()),i})._jumpTo(t)}setBackgroundMusic(t,n){return this.chain(new ee(this.chain(),B.setBackgroundMusic,new b().setContent([t,n])))}nvl(t,n){let i,r;n!==void 0?(i=t,r=n):(i=void 0,r=t);let s=new En(this),a=typeof r=="function"?r(s):r,c=this.narrativeToActions(a),l={showTransition:i,hideTransition:i},p=new ee(this.chain(),B.nvlEnd,new b().setContent([l])),u=[...c,p];super.constructNodes(u);let d=new ee(this.chain(),B.nvlBlock,new b().setContent([u,l]));return this.chain(d)}action(t){return this.actions=t,this}preloadImage(t){if(!C.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:Ve.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=Ve.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new ee(this.chain(),"scene:action",new b);let n=this.actions,r=this.narrativeToActions(typeof n=="function"?n(this):n).map(f=>Ee.isChained(f)?f.fromChained(f):f).flat(2),s=[],a=[];this.getAllChildrenElements(t,r,{allowFutureScene:!1}).forEach(f=>{Ee.isChained(f)||(f instanceof M?s.push(f):f instanceof zt&&a.push(f))});let c=[],l=[],p=new Map;s.forEach(f=>{f.config.isWearable?l.push(f):f.config.autoInit&&c.push(f);for(let T of f.config.wearables){if(p.get(T)&&p.get(T)!==f)throw new Error(`Wearable image cannot be used multiple times
|
|
@@ -37,15 +37,15 @@ NarraLeaf cannot find the element with the id from the saved game`);f.reset(),f.
|
|
|
37
37
|
`&&e!==`
|
|
38
38
|
`&&n.tag===e.tag?[...t.slice(0,-1),{...e,text:n.text+e.text,config:e.config}]:[...t,e]})}function oc(o,e,t){return t||(o!==void 0?ce.formatStaticWord(o):e?e.text.flatMap(n=>typeof n.text=="function"?[]:new $(n.text,n.config)):[])}function rc(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 ds(o,e){let t=Math.max(.01,o),n=Math.max(.01,e);return 1e3/(t*n)}function Ii(o){return o===void 0?void 0:nn(o)}function wo({defaultColor:o,className:e,style:t,dialog:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,...c}){let l=P(),p=l.getLiveGame().getGameState(),u=ms(null),[d,g]=Co(()=>n&&!n.config.useTypeEffect?Ao(n.config.evaluatedWords):[]),[f,T]=te();if(!n)throw new Error("Dialog state is required");mn(()=>{if(!(!n.config.action.sentence||u.current))return p.logger.info("Initializing the sentence",n,u.current),p.schedule(({onCleanup:A})=>{if(!n.config.useTypeEffect){n.dispatchComplete();return}g([]),u.current=h(),f(),u.current.onComplete(()=>{n.dispatchComplete()}),A(()=>{u.current?.timeline?.abort()})},0)},[]),mn(()=>n.events.depends([n.events.on(Ce.Events.requestComplete,()=>{u.current?.interact()}),n.events.on(Ce.Events.forceSkip,()=>{n.isEnded()||u.current?.forceSkip()})]).cancel,[n,T]),mn(()=>l.preference.events.depends([l.preference.onPreferenceChange(J.Preferences.gameSpeed,()=>{u.current?.update()}),l.preference.onPreferenceChange(J.Preferences.autoForward,()=>{u.current?.update()}),l.preference.onPreferenceChange(J.Preferences.cps,()=>{u.current?.update()})]).cancel,[]);function h(){let A=new v,R=new we(A).setGuard(p.guard),j=new Set,K=new Set,se=new Set,Ge=xo(n.config.evaluatedWords),ke=null,At=[],Be=[],ge=()=>{At.forEach(V=>V()),At.length=0},G=()=>{if(Be.length!==0)return{done:!1,value:Be.shift()};let{done:V,value:x}=Ge.next();return{done:V,value:x}},ie=V=>{let x=N=>{V(N),K.delete(x)};return K.add(x),{cancel:()=>{K.delete(x)}}},Z=V=>{fs(g,V)},q=(V=!1)=>{let x=!1;for(;!x;){let{done:N,value:_}=G();if(N){x=!0;break}if(Ie.isPause(_)){if(V)continue;x=!0,Be.push(_);break}else _===`
|
|
39
39
|
`?g(w=>[...w,_]):typeof _=="object"&&"text"in _&&!j.has(_)&&(j.add(_),Z(_))}ke&&!ke.isSettled()?ke.abort():(se.forEach(N=>N()),A.resolve())};return p.schedule(async V=>{let x=!1,N=!1;for(;!x;){let{done:_,value:w}=G();if(_){x=N=!0;break}let ze=new v;if(p.timelines.attachTimeline(ze),ze.registerSkipController(new H(()=>{ge(),x=!0,V.retry()})),ze.onSettled(()=>{ge()}),ke=ze,Ie.isPause(w)){let xt=Ie.from(w),jn=l.preference.getPreference(J.Preferences.gameSpeed);if(xt.config.duration){let qn=xt.config.duration/jn;await ni(qn)}else{let qn=l.preference.getPreference(J.Preferences.autoForward),Qn=v.race([v.create(ma=>{let fa=ie(ha=>{ha(),ma.resolve()});At.push(()=>fa.cancel())}),...qn?[v.delay(l.config.autoForwardDefaultPause/jn)]:[]]);p.timelines.attachTimeline(Qn),await v.wait(Qn)}}else{if(w!==`
|
|
40
|
-
`&&j.has(w))continue;j.add(w),Z(w);let{gameSpeed:xt,cps:jn}=l.preference.getPreferences(),Qn=1e3/((typeof w=="object"&&"cps"in w&&w.cps!==void 0?w.cps:jn)*xt);await ni(Qn)}}N&&(se.forEach(_=>_()),A.resolve())},0),{getToken:()=>A,interact:()=>{let V=!1;K.forEach(x=>x(()=>V=!0)),!V&&q()},update:()=>{ke&&ke.abort()},forceSkip:()=>{q(!0)},timeline:R,onComplete:V=>(se.add(V),{cancel:()=>{se.delete(V)}})}}let
|
|
41
|
-
`?Ne.createElement("br",{key:R}):Ne.createElement(qt.Span,{tag:`say.word.${R}`,key:R,style:{...
|
|
40
|
+
`&&j.has(w))continue;j.add(w),Z(w);let{gameSpeed:xt,cps:jn}=l.preference.getPreferences(),Qn=1e3/((typeof w=="object"&&"cps"in w&&w.cps!==void 0?w.cps:jn)*xt);await ni(Qn)}}N&&(se.forEach(_=>_()),A.resolve())},0),{getToken:()=>A,interact:()=>{let V=!1;K.forEach(x=>x(()=>V=!0)),!V&&q()},update:()=>{ke&&ke.abort()},forceSkip:()=>{q(!0)},timeline:R,onComplete:V=>(se.add(V),{cancel:()=>{se.delete(V)}})}}let y=n.config.action.sentence;if(!y)return null;let m=s??"bold",S={fontWeight:y.config.bold?m:r,fontSize:y.config.fontSize??i,color:Ii(y.config.color??o),fontFamily:y.config.fontFamily??a,fontStyle:y.config.italic?"italic":void 0},L=A=>({fontWeight:A.config.bold||y.config.bold?m:r,fontSize:A.config.fontSize??y.config.fontSize??i,color:Ii(A.config.color??y.config.color??o),fontFamily:A.config.fontFamily??y.config.fontFamily??a,fontStyle:A.config.italic??y.config.italic?"italic":void 0}),O=(A,R)=>A===`
|
|
41
|
+
`?Ne.createElement("br",{key:R}):Ne.createElement(qt.Span,{tag:`say.word.${R}`,key:R,style:{...L(A),...ii(l.config.app.debug,{outline:"1px dashed red"})},className:Li("inline-block break-all",A.config.className)},A.config.ruby?Ne.createElement("ruby",{className:"align-bottom inline-block"},Ne.createElement("rt",{className:"block text-center"},A.config.ruby),A.text):A.text);return Ne.createElement("div",{...c,className:Li("whitespace-pre-wrap",e),style:{...S,...t}},d.map(O))}function sc({text:o,sentence:e,words:t,useTypeEffect:n=!0,loop:i=!0,restartDelay:r,cps:s,gameSpeed:a,pauseDuration:c,defaultColor:l,className:p,style:u,fontSize:d,fontWeight:g,fontWeightBold:f,fontFamily:T,onCompleted:h,...y}){let m=_r(),[,S]=Co(0),L=m?.config??J.DefaultConfig,O=m?.preference.getPreferences()??J.DefaultPreference,A=s??O.cps,R=a??O.gameSpeed,j=c??L.autoForwardDefaultPause,K=r??L.autoForwardDefaultPause,se=Ne.useMemo(()=>oc(o,e,t),[o,e,t]),Ge=Ne.useMemo(()=>rc(i,r,K),[i,r,K]),ke=ms(h),[At,Be]=Co(()=>n?[]:Ao(se));mn(()=>{if(m)return m.preference.onPreferenceChange(()=>{S(I=>I+1)}).cancel},[m]),mn(()=>{ke.current=h},[h]),mn(()=>{let I=!1,ye=[],ue=Math.max(.01,R),ae=N=>new Promise(_=>{let w=setTimeout(_,Math.max(0,N));ye.push(w)}),V=()=>{I||ke.current?.()};return n?se.length===0?(Be([]),()=>{I=!0}):((async()=>{do{let N=xo(se);for(Be([]);!I;){let{done:_,value:w}=N.next();if(_)break;if(Ie.isPause(w)){let ze=Ie.from(w);await ae((ze.config.duration??j)/ue)}else fs(Be,w),w===`
|
|
42
42
|
`?await ae(ds(A,R)):await ae(ds(w.cps??A,R))}if(I)return;V(),Ge.enabled&&await ae(Ge.delay)}while(!I&&Ge.enabled)})(),()=>{I=!0,ye.forEach(N=>clearTimeout(N))}):(Be(Ao(se)),V(),()=>{I=!0})},[se,n,Ge,A,R,j]);let ge=e?.config,G=f??"bold",ie={fontWeight:ge?.bold?G:g,fontSize:ge?.fontSize??d,color:Ii(ge?.color??l),fontFamily:ge?.fontFamily??T,fontStyle:ge?.italic?"italic":void 0},Z=I=>({fontWeight:I.config.bold||ge?.bold?G:g,fontSize:I.config.fontSize??ge?.fontSize??d,color:Ii(I.config.color??ge?.color??l),fontFamily:I.config.fontFamily??ge?.fontFamily??T,fontStyle:I.config.italic??ge?.italic?"italic":void 0}),q=(I,ye)=>I===`
|
|
43
|
-
`?Ne.createElement("br",{key:ye}):Ne.createElement("span",{key:ye,style:Z(I),className:Li("inline-block break-all",I.config.className)},I.config.ruby?Ne.createElement("ruby",{className:"align-bottom inline-block"},Ne.createElement("rt",{className:"block text-center"},I.config.ruby),I.text):I.text);return Ne.createElement("div",{...
|
|
44
|
-
This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function Gc({children:o,name:e,propagate:t}){let n=P(),[i]=te(),{path:r,router:s,consumedBy:a}=Un(),c=s.joinPath(r,e),l=Fi(()=>s.createToken(c+"@layout")),p=s.getCurrentPath(),u=Mc(!1),d=f=>{u.current=f,i()},g=s.matchPath(p,c);if(Hn(),Ki(f=>{let T=f.matchPath(f.getCurrentPath(),c);if(u.current&&!T){if(!o){d(!1);return}f.registerUnmountingPath(l)}T&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(l),T&&!u.current&&!f.isTransitioning()&&d(!0)},[g,o]),Nc(()=>{if(!g)return;let f=s.mount(c);return()=>{f.cancel()}},[c,s,g]),a)throw new k("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return Fn.createElement(On,{path:c},Fn.createElement(Oi,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),d(!1)}},g&&u.current&&o))}function Cs({children:o}){return Hn(),Fn.createElement(On,{path:Ut.rootPath},Fn.createElement(xi,{"data-layout-path":Ut.rootPath,key:Ut.rootPath},o))}var Ro=Hc(null);function Oc(){return Uc(Ro)}function Kc({children:o,name:e}){let[t]=te(),{path:n,router:i,consumedBy:r}=Un(),s=Oc(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,p=Fi(()=>i.createToken(l+"@page")),u=i.getCurrentPath(),d=!a,g=Fc(!1),f=m=>{g.current=m,t()},T=d&&i.exactMatch(u,n)||i.exactMatch(u,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.");Hn(),Ki(m=>{let y=d&&m.exactMatch(m.getCurrentPath(),n)||m.exactMatch(m.getCurrentPath(),l);if(g.current&&!y){if(!o){f(!1);return}m.registerUnmountingPath(p)}y&&m.isPathsUnmounting()&&m.unregisterUnmountingPath(p),y&&!g.current&&!m.isTransitioning()&&f(!0)},[T,o]),As(()=>{if(!T)return;let m=d?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{m.cancel()}},[l,T]),As(()=>()=>{i.unregisterUnmountingPath(p),f(!1)},[]);let h=Io.createElement(On,{path:n,consumedBy:c},Io.createElement(Oi,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(p),f(!1)}},T&&g.current&&o));return(m=>s?Io.createElement(Ro,{value:{name:null}},m):m)(h)}import No,{useCallback as Vc,useEffect as Mo,useImperativeHandle as Wc,useMemo as xs,useRef as Go,useState as Bc}from"react";var zc=50,$c={position:"relative",width:"100%",height:"100%",overflow:"hidden"},ws={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function jc(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function ks(o,e){return e==null?o:Math.max(o,e)}function qc(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 Ps=No.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:p,children:u},d){let g=Go(null),[f,T]=Bc({...ws,width:"0px",height:"0px"}),h=Go(p),S=Go(null);Mo(()=>{h.current=p},[p]);let m=Vc(()=>{let O=g.current;if(!O)return;let A=O.clientWidth,R=O.clientHeight;if(A<=0||R<=0||e<=0)return;let j=qc(A,R,e),K=ks(j.width,n),se=ks(j.height,i),Ge=S.current;(!Ge||Ge.width!==K||Ge.height!==se)&&(S.current={width:K,height:se},T({...ws,width:`${K}px`,height:`${se}px`}));let ke=t>0?K/t:1;h.current?.({width:K,height:se,scale:ke,containerWidth:A,containerHeight:R})},[e,t,n,i]),y=xs(()=>Pr(m,typeof r=="number"?r:zc),[m,r]);Mo(()=>{m()},[m]),Mo(()=>{let O=new ResizeObserver(()=>{y()});g.current&&O.observe(g.current);let A=()=>{y()};return window.addEventListener("resize",A),()=>{O.disconnect(),window.removeEventListener("resize",A)}},[y]),Wc(d,()=>({requestUpdate:m}),[m]);let D=xs(()=>jc(l),[l]);return No.createElement("div",{id:c,ref:g,style:$c,...D},No.createElement("div",{className:s,style:{...f,...a}},u))}),Es=Ps;function Qc(){return P().getLiveGame()}import Fo from"react";import Xc,{createContext as Yc,useContext as Jc,useEffect as Zc,useState as Ds}from"react";var _c={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},Ls=Yc({state:_c,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function St(){return Jc(Ls)}function Ho(){let{dialogs:o}=St();return o}function el(){let{isActive:o}=St();return o}function tl(){let{isVisible:o}=St();return o}function Uo({children:o}){let t=P().getLiveGame().getGameState(),[n,i]=Ds(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=Ds(null);Zc(()=>{let c=f=>({...f,dialogs:[...f.dialogs]}),l=t.events.on(E.EventTypes["event:state.nvl.enter"],(f,T)=>{i(c(t.getNvlState())),s(T?.showTransition||null)}),p=t.events.on(E.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState()))}),u=t.events.on(E.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),d=t.events.on(E.EventTypes["event:state.nvl.visibilityChange"],(f,T)=>{i(c(t.getNvlState())),s(T||null)}),g=t.events.on(E.EventTypes["event:state.nvl.change"],f=>{i(c(f))});return()=>{l.cancel(),p.cancel(),u.cancel(),d.cancel(),g.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return Xc.createElement(Ls.Provider,{value:a},o)}import{AnimatePresence as nl,motion as il}from"motion/react";import ol from"clsx";function Oo({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=St(),{ratio:r}=fe(),s=P(),a=i?.duration?i.duration/1e3:.3;return Fo.createElement(nl,null,n&&Fo.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},Fo.createElement(il.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:ol("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 Yt from"react";function Ko({renderDialogItem:o,dialogs:e}){return Yt.createElement(Oo,{className:"bg-black/80 text-white p-16 inset-8"},Yt.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?Yt.createElement(Lt,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=Yt.createElement(Ft,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return Yt.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}):Yt.createElement(Yt.Fragment,null,r,s))})))}import tt,{useMemo as rl}from"react";import Is from"clsx";function sl({children:o,className:e,style:t,renderDialogItem:n}){let i=Ho(),{state:r}=St();return tt.createElement("div",{"data-element-type":"nvl-dialog-list",className:Is("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>tt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},tt.createElement(al,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?tt.createElement(Lt,{className:"nvl-character-name font-bold mr-2"}):null,texts:tt.createElement(Ft,{className:"nvl-dialog-text"})}):o?tt.Children.map(o,c=>tt.isValidElement(c)?tt.cloneElement(c,{entry:s,index:a}):c):tt.createElement(Rs,{entry:s,index:a})))))}function Rs({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??tt.createElement(Ft,{className:"nvl-dialog-text"});return tt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:Is("nvl-dialog-item",t),style:n},r&&tt.createElement(Lt,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function al({entry:o,children:e}){let n=P().getLiveGame().getGameState(),i=rl(()=>o.sentence.evaluate(Se.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=Di({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return tt.createElement(Qt,{value:c},e)}function Ms({state:o}){let e=P(),t=yt(),n=Vo(null),i=Vo(null),r=Vo(!1),[s]=at(J.Preferences.skipDelay),[a]=at(J.Preferences.skipInterval),[c]=Xt("skipAction");return ll(()=>{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 p=()=>{i.current&&(clearTimeout(i.current),i.current=null),n.current&&(clearInterval(n.current),n.current=null),r.current=!1},u=g=>{if(e.keyMap.match("skipAction",g.key)&&e.preference.getPreference(J.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)};p(),o.events.emit(E.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?f():i.current=setTimeout(f,s)}},d=g=>{e.keyMap.match("skipAction",g.key)&&p()};if(e.config.useWindowListener){let g=e.getLiveGame().onWindowEvent("keydown",u).cancel,f=e.getLiveGame().onWindowEvent("keyup",d).cancel;return()=>{p(),g(),f()}}else{let g=e.getLiveGame().onPlayerEvent("keydown",u).cancel,f=e.getLiveGame().onPlayerEvent("keyup",d).cancel;return()=>{p(),g(),f()}}},[t,s,a,c]),Ns.createElement(Ns.Fragment,null)}import Gs,{useEffect as ul}from"react";function pl(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var Hs=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],dl=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]'];function ml(o,e){return!o||e&&Hs.some(t=>!!o.closest(t))?!1:[...dl,...Hs].some(t=>!!o.closest(t))}function Us(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 Fs({state:o}){let e=P();return ul(()=>{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)||!Us(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!Us(i,s))||pl(r)||ml(r,o.isNvlMode())||(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]),Gs.createElement(Gs.Fragment,null)}import{useEffect as Kn}from"react";function Wo({gameState:o}){let e=o.audioManager,[t]=at("voiceVolume"),[n]=at("bgmVolume"),[i]=at("soundVolume"),[r,s]=at("globalVolume");return Kn(()=>{s(e.getGlobalVolume())},[]),Kn(()=>{e.setGroupVolume("voice",t)},[t]),Kn(()=>{e.setGroupVolume("bgm",n)},[n]),Kn(()=>{e.setGroupVolume("sound",i)},[i]),Kn(()=>{e.setGlobalVolume(r)},[r]),null}import{useEffect as Wi,useRef as gl}from"react";import Bo,{createContext as fl,useContext as hl,useState as Os}from"react";var Jt=class Jt{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(Jt.EventTypes["event:preloaded.add"],e),this.events.emit(Jt.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(Jt.EventTypes["event:preloaded.remove"],e),this.events.emit(Jt.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Ue.getSrc(e)}};Jt.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 Me=Jt;var Vi=class o{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear()})}static getImage(e,t,n){return Dr(e,{...n,signal: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}get(e){return this.src.get(e)}clear(){return this.src.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t){if(this.src.has(t)||this.preloadTasks.has(t)){let u={abort:()=>{},onFinished:()=>u,onErrored:()=>u};return u}let n=t,i={};this.game.hooks.rawTrigger("preloadImage",()=>[n,(u,d)=>{n=u,i={...i,...d}}]);let r=new AbortController,s=r.signal,a=[],l={promise:o.getImage(n,s,i).then(u=>{this.preloadTasks.delete(t),u&&this.add(t,u)}).catch(u=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${u}`),a.forEach(d=>d(u))}),controller:r};this.preloadTasks.set(t,l);let p={abort:()=>{r.abort(),this.preloadTasks.delete(t)},onFinished:u=>(l.promise.then(u),p),onErrored:u=>(a.push(u),p)};return p}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){for(let t of this.src.keys())e.includes(t)||this.src.delete(t);return this}};var zo=fl(null);function Ks({children:o}){let e=P(),[t]=Os(()=>new Me),[n]=Os(()=>new Vi(e));return Bo.createElement(Bo.Fragment,null,Bo.createElement(zo,{value:{preloaded:t,cacheManager:n}},o))}function fn(){if(!zo)throw new Error("usePreloaded must be used within a PreloadedProvider");return hl(zo)}function Vs({state:o}){let{preloaded:e,cacheManager:t}=fn(),n=P(),i=gl(new Set),[r]=te(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function p(){o.logger.debug(s,"Preload unmounted"),e.events.emit(Me.EventTypes["event:preloaded.unmount"])}return Wi(()=>o.events.on(E.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),Wi(()=>{if(typeof fetch>"u")return e.events.emit(Me.EventTypes["event:preloaded.complete"]),e.events.emit(Me.EventTypes["event:preloaded.ready"]),o.logger.warn(s,"Fetch is not supported in this environment, skipping preload"),p;if(!n.config.preloadAllImages)return e.events.emit(Me.EventTypes["event:preloaded.complete"]),e.events.emit(Me.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),p;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"),p;let u=performance.now(),d=Ue.catSrc([...a.srcManager?.src||[],...a.srcManager?.getFutureSrc()||[]]),g=new bn(n.config.preloadConcurrency,n.config.preloadDelay),f=[],T=o.logger.group(s,!0),h=[];o.logger.debug(s,"preloading:",d,a);for(let S of d.image){let m=Ue.getSrc(S);if(m){if(f.push(m),t.has(m)||t.isPreloading(m)||h.includes(m)){o.logger.debug(s,`Image already loaded (${d.image.indexOf(S)+1}/${d.image.length})`,m),h.push(m);continue}h.push(m),g.addTask(()=>new Promise(y=>{t.preload(o,m).onFinished(()=>{o.logger.debug(s,`Image loaded (${d.image.indexOf(S)+1}/${d.image.length})`,m),y()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${d.image.indexOf(S)+1}/${d.image.length})`,m),y()})}))}}return T.end(),g.start().then(()=>{o.logger.info(s,"Image preload",`loaded ${t.size()} images in ${performance.now()-u}ms`),e.events.emit(Me.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit(Me.EventTypes["event:preloaded.ready"]),t.filter(f)}),n.config.waitForPreload||e.events.emit(Me.EventTypes["event:preloaded.ready"]),e.events.emit(Me.EventTypes["event:preloaded.mount"]),p},[a,l]),Wi(()=>{i.current.clear()},[a]),Wi(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let u=performance.now(),d=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(m=>Ue.getPreloadableSrc(l,m)).filter(function(m){return m!==null});d.filter(function(m){return m?.activeType==="scene"}).forEach(m=>{i.current.has(m)||i.current.add(m)});let f=Ue.catSrc([...i.current,...d]),T=new bn(n.config.preloadConcurrency,n.config.preloadDelay),h=[],S=o.logger.group(s);o.logger.debug(s,"preloading:",f);for(let m of f.image){let y=Ue.getSrc(m);if(y){if(h.push(y),t.has(y)||t.isPreloading(y)){o.logger.debug(s,`Image already loaded (${f.image.indexOf(m)+1}/${f.image.length})`,y);continue}T.addTask(()=>new Promise(D=>{t.preload(o,y).onFinished(()=>{o.logger.debug(s,`Image loaded (${f.image.indexOf(m)+1}/${f.image.length})`,y),D()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${f.image.indexOf(m)+1}/${f.image.length})`,y),D()})}))}}S.end(),T.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-u}ms`),t.filter(h)})},[c,l]),null}import yl from"clsx";import Tt,{useCallback as $o,useMemo as vl,useRef as Sl}from"react";function jo({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=P(),a=Sl([]),c=$o(f=>(a.current.push(f),a.current.indexOf(f)),[]),l=$o(f=>{let T=a.current.indexOf(f);T!==-1&&a.current.splice(T,1)},[]),p=$o(f=>a.current.indexOf(f),[]),u=s.config.menu,d=vl(()=>e.map(f=>({...f,words:f.prompt.evaluate(Se.getCtx({gameState:n}))})),[]);function g(f){t(f)}return Tt.createElement(Tt.Fragment,null,Tt.createElement(ko,{value:{evaluated:d,choose:g,gameState:n}},Tt.createElement(Eo,{value:{register:c,unregister:l,getIndex:p}},Tt.createElement(vt,{className:"absolute"},r&&o&&Tt.createElement(Mn,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),Tt.createElement(qt.Div,{color:"green",border:"dashed",className:yl("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},Tt.createElement(u,{items:d.map((f,T)=>T)})))))}function Ws({items:o}){return Tt.createElement(wi,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>Tt.createElement(Mi,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import qi from"react";import Bi from"react";import qo,{useEffect as Qo,useLayoutEffect as Xo,useRef as Yo,useState as Jo}from"react";function hn({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c}){let[l,p]=Jo(null),[u,d]=Jo(null),g=qo.useRef(null),[f]=Jo(()=>new Jn("displayable.refGroup")),T=Yo(f.next()),h=Yo(Be()),m=P().getLiveGame().getGameState(),y=typeof a=="function"?a(l):a,[D]=te([u,l,h]);Qo(()=>m.events.depends([m.events.on(E.EventTypes["event:state.player.skip"],At)]).cancel,[u,l,h]),Xo(()=>{if(R(),!l)return;if(h.current.some(([q])=>!q.current))throw new k("Displayable: Trying to access transition groups before they are mounted");let{controller:G,task:ie}=l;return G.onUpdate(q=>{h.current.forEach(([I],ye)=>{let ue=ie.resolve[ye],ae=typeof ue=="function"?ue:ue.resolver;if(!ae)throw new k(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${ye}])`);let V=ae(...q),x=U(y[ye]||y[y.length-1]||{},V);K(I,c?c(x):x)})}).cancel},[l]),Qo(()=>{if(!g.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),Xo(()=>{let G=e.toStyle(m,i);Object.assign(g.current.style,G),m.logger.debug("Displayable","Initial style applied",g.current,G)},[]);let O=Yo(()=>{});O.current=()=>{u||l||!g.current||Object.assign(g.current.style,e.toStyle(m,i))},Xo(()=>{O.current()});let{ratio:A}=fe();Qo(()=>A.onUpdate(()=>{O.current(),requestAnimationFrame(()=>O.current())}),[A]);function R(){let G=typeof a=="function"?a(l):a;if(!h.current||!h.current.length)throw new k("Displayable: Transition group refs are not initialized correctly");if(h.current.some(([ie])=>!ie.current))throw new k("Displayable: Trying to access transition groups before they are mounted");h.current.forEach(([ie],Z)=>{if(!ie.current)throw new k("Displayable: Trying to assign properties to unmounted element");K(ie,G[Z]||G[G.length-1]||{})})}function j(G){m.logger.debug("Displayable","Transform applied",e.toStyle(m,i),g.current),D(),r?.(G)}function K(G,ie){if(!G.current)throw new k("Displayable: Trying to assign properties to unmounted element");let Z=G.current,q={},I={};Object.keys(ie).forEach(ue=>{let ae=ue;ae==="style"&&ie.style?Object.assign(q,ie.style):ie[ae]!==void 0&&ae!=="key"&&(I[ae]=ie[ae])}),Object.keys(q).length>0&&Object.assign(Z.style,q);let ye=c?c(I):I;for(let[ue,ae]of Object.entries(ye))Z.getAttribute(ue)!==ae&&Z.setAttribute(ue,ae)}function se(G,ie){u&&(u.abort(),d(null));let Z=G.animate(e,{gameState:m,ref:g,overwrites:i}),q=new we(Z);return m.timelines.attachTimeline(q),Z.onSkipControllerRegister(I=>{I.onAbort(()=>{q.abort(),d(null)})}),d(Z),Z.then(()=>{d(null),j(G),ie()}),q}function Ge(G,ie){l&&l.controller.complete();let Z=G.createTask(m),q=G.requestAnimations(Z.animations),I=new v().registerSkipController(new H(q.cancel)),ye=new we(I);I.skipController.onAbort(()=>{q.cancel()}),q.onCanceled(()=>{ye.abort(),p(null),m.logger.debug("Displayable","Transition cancelled",G)}),m.timelines.attachTimeline(ye),p({task:Z,controller:q,transition:G,resolve:ie});let ue;if(h.current=Z.resolve.map(V=>{let x=qo.createRef(),N=typeof V=="function"?void 0:V.key;if(!N)return[x,f.next()];if(N==="target")return ue=f.next(),[x,ue];if(N==="current")return[x,T.current];throw new k("Displayable: Invalid key type")}),!ue)throw new k("Displayable: No target key found");T.current=ue;let ae=h.current.map(([V])=>{let x=V.current;return x?.waitForLoad?x.waitForLoad():Promise.resolve()});return Promise.all(ae).then(()=>{q.start(),q.onComplete(()=>{ge(),p(null),s?.(G),ie(),I.resolve()})}),ye}function ke(G){return m.logger.debug("initDisplayable",o),se(Y.immediate(e.get()),G)}function At(){t&&u&&(u.abort(),d(null),m.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),m.logger.debug("transition skipped"))}function Be(){return[[qo.createRef(),T.current]]}function ge(){h.current.forEach(([G])=>{G.current=null}),h.current=Be()}return{transformRef:g,transitionRefs:h.current,isTransforming:!!u,transitionTask:l,initDisplayable:ke,applyTransform:se,applyTransition:Ge,updateStyleSync:R,deps:[u,l,h]}}import{useEffect as Tl}from"react";function Ot(o,e,t=[]){let i=P().getLiveGame().getGameState();return Tl(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function Zo({state:o,text:e}){let{ratio:t}=fe(),[n]=te(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:p,isTransforming:u}=hn({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:d=>({width:"fit-content",transform:Y.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 Ot(e,{initDisplayable:s,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...p]),Bi.createElement(qt.Div,{"data-element-type":"text"},Bi.createElement(qt.mDiv,{tag:"text.container",color:"green",border:"dashed",layout:u,ref:i,className:"absolute"},r.map(([d,g])=>Bi.createElement("span",{key:g,ref:d,className:e.config.className},Bi.createElement("span",null,e.state.text)))))}import gn,{useRef as $s,useState as js}from"react";import zi,{useEffect as _o,useRef as $i,forwardRef as bl}from"react";var Bs=bl(({onSizeChanged:o,onLoad:e,autoFit:t=!1},n)=>{let i=$i(null),{ratio:r}=fe(),[s,a]=zi.useState(()=>r.state.width),[c,l]=zi.useState(()=>r.state.height),p=P(),u=$i(!1),d=$i(null),g=$i(null);zi.useImperativeHandle(n,()=>i.current,[]),_o(()=>{i.current&&Object.defineProperties(i.current,{isLoaded:{value:()=>u.current,configurable:!0},waitForLoad:{value:()=>u.current?Promise.resolve():(d.current||(d.current=new Promise(h=>{g.current=h})),d.current),configurable:!0}})},[]),_o(()=>(f(),r.onUpdate(f)),[o]),_o(()=>{let h=new MutationObserver(S=>{S.forEach(m=>{m.type==="attributes"&&m.attributeName==="src"&&i.current&&f()})});return i.current&&h.observe(i.current,{attributes:!0}),()=>{h.disconnect()}},[o]);function f(){if(i.current&&i.current.naturalWidth)if(i.current.naturalWidth*i.current.naturalHeight===1){let h=r.state.width,S=r.state.height,m=`${h} / ${S}`;a(h),l(S),i.current.style.aspectRatio=m,o&&o(h,S)}else{let h=t?p.config.width/i.current.naturalWidth:1,S=i.current.naturalWidth*r.state.scale*h,m=i.current.naturalHeight*r.state.scale*h;a(S),l(m),i.current.style.aspectRatio="auto",o&&o(S,m)}}function T(){f(),u.current=!0,g.current&&(g.current(),g.current=null,d.current=null),e&&e()}return zi.createElement("img",{ref:i,onLoad:T,width:s,height:c,alt:""})});Bs.displayName="AspectScaleImage";var zs=Bs;import qs from"clsx";import{motion as Cl}from"motion/react";function ji({image:o,state:e}){let[t]=js(()=>new Q),[n,i]=js([]),{cacheManager:r}=fn(),s=$s([]),a=$s(null),{transformRef:c,transitionRefs:l,isTransforming:p,initDisplayable:u,applyTransition:d,applyTransform:g,updateStyleSync:f,deps:T}=hn({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:m=>{let y=m?m.transition._getCurrentSrc():o.state.currentSrc;return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:C.isColor(y)?C.colorToString(y):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:C.isImageSrc(y)?C.srcToURL(y):M.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:m=>m.src?(!C.isDataURI(m.src)&&!r.has(m.src)&&!r.isPreloading(m.src)&&!s.current.includes(m.src)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${m.src}".
|
|
43
|
+
`?Ne.createElement("br",{key:ye}):Ne.createElement("span",{key:ye,style:Z(I),className:Li("inline-block break-all",I.config.className)},I.config.ruby?Ne.createElement("ruby",{className:"align-bottom inline-block"},Ne.createElement("rt",{className:"block text-center"},I.config.ruby),I.text):I.text);return Ne.createElement("div",{...y,className:Li("whitespace-pre-wrap",p),style:{...ie,...u}},At.map(q))}function hs(o){return Ne.createElement(wo,{...o,key:o.dialog?.config.action.id})}function ac({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i,...r}){let s=Di({entry:o,gameState:e,words:t,useTypeEffect:n,isActive:i});return Ne.createElement(wo,{...r,dialog:s,key:s.config.action.id})}function cc(o){let e=ct();return Ne.createElement(wo,{...o,dialog:e,key:e.config.action.id})}function Ft(o){return"entry"in o&&o.entry&&"gameState"in o&&o.gameState&&"words"in o&&o.words?Ne.createElement(ac,{...o}):Ne.createElement(cc,{...o})}var lc=Ft;import Ni,{useEffect as uc,useLayoutEffect as pc,useMemo as ys,useRef as dc,useState as mc}from"react";import Ri from"react";var ko=Ri.createContext(null);function Po(){let o=Ri.useContext(ko);if(!o)throw new Error("useUIMenuContext must be used within a UIMenuContext");return o}var Eo=Ri.createContext(null);function gs(){let o=Ri.useContext(Eo);if(!o)throw new Error("useUIListContext must be used within a UIListContext");return o}function Mi({className:o,style:e,bindKey:t,defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a}){let c=dc(null),{register:l,unregister:p,getIndex:u}=gs(),[d,g]=mc(-1),{choose:f,evaluated:T,gameState:h}=Po(),y=d===-1?null:T[d],m=ys(()=>Se.getCtx({gameState:h}),[h]),{hidden:S,disabled:L}=ys(()=>{if(!y)return{hidden:!1,disabled:!1};let R=y.config.hidden?.evaluate(m)?.value??!1,j=!R&&(y.config.disabled?.evaluate(m)?.value??!1);return{hidden:R,disabled:j}},[y,m]);pc(()=>{if(!c.current)return;let R=c;l(R);let j=u(R);return g(j),c.current.dataset.index=j.toString(),()=>p(R)},[l,p,u]),uc(()=>{if(!t)return;let R=j=>{j.key.toLowerCase()===t.toLowerCase()&&!j.ctrlKey&&!j.metaKey&&(j.preventDefault(),j.stopPropagation(),O())};return window.addEventListener("keydown",R,!0),()=>{window.removeEventListener("keydown",R,!0)}},[t]);function O(){if(d===-1||!T[d]||S||L)return;let R=T[d];f({...R,evaluated:$.getText(R.words||[])})}let A=y&&!S;return Ni.createElement(Ni.Fragment,null,Ni.createElement("button",{className:o,style:{...e,display:A?e?.display??void 0:"none"},onClick:O,ref:c,disabled:L},A&&Ni.createElement(hs,{defaultColor:n,fontSize:i,fontWeight:r,fontWeightBold:s,fontFamily:a,dialog:new Ce({useTypeEffect:!1,action:{sentence:y.prompt,words:y.words,character:null},gameState:h,evaluatedWords:y.words})})))}import Gi from"react";import{AnimatePresence as fc}from"motion/react";function Hi({children:o,...e}){let t=fc;return Gi.createElement(Gi.Fragment,null,Gi.createElement("div",{...e},Gi.createElement(t,null,o)))}import vs from"react";function Lt({entry:o,character:e,name:t,color:n,children:i,style:r,...s}){let a=vs.useContext(Qt),c=e??o?.character??a?.config.action.character??null,l=n??c?.config.color,p=i??t??c?.state.name;return vs.createElement("div",{...s,style:{color:l?nn(l):void 0,...r}},p)}import hc from"clsx";import gc from"react";function Ss(){let o=ct(),{action:e,gameState:t}=o.config,n=e.character,i=e.sentence;if(!n||!i||!n.state.name)return Sc(n||null,null);let r=t.findCurrentPortraitForCharacter(n),s=r?.image||null,a=s?M.getSrcURL(s):null,c=s&&M.isTagSrc(s)?[...s.state.currentSrc]:null,l=qr({character:n,sentence:i,portrait:s,currentSrc:a,tags:c,gameState:t,sentenceAvatar:i.config.avatar,portraitAvatar:r?.avatar,characterAvatar:n.config.avatar}),p=vc(l.source);return{visible:!!p,src:p,character:l.character,portrait:l.portrait,alt:n.state.name?`${n.state.name} avatar`:"dialog avatar"}}function yc({className:o,style:e,alt:t,...n}){let i=Ss();return!i.visible||!i.src?null:gc.createElement("img",{...n,"data-element-type":"dialog-avatar",className:hc("dialog-avatar",o),src:i.src,alt:t??i.alt,style:{width:96,height:96,objectFit:"cover",borderRadius:6,flex:"0 0 auto",...e}})}function vc(o){return o?C.srcToURL(o):null}function Sc(o,e){return{visible:!1,src:null,character:o,portrait:e,alt:o?.state.name?`${o.state.name} avatar`:"dialog avatar"}}var Do=yc;import{useEffect as Tc}from"react";function bc(){let o=ct(),[e]=te(o.deps),t=$.getText(o.config.evaluatedWords);return Tc(()=>o.events.on(Ce.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 Ui,useEffect as Lo,useMemo as Cc,useRef as Ac,useState as Ts}from"react";function xc(){let o=ct(),[e]=te(o.deps),[t,n]=Ts(!0),[i,r]=Ts(!0),s=Ac(null),a=o.config.gameState,c=o.config.action.sentence,l=c?.config.voiceId??null;Lo(()=>o.events.on(Ce.Events.onFlush,()=>{e()}).cancel,[o]);let p=Cc(()=>{if(!c)return null;try{return st.getVoice(a,c)}catch{return null}},[a,c,l,c?.config.voice]);Lo(()=>{s.current=null,r(!0)},[c]),Lo(()=>{let T=!1,h=null,y=null,m=null;if(!p){n(!0);return}n(!1);let S=()=>{T||n(!0)};h=a.audioManager.getToken(p),h&&(h.isPlaying()||n(!0),y=()=>S(),m=()=>S(),h.once("ended",y),h.once("stop",m));let L=a.events.on(E.EventTypes["event:state.player.lineEnd"],()=>{S()});return()=>{T=!0,L.cancel(),h&&y&&h.off("ended",y),h&&m&&h.off("stop",m)}},[a,p]);let u=Ui(async T=>{let h=T??p;if(!h)return r(!0),null;s.current?.isPlaying()&&s.current.stop(),r(!1);let y=h instanceof URL?pe.voice(h.toString()):typeof h=="string"?pe.voice(h):h,m=await a.getLiveGame().playSound(y);s.current=m;let S=()=>{r(!0)};return m.once("ended",S),m.once("stop",S),m},[a,p]),d=Ui(()=>p,[p]),g=Ui(()=>l,[l]),f=Ui(()=>p?.getSrc()??null,[p]);return{done:t&&i,voice:p,playVoice:u,getVoice:d,getVoiceId:g,getVoiceSrc:f}}import Io,{createContext as Hc,useContext as Uc,useEffect as As,useRef as Fc}from"react";import{useState as wc}from"react";function Fi(o){let[e]=wc(o);return e}import{AnimatePresence as kc}from"motion/react";var Oi=kc;import Fn,{createContext as Ic,useContext as Rc,useEffect as Nc,useRef as Mc}from"react";import{useEffect as Gn,useLayoutEffect as Pc}from"react";function Ec(){let o=yt(),[e]=te();return Gn(()=>o.onChange(e).cancel,[]),o.getPathname()}function Dc(){let{router:o,path:e}=Un(),[t]=te();return Gn(()=>o.onChange(t).cancel,[]),o.extractParams(o.getCurrentPath(),e)}function Lc(){let o=yt(),[e]=te();return Gn(()=>o.onChange(e).cancel,[]),o.getQueryParams()}function Ki(o,e){let t=yt();Pc(()=>t.onUpdate(()=>o(t)).cancel,e),Gn(()=>{o(t)},[])}function Hn(){let o=yt(),[e]=te();return Gn(()=>o.onChange(e).cancel,[]),e}var bs=Ic(null);function On({children:o,path:e,consumedBy:t}){let i={router:yt(),path:e,consumedBy:t};return Fn.createElement(bs,{value:i},o)}function Un(){let o=Rc(bs);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.
|
|
44
|
+
This is likely caused by a nested Layout component or using Page inside a Page. `);return o}function Gc({children:o,name:e,propagate:t}){let n=P(),[i]=te(),{path:r,router:s,consumedBy:a}=Un(),c=s.joinPath(r,e),l=Fi(()=>s.createToken(c+"@layout")),p=s.getCurrentPath(),u=Mc(!1),d=f=>{u.current=f,i()},g=s.matchPath(p,c);if(Hn(),Ki(f=>{let T=f.matchPath(f.getCurrentPath(),c);if(u.current&&!T){if(!o){d(!1);return}f.registerUnmountingPath(l)}T&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(l),T&&!u.current&&!f.isTransitioning()&&d(!0)},[g,o]),Nc(()=>{if(!g)return;let f=s.mount(c);return()=>{f.cancel()}},[c,s,g]),a)throw new k("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return Fn.createElement(On,{path:c},Fn.createElement(Oi,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{s.unregisterUnmountingPath(l),d(!1)}},g&&u.current&&o))}function Cs({children:o}){return Hn(),Fn.createElement(On,{path:Ut.rootPath},Fn.createElement(xi,{"data-layout-path":Ut.rootPath,key:Ut.rootPath},o))}var Ro=Hc(null);function Oc(){return Uc(Ro)}function Kc({children:o,name:e}){let[t]=te(),{path:n,router:i,consumedBy:r}=Un(),s=Oc(),a=s?.name??e,c=a??n+"@default",l=a?i.joinPath(n,a):n,p=Fi(()=>i.createToken(l+"@page")),u=i.getCurrentPath(),d=!a,g=Fc(!1),f=m=>{g.current=m,t()},T=d&&i.exactMatch(u,n)||i.exactMatch(u,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.");Hn(),Ki(m=>{let S=d&&m.exactMatch(m.getCurrentPath(),n)||m.exactMatch(m.getCurrentPath(),l);if(g.current&&!S){if(!o){f(!1);return}m.registerUnmountingPath(p)}S&&m.isPathsUnmounting()&&m.unregisterUnmountingPath(p),S&&!g.current&&!m.isTransitioning()&&f(!0)},[T,o]),As(()=>{if(!T)return;let m=d?i.mountDefaultHandler(l):i.mount(l);return i.emitOnPageMount(),()=>{m.cancel()}},[l,T]),As(()=>()=>{i.unregisterUnmountingPath(p),f(!1)},[]);let h=Io.createElement(On,{path:n,consumedBy:c},Io.createElement(Oi,{mode:"wait",onExitComplete:()=>{i.unregisterUnmountingPath(p),f(!1)}},T&&g.current&&o));return(m=>s?Io.createElement(Ro,{value:{name:null}},m):m)(h)}import No,{useCallback as Vc,useEffect as Mo,useImperativeHandle as Wc,useMemo as xs,useRef as Go,useState as Bc}from"react";var zc=50,$c={position:"relative",width:"100%",height:"100%",overflow:"hidden"},ws={margin:"auto",position:"absolute",top:0,bottom:0,left:0,right:0,display:"flex",alignItems:"center",justifyContent:"center"};function jc(o){return o?Object.entries(o).reduce((e,[t,n])=>(e[`data-${t}`]=n,e),{}):{}}function ks(o,e){return e==null?o:Math.max(o,e)}function qc(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 Ps=No.forwardRef(function({aspectRatio:e,baseWidth:t,minWidth:n,minHeight:i,debounceMs:r,className:s,style:a,id:c,dataAttributes:l,onUpdate:p,children:u},d){let g=Go(null),[f,T]=Bc({...ws,width:"0px",height:"0px"}),h=Go(p),y=Go(null);Mo(()=>{h.current=p},[p]);let m=Vc(()=>{let O=g.current;if(!O)return;let A=O.clientWidth,R=O.clientHeight;if(A<=0||R<=0||e<=0)return;let j=qc(A,R,e),K=ks(j.width,n),se=ks(j.height,i),Ge=y.current;(!Ge||Ge.width!==K||Ge.height!==se)&&(y.current={width:K,height:se},T({...ws,width:`${K}px`,height:`${se}px`}));let ke=t>0?K/t:1;h.current?.({width:K,height:se,scale:ke,containerWidth:A,containerHeight:R})},[e,t,n,i]),S=xs(()=>Pr(m,typeof r=="number"?r:zc),[m,r]);Mo(()=>{m()},[m]),Mo(()=>{let O=new ResizeObserver(()=>{S()});g.current&&O.observe(g.current);let A=()=>{S()};return window.addEventListener("resize",A),()=>{O.disconnect(),window.removeEventListener("resize",A)}},[S]),Wc(d,()=>({requestUpdate:m}),[m]);let L=xs(()=>jc(l),[l]);return No.createElement("div",{id:c,ref:g,style:$c,...L},No.createElement("div",{className:s,style:{...f,...a}},u))}),Es=Ps;function Qc(){return P().getLiveGame()}import Fo from"react";import Xc,{createContext as Yc,useContext as Jc,useEffect as Zc,useState as Ds}from"react";var _c={active:!1,visible:!1,sessionId:null,dialogs:[],options:null,activeDialogId:null,phase:"idle",pendingAdvance:!1,isTyping:!1},Ls=Yc({state:_c,dialogs:[],isActive:!1,isVisible:!1,transitionOptions:null});function St(){return Jc(Ls)}function Ho(){let{dialogs:o}=St();return o}function el(){let{isActive:o}=St();return o}function tl(){let{isVisible:o}=St();return o}function Uo({children:o}){let t=P().getLiveGame().getGameState(),[n,i]=Ds(()=>({...t.getNvlState(),dialogs:[...t.getNvlState().dialogs]})),[r,s]=Ds(null);Zc(()=>{let c=f=>({...f,dialogs:[...f.dialogs]}),l=t.events.on(E.EventTypes["event:state.nvl.enter"],(f,T)=>{i(c(t.getNvlState())),s(T?.showTransition||null)}),p=t.events.on(E.EventTypes["event:state.nvl.exit"],()=>{i(c(t.getNvlState()))}),u=t.events.on(E.EventTypes["event:state.nvl.dialogAppend"],()=>{i(c(t.getNvlState()))}),d=t.events.on(E.EventTypes["event:state.nvl.visibilityChange"],(f,T)=>{i(c(t.getNvlState())),s(T||null)}),g=t.events.on(E.EventTypes["event:state.nvl.change"],f=>{i(c(f))});return()=>{l.cancel(),p.cancel(),u.cancel(),d.cancel(),g.cancel()}},[t]);let a={state:n,dialogs:n.dialogs,isActive:n.active,isVisible:n.visible,transitionOptions:r};return Xc.createElement(Ls.Provider,{value:a},o)}import{AnimatePresence as nl,motion as il}from"motion/react";import ol from"clsx";function Oo({children:o,className:e,style:t}){let{isVisible:n,transitionOptions:i}=St(),{ratio:r}=fe(),s=P(),a=i?.duration?i.duration/1e3:.3;return Fo.createElement(nl,null,n&&Fo.createElement("div",{className:"absolute inset-0 p-6","data-element-type":"nvl-container-wrapper"},Fo.createElement(il.div,{key:"nvl-container",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:a},"data-element-type":"nvl-container",className:ol("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 Yt from"react";function Ko({renderDialogItem:o,dialogs:e}){return Yt.createElement(Oo,{className:"bg-black/80 text-white p-16 inset-8"},Yt.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?Yt.createElement(Lt,{className:"nvl-character-name font-bold mr-2",entry:n.entry}):null,s=Yt.createElement(Ft,{className:"nvl-dialog-text",entry:n.entry,gameState:n.gameState,words:n.words,useTypeEffect:n.useTypeEffect,isActive:n.isActive});return Yt.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}):Yt.createElement(Yt.Fragment,null,r,s))})))}import tt,{useMemo as rl}from"react";import Is from"clsx";function sl({children:o,className:e,style:t,renderDialogItem:n}){let i=Ho(),{state:r}=St();return tt.createElement("div",{"data-element-type":"nvl-dialog-list",className:Is("flex flex-col space-y-4 p-4",e),style:t},i.map((s,a)=>tt.createElement("div",{key:`${s.id}:${r.activeDialogId===s.id?r.phase:"idle"}`},tt.createElement(al,{entry:s},n?n({entry:s,index:a,isActive:r.activeDialogId===s.id,nametag:s.character?tt.createElement(Lt,{className:"nvl-character-name font-bold mr-2"}):null,texts:tt.createElement(Ft,{className:"nvl-dialog-text"})}):o?tt.Children.map(o,c=>tt.isValidElement(c)?tt.cloneElement(c,{entry:s,index:a}):c):tt.createElement(Rs,{entry:s,index:a})))))}function Rs({entry:o,index:e,className:t,style:n,texts:i}){let r=o.character?.state.name||null,s=i??tt.createElement(Ft,{className:"nvl-dialog-text"});return tt.createElement("div",{"data-element-type":"nvl-dialog-item","data-dialog-index":e,className:Is("nvl-dialog-item",t),style:n},r&&tt.createElement(Lt,{entry:o,className:"nvl-character-name font-bold mr-2"},r,":"),s)}function al({entry:o,children:e}){let n=P().getLiveGame().getGameState(),i=rl(()=>o.sentence.evaluate(Se.getCtx({gameState:n})),[o.sentence,n]),r=n.getNvlState(),s=r.activeDialogId===o.id,a=s&&r.phase==="typing",c=Di({entry:o,gameState:n,words:i,isActive:s,useTypeEffect:a});return tt.createElement(Qt,{value:c},e)}function Ms({state:o}){let e=P(),t=yt(),n=Vo(null),i=Vo(null),r=Vo(!1),[s]=at(J.Preferences.skipDelay),[a]=at(J.Preferences.skipInterval),[c]=Xt("skipAction");return ll(()=>{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 p=()=>{i.current&&(clearTimeout(i.current),i.current=null),n.current&&(clearInterval(n.current),n.current=null),r.current=!1},u=g=>{if(e.keyMap.match("skipAction",g.key)&&e.preference.getPreference(J.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)};p(),o.events.emit(E.EventTypes["event:state.player.skip"],!1),r.current=!0,s===0?f():i.current=setTimeout(f,s)}},d=g=>{e.keyMap.match("skipAction",g.key)&&p()};if(e.config.useWindowListener){let g=e.getLiveGame().onWindowEvent("keydown",u).cancel,f=e.getLiveGame().onWindowEvent("keyup",d).cancel;return()=>{p(),g(),f()}}else{let g=e.getLiveGame().onPlayerEvent("keydown",u).cancel,f=e.getLiveGame().onPlayerEvent("keyup",d).cancel;return()=>{p(),g(),f()}}},[t,s,a,c]),Ns.createElement(Ns.Fragment,null)}import Gs,{useEffect as ul}from"react";function pl(o){let e=o;for(;e;){if(e.hasAttribute("data-layout-path"))return!0;e=e.parentElement}return!1}var Hs=['[data-element-type="nvl-container"]','[data-element-type="nvl-dialog-list"]','[data-element-type="nvl-dialog-item"]'],dl=["[data-layout-path]",'[data-element-type="menu"]','[data-element-type="notification"]'];function ml(o,e){return!o||e&&Hs.some(t=>!!o.closest(t))?!1:[...dl,...Hs].some(t=>!!o.closest(t))}function Us(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 Fs({state:o}){let e=P();return ul(()=>{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)||!Us(i,t))return;let s=o.mainContentNode;s&&(!s.contains(r)||!Us(i,s))||pl(r)||ml(r,o.isNvlMode())||(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]),Gs.createElement(Gs.Fragment,null)}import{useEffect as Kn}from"react";function Wo({gameState:o}){let e=o.audioManager,[t]=at("voiceVolume"),[n]=at("bgmVolume"),[i]=at("soundVolume"),[r,s]=at("globalVolume");return Kn(()=>{s(e.getGlobalVolume())},[]),Kn(()=>{e.setGroupVolume("voice",t)},[t]),Kn(()=>{e.setGroupVolume("bgm",n)},[n]),Kn(()=>{e.setGroupVolume("sound",i)},[i]),Kn(()=>{e.setGlobalVolume(r)},[r]),null}import{useEffect as Wi,useRef as gl}from"react";import Bo,{createContext as fl,useContext as hl,useState as Os}from"react";var Jt=class Jt{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(Jt.EventTypes["event:preloaded.add"],e),this.events.emit(Jt.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(Jt.EventTypes["event:preloaded.remove"],e),this.events.emit(Jt.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return Ue.getSrc(e)}};Jt.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 Me=Jt;var Vi=class o{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear()})}static getImage(e,t,n){return Dr(e,{...n,signal:t})}static decodeImage(e){if(typeof window>"u"||typeof window.Image>"u")return Promise.resolve();let t=new window.Image;return t.src=e,typeof t.decode!="function"?Promise.resolve():t.decode().catch(()=>{})}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}get(e){return this.src.get(e)}clear(){return this.src.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t){if(this.src.has(t)||this.preloadTasks.has(t)){let u={abort:()=>{},onFinished:()=>u,onErrored:()=>u};return u}let n=t,i={};this.game.hooks.rawTrigger("preloadImage",()=>[n,(u,d)=>{n=u,i={...i,...d}}]);let r=new AbortController,s=r.signal,a=[],l={promise:o.getImage(n,s,i).then(async u=>{this.preloadTasks.delete(t),u&&(this.add(t,u),await o.decodeImage(u))}).catch(u=>{this.preloadTasks.delete(t),e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${u}`),a.forEach(d=>d(u))}),controller:r};this.preloadTasks.set(t,l);let p={abort:()=>{r.abort(),this.preloadTasks.delete(t)},onFinished:u=>(l.promise.then(u),p),onErrored:u=>(a.push(u),p)};return p}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){for(let t of this.src.keys())e.includes(t)||this.src.delete(t);return this}};var zo=fl(null);function Ks({children:o}){let e=P(),[t]=Os(()=>new Me),[n]=Os(()=>new Vi(e));return Bo.createElement(Bo.Fragment,null,Bo.createElement(zo,{value:{preloaded:t,cacheManager:n}},o))}function fn(){if(!zo)throw new Error("usePreloaded must be used within a PreloadedProvider");return hl(zo)}function Vs({state:o}){let{preloaded:e,cacheManager:t}=fn(),n=P(),i=gl(new Set),[r]=te(),s="Preload",a=o.getLastScene()||o.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function p(){o.logger.debug(s,"Preload unmounted"),e.events.emit(Me.EventTypes["event:preloaded.unmount"])}return Wi(()=>o.events.on(E.EventTypes["event:state:flushPreloadedScenes"],()=>{r()}).cancel,[]),Wi(()=>{if(typeof fetch>"u")return e.events.emit(Me.EventTypes["event:preloaded.complete"]),e.events.emit(Me.EventTypes["event:preloaded.ready"]),o.logger.warn(s,"Fetch is not supported in this environment, skipping preload"),p;if(!n.config.preloadAllImages)return e.events.emit(Me.EventTypes["event:preloaded.complete"]),e.events.emit(Me.EventTypes["event:preloaded.ready"]),o.logger.debug(s,"Preload all images is disabled, skipping preload"),p;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"),p;let u=performance.now(),d=Ue.catSrc([...a.srcManager?.src||[],...a.srcManager?.getFutureSrc()||[]]),g=new bn(n.config.preloadConcurrency,n.config.preloadDelay),f=[],T=o.logger.group(s,!0),h=[];o.logger.debug(s,"preloading:",d,a);for(let y of d.image){let m=Ue.getSrc(y);if(m){if(f.push(m),t.has(m)||t.isPreloading(m)||h.includes(m)){o.logger.debug(s,`Image already loaded (${d.image.indexOf(y)+1}/${d.image.length})`,m),h.push(m);continue}h.push(m),g.addTask(()=>new Promise(S=>{t.preload(o,m).onFinished(()=>{o.logger.debug(s,`Image loaded (${d.image.indexOf(y)+1}/${d.image.length})`,m),S()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${d.image.indexOf(y)+1}/${d.image.length})`,m),S()})}))}}return T.end(),g.start().then(()=>{o.logger.info(s,"Image preload",`loaded ${t.size()} images in ${performance.now()-u}ms`),e.events.emit(Me.EventTypes["event:preloaded.complete"]),n.config.waitForPreload&&e.events.emit(Me.EventTypes["event:preloaded.ready"]),t.filter(f)}),n.config.waitForPreload||e.events.emit(Me.EventTypes["event:preloaded.ready"]),e.events.emit(Me.EventTypes["event:preloaded.mount"]),p},[a,l]),Wi(()=>{i.current.clear()},[a]),Wi(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){o.logger.weakWarn(s,"Story not found, skipping preload");return}let u=performance.now(),d=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(m=>Ue.getPreloadableSrc(l,m)).filter(function(m){return m!==null});d.filter(function(m){return m?.activeType==="scene"}).forEach(m=>{i.current.has(m)||i.current.add(m)});let f=Ue.catSrc([...i.current,...d]),T=new bn(n.config.preloadConcurrency,n.config.preloadDelay),h=[],y=o.logger.group(s);o.logger.debug(s,"preloading:",f);for(let m of f.image){let S=Ue.getSrc(m);if(S){if(h.push(S),t.has(S)||t.isPreloading(S)){o.logger.debug(s,`Image already loaded (${f.image.indexOf(m)+1}/${f.image.length})`,S);continue}T.addTask(()=>new Promise(L=>{t.preload(o,S).onFinished(()=>{o.logger.debug(s,`Image loaded (${f.image.indexOf(m)+1}/${f.image.length})`,S),L()}).onErrored(()=>{o.logger.weakError(s,`Failed to preload image (${f.image.indexOf(m)+1}/${f.image.length})`,S),L()})}))}}y.end(),T.start().then(()=>{o.logger.info(s,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-u}ms`),t.filter(h)})},[c,l]),null}import yl from"clsx";import Tt,{useCallback as $o,useMemo as vl,useRef as Sl}from"react";function jo({prompt:o,choices:e,afterChoose:t,state:n,words:i,renderPrompt:r=!0}){let s=P(),a=Sl([]),c=$o(f=>(a.current.push(f),a.current.indexOf(f)),[]),l=$o(f=>{let T=a.current.indexOf(f);T!==-1&&a.current.splice(T,1)},[]),p=$o(f=>a.current.indexOf(f),[]),u=s.config.menu,d=vl(()=>e.map(f=>({...f,words:f.prompt.evaluate(Se.getCtx({gameState:n}))})),[]);function g(f){t(f)}return Tt.createElement(Tt.Fragment,null,Tt.createElement(ko,{value:{evaluated:d,choose:g,gameState:n}},Tt.createElement(Eo,{value:{register:c,unregister:l,getIndex:p}},Tt.createElement(vt,{className:"absolute"},r&&o&&Tt.createElement(Mn,{gameState:n,action:{sentence:o,words:i,character:null},useTypeEffect:!1})),Tt.createElement(qt.Div,{color:"green",border:"dashed",className:yl("absolute"),style:{width:`${s.config.width}px`,height:`${s.config.height}px`}},Tt.createElement(u,{items:d.map((f,T)=>T)})))))}function Ws({items:o}){return Tt.createElement(wi,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},o.map(e=>Tt.createElement(Mi,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import qi from"react";import Bi from"react";import qo,{useEffect as Qo,useLayoutEffect as Xo,useRef as Yo,useState as Jo}from"react";function hn({element:o,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:i,onTransform:r,onTransition:s,transitionsProps:a=[],propOverwrite:c}){let[l,p]=Jo(null),[u,d]=Jo(null),g=qo.useRef(null),[f]=Jo(()=>new Jn("displayable.refGroup")),T=Yo(f.next()),h=Yo(Be()),m=P().getLiveGame().getGameState(),S=typeof a=="function"?a(l):a,[L]=te([u,l,h]);Qo(()=>m.events.depends([m.events.on(E.EventTypes["event:state.player.skip"],At)]).cancel,[u,l,h]),Xo(()=>{if(R(),!l)return;if(h.current.some(([q])=>!q.current))throw new k("Displayable: Trying to access transition groups before they are mounted");let{controller:G,task:ie}=l;return G.onUpdate(q=>{h.current.forEach(([I],ye)=>{let ue=ie.resolve[ye],ae=typeof ue=="function"?ue:ue.resolver;if(!ae)throw new k(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${ye}])`);let V=ae(...q),x=U(S[ye]||S[S.length-1]||{},V);K(I,c?c(x):x)})}).cancel},[l]),Qo(()=>{if(!g.current)throw new Error(`Scope not ready. Using element: ${o.constructor.name}`)},[]),Xo(()=>{let G=e.toStyle(m,i);Object.assign(g.current.style,G),m.logger.debug("Displayable","Initial style applied",g.current,G)},[]);let O=Yo(()=>{});O.current=()=>{u||l||!g.current||Object.assign(g.current.style,e.toStyle(m,i))},Xo(()=>{O.current()});let{ratio:A}=fe();Qo(()=>A.onUpdate(()=>{O.current(),requestAnimationFrame(()=>O.current())}),[A]);function R(){let G=typeof a=="function"?a(l):a;if(!h.current||!h.current.length)throw new k("Displayable: Transition group refs are not initialized correctly");if(h.current.some(([ie])=>!ie.current))throw new k("Displayable: Trying to access transition groups before they are mounted");h.current.forEach(([ie],Z)=>{if(!ie.current)throw new k("Displayable: Trying to assign properties to unmounted element");K(ie,G[Z]||G[G.length-1]||{})})}function j(G){m.logger.debug("Displayable","Transform applied",e.toStyle(m,i),g.current),L(),r?.(G)}function K(G,ie){if(!G.current)throw new k("Displayable: Trying to assign properties to unmounted element");let Z=G.current,q={},I={};Object.keys(ie).forEach(ue=>{let ae=ue;ae==="style"&&ie.style?Object.assign(q,ie.style):ie[ae]!==void 0&&ae!=="key"&&(I[ae]=ie[ae])}),Object.keys(q).length>0&&Object.assign(Z.style,q);let ye=c?c(I):I;for(let[ue,ae]of Object.entries(ye))Z.getAttribute(ue)!==ae&&Z.setAttribute(ue,ae)}function se(G,ie){u&&(u.abort(),d(null));let Z=G.animate(e,{gameState:m,ref:g,overwrites:i}),q=new we(Z);return m.timelines.attachTimeline(q),Z.onSkipControllerRegister(I=>{I.onAbort(()=>{q.abort(),d(null)})}),d(Z),Z.then(()=>{d(null),j(G),ie()}),q}function Ge(G,ie){l&&l.controller.complete();let Z=G.createTask(m),q=G.requestAnimations(Z.animations),I=new v().registerSkipController(new H(q.cancel)),ye=new we(I);I.skipController.onAbort(()=>{q.cancel()}),q.onCanceled(()=>{ye.abort(),p(null),m.logger.debug("Displayable","Transition cancelled",G)}),m.timelines.attachTimeline(ye),p({task:Z,controller:q,transition:G,resolve:ie});let ue;if(h.current=Z.resolve.map(V=>{let x=qo.createRef(),N=typeof V=="function"?void 0:V.key;if(!N)return[x,f.next()];if(N==="target")return ue=f.next(),[x,ue];if(N==="current")return[x,T.current];throw new k("Displayable: Invalid key type")}),!ue)throw new k("Displayable: No target key found");T.current=ue;let ae=h.current.map(([V])=>{let x=V.current;return x?.waitForLoad?x.waitForLoad():Promise.resolve()});return Promise.all(ae).then(()=>{q.start(),q.onComplete(()=>{ge(),p(null),s?.(G),ie(),I.resolve()})}),ye}function ke(G){return m.logger.debug("initDisplayable",o),se(Y.immediate(e.get()),G)}function At(){t&&u&&(u.abort(),d(null),m.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),m.logger.debug("transition skipped"))}function Be(){return[[qo.createRef(),T.current]]}function ge(){h.current.forEach(([G])=>{G.current=null}),h.current=Be()}return{transformRef:g,transitionRefs:h.current,transitionTask:l,initDisplayable:ke,applyTransform:se,applyTransition:Ge,updateStyleSync:R,deps:[u,l,h]}}import{useEffect as Tl}from"react";function Ot(o,e,t=[]){let i=P().getLiveGame().getGameState();return Tl(()=>{let r=typeof e=="function"?e():e;return i.mountState(o,r).unMount},[...t]),[]}function Zo({state:o,text:e}){let{ratio:t}=fe(),[n]=te(),{transformRef:i,transitionRefs:r,initDisplayable:s,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:p}=hn({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipTextTransform,skipTransition:o.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:u=>({width:"fit-content",transform:Y.propToCSSTransform(o,u,{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 Ot(e,{initDisplayable:s,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...p]),Bi.createElement(qt.Div,{"data-element-type":"text"},Bi.createElement(qt.mDiv,{tag:"text.container",color:"green",border:"dashed",ref:i,className:"absolute"},r.map(([u,d])=>Bi.createElement("span",{key:d,ref:u,className:e.config.className},Bi.createElement("span",null,e.state.text)))))}import gn,{useRef as $s,useState as js}from"react";import zi,{useEffect as _o,useRef as $i,forwardRef as bl}from"react";var Bs=bl(({onSizeChanged:o,onLoad:e,autoFit:t=!1},n)=>{let i=$i(null),{ratio:r}=fe(),[s,a]=zi.useState(()=>r.state.width),[c,l]=zi.useState(()=>r.state.height),p=P(),u=$i(!1),d=$i(null),g=$i(null);zi.useImperativeHandle(n,()=>i.current,[]),_o(()=>{i.current&&Object.defineProperties(i.current,{isLoaded:{value:()=>u.current,configurable:!0},waitForLoad:{value:()=>{let h=()=>{let y=i.current;return!y||typeof y.decode!="function"?Promise.resolve():y.decode().catch(()=>{})};return u.current?h():(d.current||(d.current=new Promise(y=>{g.current=y})),d.current.then(h))},configurable:!0}})},[]),_o(()=>(f(),r.onUpdate(f)),[o]),_o(()=>{let h=new MutationObserver(y=>{y.forEach(m=>{m.type==="attributes"&&m.attributeName==="src"&&i.current&&f()})});return i.current&&h.observe(i.current,{attributes:!0}),()=>{h.disconnect()}},[o]);function f(){if(i.current&&i.current.naturalWidth)if(i.current.naturalWidth*i.current.naturalHeight===1){let h=r.state.width,y=r.state.height,m=`${h} / ${y}`;a(h),l(y),i.current.style.aspectRatio=m,o&&o(h,y)}else{let h=t?p.config.width/i.current.naturalWidth:1,y=i.current.naturalWidth*r.state.scale*h,m=i.current.naturalHeight*r.state.scale*h;a(y),l(m),i.current.style.aspectRatio="auto",o&&o(y,m)}}function T(){f(),u.current=!0,g.current&&(g.current(),g.current=null,d.current=null),e&&e()}return zi.createElement("img",{ref:i,onLoad:T,width:s,height:c,alt:""})});Bs.displayName="AspectScaleImage";var zs=Bs;import qs from"clsx";import{motion as Cl}from"motion/react";function ji({image:o,state:e}){let[t]=js(()=>new Q),[n,i]=js([]),{cacheManager:r}=fn(),s=$s([]),a=$s(null),{transformRef:c,transitionRefs:l,initDisplayable:p,applyTransition:u,applyTransform:d,updateStyleSync:g,deps:f}=hn({element:o,state:o.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:y=>{let m=y?y.transition._getCurrentSrc():o.state.currentSrc;return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:C.isColor(m)?C.colorToString(m):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-o.state.darkness})`},src:C.isImageSrc(m)?C.srcToURL(m):M.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:y=>y.src?(!C.isDataURI(y.src)&&!r.has(y.src)&&!r.isPreloading(y.src)&&!s.current.includes(y.src)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${y.src}".
|
|
45
45
|
This may be caused by complicated image action behavior that cannot be predicted.
|
|
46
|
-
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(
|
|
47
|
-
at Video.tsx: useEffect`),l=()=>{a||!s||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();i()},play:()=>{if(!t.current)throw c();let u=t.current;return u.currentTime=0,new Promise(d=>{o.schedule(({retry:g})=>{if(u.readyState<3){let S=()=>{u.removeEventListener("loadeddata",S),g()};u.addEventListener("loadeddata",S);return}let f=()=>{h(),d()},T=()=>{h(),d()},h=()=>{u.removeEventListener("ended",f),u.removeEventListener("stopped",T)};u.addEventListener("ended",f),u.addEventListener("stopped",T),p.push(h),u.play().catch(S=>{o.logger.error("Failed to play video: "+S),h(),d()})},10)})},pause:()=>{if(!t.current)throw c();t.current.pause()},resume:()=>{if(!t.current)throw c();return t.current.play()},stop:()=>{if(!t.current)throw c();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:u=>{if(!t.current)throw c();t.current.currentTime=u}}))},p=[];return s.addEventListener("canplay",l),()=>{a=!1,s.removeEventListener("canplay",l),p.forEach(u=>u()),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 Dl.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 Il from"clsx";import Rl,{useCallback as Nl,useEffect as Xi,useRef as Ml}from"react";function rr({children:o,className:e,gameState:t}){let{ratio:n}=fe(),i=P(),[r]=te(),s=Ml(null),a=i.config.minWidth,c=i.config.minHeight,l=Nl(p=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(p.width,p.height,p.scale),n.updateMin(a,c),r()},[r,t.logger,c,a,n]);return Xi(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Xi(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Xi(()=>{let p=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(p)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Xi(()=>t.events.on(E.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),Rl.createElement(Es,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:Il(e),onUpdate:l},o)}import Js,{useEffect as Gl,useRef as Hl,useState as Zs}from"react";function sr({src:o,width:e,height:t}){let[n,i]=Zs({x:0,y:0}),[r,s]=Zs(!1),a=Hl(null),{ratio:c}=fe();return Gl(()=>{let l=p=>{if(a.current){let u=a.current.getBoundingClientRect(),d=p.clientX-u.left,g=p.clientY-u.top;i({x:d,y:g}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),Js.createElement(vt,{ref:a,className:"overflow-hidden absolute"},Js.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 _s from"react";import It from"react";function ar({error:o,errorInfo:e}){return P().config.app.debug?It.createElement("div",{className:"text-left"},It.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),It.createElement("p",{className:"text-red-700"},"Message: ",o.message),It.createElement("pre",null,"Error Stack: ",o?.stack),It.createElement("pre",null,"Component Stack: ",e?.componentStack),It.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):It.createElement("div",{className:"bg-white w-full h-full"},It.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),It.createElement("p",null,"Please contact the game developer for further assistance."))}var Yi=class extends _s.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?_s.createElement(ar,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import na from"clsx";import W,{useEffect as bt,useReducer as ia,useState as yn}from"react";import{flushSync as oa}from"react-dom";import{useRef as Ul}from"react";import{useEffect as Fl}from"react";function ea({gameState:o}){let e=Ul(null);return Fl(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(E.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import Wn,{useEffect as Ol}from"react";function cr({gameState:o}){let[e]=te(),{ratio:t}=fe(),n=o.notificationMgr;Ol(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return Wn.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"},Wn.createElement(i,{notifications:n.toArray()}))}function ta({notifications:o}){return Wn.createElement(Hi,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>Wn.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},Wn.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function ra({story:o=Dn.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:p,active:u=!0}){let[d,g]=ia(x=>x+1,0),[f,T]=ia(x=>x+1,0),[h,S]=yn(0),m=P(),[y]=yn(()=>new E(m,{update:g,forceUpdate:()=>{y.logger.weakWarn("Player","force update"),oa(()=>{g()})},forceRemount:()=>{y.logger.weakWarn("Player","force remount"),oa(()=>{S(x=>x+1),g()})},next:ue})),D=W.createRef(),O=W.createRef(),[A,R]=yn(!1),j=W.useRef(!1),K=W.useRef(null),se=W.useRef(null),{preloaded:Ge}=fn(),[ke,At]=yn(!1),Be=W.useRef(!1),[ge,G]=yn(!1),ie=W.useRef(!1),Z=W.useRef(null),q=W.useRef(!1),[I]=yn(new Map);function ye(x){return{game:m,gameState:y,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable(),scene:x}}function ue(){let x=()=>{I.forEach(w=>w.cancel())};if(y.rollLock.isLocked())return;x();let N=!1,_=0;for(;!N;){if(_++>m.config.maxStackModelLoop)throw new k("Max stack model loop reached");let w=m.getLiveGame().next();if(!w){if(m.getLiveGame().stackModel&&!m.getLiveGame().stackModel.isEmpty())continue;break}if(v.isAwaitable(w)){if(K.current===w)break;K.current=w,w.onSettled(()=>{w.isFailed()||(K.current===w&&(K.current=null),ue())}),w.onFailed(ze=>{K.current===w&&(K.current=null),y.logger.error("Player",ze)}),N=!0;break}if(w instanceof tn){if(se.current===w)break;se.current=w,w.nextUnlock().then(()=>{se.current===w&&(se.current=null),ue()}),N=!0;break}if(Oe.isCalledActionResult(w)&&w.wait&&Oe.isStackModelsAwaiting(w.wait.type,w.wait.stackModels)){if(K.current===w)break;if(K.current=w,w.wait){let ze=Oe.executeStackModelGroup(w.wait.type,w.wait.stackModels);ze.then(()=>{K.current===w&&(K.current=null),ue()}),ze.onFailed(xt=>{K.current===w&&(K.current=null),y.logger.error("Player",xt)})}N=!0;break}y.handle(w)}y.stage.update()}bt(()=>{y.audioManager.initialize()},[]),bt(()=>(m.getLiveGame().setGameState(y),o&&!m.getLiveGame().isPlaying()&&m.getLiveGame().loadStory(o),y.playerCurrent=D.current,y.mainContentNode=O.current,()=>{m.getLiveGame().setGameState(void 0),y.playerCurrent=null}),[m,o]),bt(()=>je(()=>{R(!0);let x=y.getLastScene(),N=[];x?N.push(x.events.once("event:scene.mount",()=>{y.stage.next()}).cancel):y.stage.next();let _=y.events.on(E.EventTypes["event:state.end"],()=>{c&&c({game:m,gameState:y,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()})});return y.stage.update(),()=>{x&&N.forEach(w=>w()),_.cancel()}}),[]),bt(()=>je(()=>{A&&i&&!j.current&&(j.current=!0,y.stage.forceUpdate(),m.hooks.trigger("init",[]),i({game:m,gameState:y,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()}))}),[A]),bt(()=>je(()=>{if(ke&&s&&!Be.current){Be.current=!0;let x=Z.current||y.getLastScene()||y.getPreloadingScene(),N=ye(x);s(N)}}),[ke]),bt(()=>je(()=>{if(ge&&!ie.current){ie.current=!0;let x=Z.current||y.getLastScene()||y.getPreloadingScene(),N=ye(x);m.markPreloadComplete(N)&&r&&r(N)}}),[ge]),bt(()=>y.events.on(E.EventTypes["event:state.scene.mount"],x=>{Z.current||(Z.current=x,T())}).cancel,[]),bt(()=>{if(!ge||!u||q.current||m.isFirstSceneReady())return;let x=Z.current||y.getLastScene();if(!x)return;let N=null,_=null,w=!1;q.current=!0;let ze=()=>{w=!0,q.current=!1;let xt=ye(x);m.markFirstSceneReady(xt)&&a&&a(xt)};return typeof requestAnimationFrame=="function"?N=requestAnimationFrame(()=>{_=setTimeout(ze,0)}):_=setTimeout(ze,0),()=>{w||(q.current=!1,N!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(N),_!==null&&clearTimeout(_))}},[u,f,d,ge]),bt(()=>Ge.events.depends([Ge.events.on(Me.EventTypes["event:preloaded.ready"],()=>{At(!0),y.stage.update(),o&&m.getLiveGame().isPlaying()&&ue()}),Ge.events.on(Me.EventTypes["event:preloaded.complete"],()=>{G(!0)})]).cancel,[]),bt(()=>{y.flushDep=d},[d]);let ae=e||m.config.width,V=t||m.config.height;return W.createElement(Yi,{onError:l},W.createElement("div",{style:{width:typeof ae=="number"?`${ae}px`:ae,height:typeof V=="number"?`${V}px`:V},className:na(n,"__narraleaf_content-player"),ref:D,tabIndex:0},W.createElement(rr,{className:na("flex-grow overflow-auto"),gameState:y},W.createElement(Wo,{gameState:y}),W.createElement(ea,{gameState:y}),W.createElement(vt,{className:"absolute",ref:O,style:{cursor:y.game.config.cursor?"none":"auto",overflow:y.game.config.showOverflow?"visible":"hidden"}},m.config.cursor&&W.createElement(sr,{src:m.config.cursor,width:m.config.cursorWidth,height:m.config.cursorHeight}),W.createElement(Kl,{show:ke&&u,key:h},W.createElement(Uo,null,W.createElement(Ms,{state:y}),W.createElement(Fs,{state:y}),y.getSceneElements().map(x=>W.createElement(nr,{key:"scene-"+x.scene.getId(),state:y,elements:x})),y.getVideos().map((x,N)=>W.createElement("div",{className:"w-full h-full absolute",key:"video-"+N,"data-element-type":"video"},W.createElement(or,{gameState:y,video:x}))),W.createElement(Vl,{NvlComponent:m.config.nvlDialog}))),W.createElement(Vs,{state:y}),W.createElement(Cs,null,p),W.createElement(cr,{gameState:y})))))}function Kl({children:o,show:e}){return W.createElement(W.Fragment,null,e?o:null)}function Vl({NvlComponent:o}){let{dialogs:e,state:t}=St(),i=P().getLiveGame().getGameState(),r=W.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(Se.getCtx({gameState:i})),l=t.activeDialogId===s.id,p=l&&t.phase==="typing";return{entry:s,index:a,isActive:l,gameState:i,words:c,useTypeEffect:p}}),[e,i,t.activeDialogId,t.phase]);return W.createElement(o,{dialogs:r})}import"client-only";import vn from"react";function sa({children:o,game:e}){return vn.createElement(vn.Fragment,null,vn.createElement(is,null,vn.createElement(Zr,{game:e},vn.createElement(Ks,null,vn.createElement(ns,null,o)))))}var Wl=(r=>(r.image="narraleaf:image",r.text="narraleaf:text",r.layer="narraleaf:layer",r.scene="narraleaf:scene",r.video="narraleaf:video",r))(Wl||{});import Bl from"clsx";import Ct,{useEffect as aa,useRef as zl}from"react";import{motion as $l,useIsPresent as jl}from"motion/react";var ql={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function Ql({children:o,initial:e,transition:t,...n}){let i=P(),r=ct(),{ratio:s}=fe(),[a]=at(J.Preferences.showDialog),c=zl(null),[l]=Xt("nextAction"),p=jl();function u(){r.requestComplete()}return aa(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
48
|
-
at Say.tsx: onElementClick`);return}let d=f=>{i.keyMap.match("nextAction",f.key)&&r.requestComplete()};window.addEventListener("keyup",d);let g=r.events.on(Ce.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keyup",d),g.cancel()}},[r,l]),aa(()=>{let d=i.preference.onPreferenceChange(J.Preferences.autoForward,g=>{g&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{d.cancel()}},[r]),Ct.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},Ct.createElement("div",{className:Bl("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:u,style:{...ii(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},Ct.createElement($l.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&p?{duration:0}:t},o)))}function ca({children:o,...e}){let t=ct();return!t.config.action.sentence||!t.config.action.words?null:Ct.createElement(Ql,{...e},o)}var cl=ca;function la(){return Ct.createElement(ca,null,Ct.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},Ct.createElement(Do,null),Ct.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},Ct.createElement(Lt,null),Ct.createElement(Ft,{...ql}))))}var Bn={say:la,menu:Ws,notification:ta,nvlDialog:Ko};var Ji=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 zn=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 ua=(e=>(e.game="game",e))(ua||{}),Ke=class Ke{constructor(e){this.hooks=new _n;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new Rn(Ke.DefaultPreference);this.keyMap=new zn({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new Q;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=U(Ke.DefaultConfig,e),this.plugins=new Ji(this),this.router=new Ut(this)}configure(e){let[t,n]=Gr(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=U(this.config,t),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}onPreloadComplete(e){return this.lifecycleEvents.on(Ke.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(Ke.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(Ke.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(Ke.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(Ke.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(Ke.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new ht(this)}};Ke.defaultSettings={volume:1},Ke.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:500,skipInterval:100},Ke.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"},Ke.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,allowSkipBackgroundTransition:!1,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,notification:Bn.notification,menu:Bn.menu,dialog:Bn.say,nvlDialog:Bn.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100},Ke.GameSettingsNamespace=ua,Ke.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var J=Ke;var Zi=class Zi extends z{static executeActionsAsync(e,t){let n=e.game.getLiveGame().requestAsyncStackModel([{type:t.type,node:t.contentNode}]);return e.game.getLiveGame().executeAsyncStackModel(n)}checkActionChain(e){if(e.some(t=>!!t.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return e}executeAction(e,t){let n=this.contentNode,[i]=n.getContent();if(this.type===Ae.do)return[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:i[0].contentNode}];if(this.type===Ae.doAsync){let r=Zi.executeActionsAsync(e,i[0]);return e.timelines.attachTimeline(r),super.executeAction(e,t)}else if(this.type===Ae.any){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().createStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:r}}}else if(this.type===Ae.all){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().createStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:r}}}else if(this.type===Ae.allAsync){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().requestAsyncStackModel([{type:s.type,node:s.contentNode}]));return e.timelines.attachTimeline(v.all(...r.map(s=>e.game.getLiveGame().executeAsyncStackModel(s)))),super.executeAction(e,t)}else if(this.type===Ae.repeat){let[r,s]=this.contentNode.getContent();if(s<=0||r.length===0)return super.executeAction(e,t);let a=Oe.createCountLoop(e.game.getLiveGame(),s,this.checkActionChain(r));return e.logger.debug("ControlAction","repeat",r,s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[a]}}}else if(this.type===Ae.while){let[r,s]=this.contentNode.getContent();if(r.length===0)return super.executeAction(e,t);if(!s.evaluate({gameState:e}).value)return super.executeAction(e,t);let a=Oe.createConditionLoop(e.game.getLiveGame(),s,this.getId(),this.checkActionChain(r));return e.logger.debug("ControlAction","while",r),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[a]}}}else if(this.type===Ae.break){if(!t.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return t.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===Ae.sleep){let[,r]=this.contentNode.getContent(),s;typeof r=="number"?s=v.delay(r):v.isAwaitable(r)?s=r:s=v.fromPromise(r);let a=new v,c=new we(s);return e.timelines.attachTimeline(c),s.then(()=>{a.resolve({type:this.type,node:this.contentNode.getChild()})}),a.onSkipControllerRegister(l=>{l.onAbort(()=>{c.abort()})}),a}else if(this.type===Ae.waitForClick){if(e.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let r=new v,s=new v,a=new we(s);e.timelines.attachTimeline(a);let c=e.game.preference,l=c.getPreference(J.Preferences.autoForward),p=c.getPreference(J.Preferences.gameSpeed),u=l?e.game.config.autoForwardDelay/p:null,d=!1,g=null,f=null,T=null,h=()=>{f?.cancel(),T?.cancel(),g&&(clearTimeout(g),g=null)},S=()=>{d||(d=!0,h(),s.resolve())};return f=e.events.on(E.EventTypes["event:state.player.stageClick"],S),T=e.events.on(E.EventTypes["event:state.player.skip"],S),u!==null&&(g=setTimeout(S,u)),s.then(()=>{r.resolve({type:this.type,node:this.contentNode.getChild()})}),r.onSkipControllerRegister(m=>{m.onAbort(()=>{d||(d=!0,h(),a.abort())})}),r}throw new Error("Unknown control action type: "+this.type)}getFutureActions(e,t){if(this.callee.config.allowFutureScene===!1&&t.allowFutureScene===!1)return[...super.getFutureActions(e,t)];if(this.type===Ae.break||this.type===Ae.waitForClick)return super.getFutureActions(e,t);let n=this.contentNode.getContent()[0],i=super.getFutureActions(e,t);return[...n??[],...i]}stringify(e,t,n){if(this.type===Ae.break)return super.stringifyWithContent("Control","break");if(this.type===Ae.waitForClick)return super.stringifyWithContent("Control","waitForClick");let i=this.contentNode,[r]=i.getContent();return super.stringifyWithContent("Control",r.map(s=>s.stringify(e,t,n)).join(";"))}};Zi.ActionTypes=Ae;var de=Zi;var Le=class o extends oe{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()}do(t){return this.push(de.ActionTypes.do,t)}doAsync(t){return this.push(de.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(de.ActionTypes.any,t)}all(t){return this.pushUnchained(de.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(de.ActionTypes.allAsync,t)}repeat(t,n){return this.push(de.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=F.from(t);return this.pushWithLambda(de.ActionTypes.while,n,i)}breakLoop(){let t=new de(this.chain(),de.ActionTypes.break,new b().setContent([]));return this.chain(t)}sleep(t){return this.push(de.ActionTypes.sleep,[],t)}waitForClick(){let t=new de(this.chain(),de.ActionTypes.waitForClick,new b().setContent([]));return this.chain(t)}push(t,n,...i){let r=this.narrativeToActions(n),s=new de(this.chain(),t,new b().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new de(this.chain(),t,new b().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new de(this.chain(),t,new b().setContent([this.construct(r),i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?kt.say(n).getActions():Ee.toActions([n]))}};var ne=class ne extends mt{static getInitialSrc(e){if(this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return C.isStaticImageData(t)?C.srcToURL(t):C.isColor(t)?t:C.isImageSrc(t)?C.srcToURL(t):ne.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isTagDefinition(e){return typeof e=="object"&&e!==null&&!C.isImageSrc(e)&&!C.isColor(e)&&"defaults"in e}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(C.isImageSrc(t)||C.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:ne.isTagSrc(e)?ne.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):ne.isStaticSrc(e)?C.isStaticImageData(e.state.currentSrc)?C.srcToURL(e.state.currentSrc):C.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static fromSrc(e){return new ne({src:e})}constructor(e={}){super();let t=ne.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 Le,n=>{if(C.isImageSrc(e)||C.isColor(e)){if(C.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 re(n,re.ActionTypes.setAppearance,new b().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Le,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 he("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:ne.StateSerializer.serialize(this.state),transformState:be.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=ne.StateSerializer.deserialize(e.state),this.transformState=be.deserialize(e.transformState),this}_applyTransition(e,t){return new De(this.chain(),Pe.applyTransition,new b().setContent([e,t]))}_init(e,t){return new De(this.chain(),Pe.init,new b().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new re(this.chain(),re.ActionTypes.initWearable,new b().setContent([e]))}_flush(){return new re(this.chain(),re.ActionTypes.flush,new b)}reset(){return this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!ne.isTagSrc(this))throw new Error(`Tag not defined
|
|
46
|
+
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),s.current.push(y.src)),{...y,src:r.get(y.src)||y.src}):y});Ot(o,{createWearable:y=>{i(m=>[...m,y])},disposeWearable:y=>{i(m=>m.filter(S=>S.getId()!==y.getId()))},initDisplayable:p,applyTransform:d,applyTransition:u,events:t,updateStyleSync:g},[...f]);function T(y,m){a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${y}px`,height:`${m}px`}))}function h(){t.emit("event:image.onLoad")}return gn.createElement(Cl.div,{ref:c,className:"absolute w-max h-max","data-element-type":"image"},gn.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":o.getId()},l.map(([y,m],S)=>gn.createElement(zs,{key:m,ref:y,autoFit:o.config.autoFit,onSizeChanged:S===0?T:void 0,onLoad:S===0?h:void 0})),gn.createElement("div",{className:qs("w-full h-full top-0 left-0 absolute")},n.map(y=>gn.createElement("div",{className:qs("w-full h-full relative"),key:"wearable-"+y.getId()},gn.createElement(ji,{image:y,state:e}))))))}function er({state:o,displayable:e}){return qi.createElement(qi.Fragment,null,e.map(t=>{if(t instanceof zt)return qi.createElement(Zo,{state:o,text:t,key:"text-"+t.getId()});if(t instanceof M)return qi.createElement(ji,{state:o,image:t,key:"image-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Qi,{useEffect as Al}from"react";import{motion as xl}from"motion/react";function Qs({state:o,layer:e,children:t}){let{transformRef:n,transitionRefs:i,initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c,deps:l}=hn({element:e,state:e.transformState,skipTransform:o.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return Ot(e,{initDisplayable:r,applyTransition:s,applyTransform:a,updateStyleSync:c},[...l]),Al(()=>(o.logger.debug("Layer","Layer mounted",e.getId()),()=>{o.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Qi.createElement(Qi.Fragment,null,Qi.createElement(xl.div,{className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},i.map(([p,u])=>Qi.createElement("div",{className:"relative w-full h-full",ref:p,key:u},t))))}import wl from"clsx";import{AnimatePresence as kl}from"motion/react";import{useEffect as tr,useReducer as Pl,useRef as Vn}from"react";import Zt from"react";var El=120;function nr({state:o,className:e,elements:t}){let{scene:n,layers:i,texts:r,menus:s}=t,a=Vn(!1),c=Vn({slotKeys:new Map,exitingKeys:new Set,menuPromptIds:new WeakMap,nextKey:0}),l=Vn([]),p=Vn(null),u=Vn(null),[,d]=Pl(h=>h+1,0),g=()=>{u.current&&(clearTimeout(u.current),u.current=null)},f=()=>{let h=p.current;if(!h)return;let y=c.current;h.forEach(({slot:m,presenceKey:S})=>{y.slotKeys.get(m)===S&&y.slotKeys.delete(m),y.exitingKeys.add(S)}),p.current=null,u.current=null,l.current=[],d()};tr(()=>n.events.depends([n.events.on(et.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return o.audioManager.stop(n.state.backgroundMusic,n.config.backgroundMusicFade)})]).cancel,[]),tr(()=>(n.events.emit(et.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(et.EventTypes["event:scene.unmount"]),o.events.emit(E.EventTypes["event:state.scene.unmount"],n),o.logger.debug("Scene","Scene unmounted",n.getId())}),[]),tr(()=>()=>{g()},[]),Ot(n,{setBackgroundMusic(h,y){return new Promise(m=>{(async function(){n.state.backgroundMusic&&o.audioManager.isManaged(n.state.backgroundMusic)&&await o.audioManager.stop(n.state.backgroundMusic,y),h?(await o.audioManager.play(h,{end:h.state.volume,duration:y}),n.state.backgroundMusic=h):n.state.backgroundMusic=null,m()})()})}});let T=(()=>{let h=c.current,y=r.length>0?r.map(({action:L,onClick:O},A)=>({action:L,slot:A,useTypeEffect:!a.current,onFinished:R=>{R!==void 0&&(a.current=R),O(),o.events.emit(E.EventTypes["event:state.player.lineEnd"]),o.stage.next()}})):s.flatMap((L,O)=>{if(!L.action.prompt||!L.action.words)return[];let A=h.menuPromptIds.get(L);return A||(A=`menu-prompt-${n.getId()}-${h.nextKey++}`,h.menuPromptIds.set(L,A)),[{action:{sentence:L.action.prompt,words:L.action.words,character:null,id:A},slot:O,useTypeEffect:!1}]});if(y.length===0)return!p.current&&l.current.length>0&&(p.current=l.current.map(L=>({...L,active:!1}))),p.current&&!u.current&&(u.current=setTimeout(f,El)),p.current??[];g(),p.current=null;let m=new Set(y.map(({slot:L})=>L));for(let[L,O]of Array.from(h.slotKeys))m.has(L)||(h.exitingKeys.add(O),h.slotKeys.delete(L));let S=y.map(({slot:L,...O})=>{let A=h.slotKeys.get(L);return(!A||h.exitingKeys.has(A))&&(A=`say-${n.getId()}-${h.nextKey++}`,h.slotKeys.set(L,A)),{...O,presenceKey:A,slot:L,active:!0}});return l.current=S,S})();return Zt.createElement("div",{className:wl(e,"w-full h-full absolute")},[...i.entries()].sort(([h],[y])=>h.state.zIndex-y.state.zIndex).map(([h,y])=>Zt.createElement(Qs,{state:o,layer:h,key:h.getId()},Zt.createElement(er,{state:o,displayable:y}))),Zt.createElement(kl,{propagate:o.game.config.animationPropagate,onExitComplete:()=>{c.current.exitingKeys.clear()}},T.map(({action:h,onFinished:y,presenceKey:m,active:S,useTypeEffect:L})=>Zt.createElement(Mn,{gameState:o,key:m,action:h,active:S,onFinished:y,useTypeEffect:L}))),s.map(({action:h,onClick:y},m)=>Zt.createElement("div",{key:"menu-"+m,"data-element-type":"menu"},Zt.createElement(jo,{state:o,prompt:h.prompt,choices:h.choices,renderPrompt:!h.prompt,afterChoose:S=>{a.current=!1,y(S),o.stage.next()},words:h.words}))))}import Dl from"react";import{useEffect as ir,useRef as Ll}from"react";import{useCallback as Xs}from"react";function Ys(o){let e=Xs(()=>{if(!o.current)return;let n=o.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[o]),t=Xs(()=>{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 or({gameState:o,video:e}){let t=Ll(null),{show:n,hide:i}=Ys(t);ir(()=>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,[]),ir(()=>{i(),e.state.display&&n()},[]),ir(()=>{if(!t.current)return;let s=t.current,a=!1,c=()=>new k(`Failed to add event listener, ref is not available
|
|
47
|
+
at Video.tsx: useEffect`),l=()=>{a||!s||(a=!0,o.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();i()},play:()=>{if(!t.current)throw c();let u=t.current;return u.currentTime=0,new Promise(d=>{o.schedule(({retry:g})=>{if(u.readyState<3){let y=()=>{u.removeEventListener("loadeddata",y),g()};u.addEventListener("loadeddata",y);return}let f=()=>{h(),d()},T=()=>{h(),d()},h=()=>{u.removeEventListener("ended",f),u.removeEventListener("stopped",T)};u.addEventListener("ended",f),u.addEventListener("stopped",T),p.push(h),u.play().catch(y=>{o.logger.error("Failed to play video: "+y),h(),d()})},10)})},pause:()=>{if(!t.current)throw c();t.current.pause()},resume:()=>{if(!t.current)throw c();return t.current.play()},stop:()=>{if(!t.current)throw c();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:u=>{if(!t.current)throw c();t.current.currentTime=u}}))},p=[];return s.addEventListener("canplay",l),()=>{a=!1,s.removeEventListener("canplay",l),p.forEach(u=>u()),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 Dl.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 Il from"clsx";import Rl,{useCallback as Nl,useEffect as Xi,useRef as Ml}from"react";function rr({children:o,className:e,gameState:t}){let{ratio:n}=fe(),i=P(),[r]=te(),s=Ml(null),a=i.config.minWidth,c=i.config.minHeight,l=Nl(p=>{if(n.isLocked()){t.logger.weakWarn("AspectRatio","ratio is locked, skipping update");return}n.update(p.width,p.height,p.scale),n.updateMin(a,c),r()},[r,t.logger,c,a,n]);return Xi(()=>{n.setUpdate(()=>{s.current?.requestUpdate()})},[n]),Xi(()=>n.onRequestedUpdate(()=>{s.current?.requestUpdate()}),[n]),Xi(()=>{let p=requestAnimationFrame(()=>{s.current?.requestUpdate()});return()=>{cancelAnimationFrame(p)}},[i.config.aspectRatio,i.config.height,i.config.width,c,a]),Xi(()=>t.events.on(E.EventTypes["event:state.player.requestFlush"],r).cancel,[t,r]),Rl.createElement(Es,{ref:s,id:i.config.contentContainerId,aspectRatio:i.config.aspectRatio,baseWidth:i.config.width,minWidth:a,minHeight:c,debounceMs:i.config.ratioUpdateInterval,className:Il(e),onUpdate:l},o)}import Js,{useEffect as Gl,useRef as Hl,useState as Zs}from"react";function sr({src:o,width:e,height:t}){let[n,i]=Zs({x:0,y:0}),[r,s]=Zs(!1),a=Hl(null),{ratio:c}=fe();return Gl(()=>{let l=p=>{if(a.current){let u=a.current.getBoundingClientRect(),d=p.clientX-u.left,g=p.clientY-u.top;i({x:d,y:g}),r||s(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[r]),Js.createElement(vt,{ref:a,className:"overflow-hidden absolute"},Js.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 _s from"react";import It from"react";function ar({error:o,errorInfo:e}){return P().config.app.debug?It.createElement("div",{className:"text-left"},It.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),It.createElement("p",{className:"text-red-700"},"Message: ",o.message),It.createElement("pre",null,"Error Stack: ",o?.stack),It.createElement("pre",null,"Component Stack: ",e?.componentStack),It.createElement("pre",null,"Digest: ","digest"in e?String(e.digest):"")):It.createElement("div",{className:"bg-white w-full h-full"},It.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),It.createElement("p",null,"Please contact the game developer for further assistance."))}var Yi=class extends _s.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?_s.createElement(ar,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import na from"clsx";import W,{useEffect as bt,useReducer as ia,useState as yn}from"react";import{flushSync as oa}from"react-dom";import{useRef as Ul}from"react";import{useEffect as Fl}from"react";function ea({gameState:o}){let e=Ul(null);return Fl(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{o.events.emit(E.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[o.deps]),null}import Wn,{useEffect as Ol}from"react";function cr({gameState:o}){let[e]=te(),{ratio:t}=fe(),n=o.notificationMgr;Ol(()=>n.onFlush(()=>{e()}).cancel,[]);let i=o.game.config.notification;return Wn.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"},Wn.createElement(i,{notifications:n.toArray()}))}function ta({notifications:o}){return Wn.createElement(Hi,{className:"absolute top-0 left-0 w-full h-full"},o.map(({id:e,message:t})=>Wn.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},Wn.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function ra({story:o=Dn.empty(),width:e,height:t,className:n,onReady:i,onPreloadComplete:r,onPreloadedReady:s,onFirstSceneReady:a,onEnd:c,onError:l,children:p,active:u=!0}){let[d,g]=ia(x=>x+1,0),[f,T]=ia(x=>x+1,0),[h,y]=yn(0),m=P(),[S]=yn(()=>new E(m,{update:g,forceUpdate:()=>{S.logger.weakWarn("Player","force update"),oa(()=>{g()})},forceRemount:()=>{S.logger.weakWarn("Player","force remount"),oa(()=>{y(x=>x+1),g()})},next:ue})),L=W.createRef(),O=W.createRef(),[A,R]=yn(!1),j=W.useRef(!1),K=W.useRef(null),se=W.useRef(null),{preloaded:Ge}=fn(),[ke,At]=yn(!1),Be=W.useRef(!1),[ge,G]=yn(!1),ie=W.useRef(!1),Z=W.useRef(null),q=W.useRef(!1),[I]=yn(new Map);function ye(x){return{game:m,gameState:S,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable(),scene:x}}function ue(){let x=()=>{I.forEach(w=>w.cancel())};if(S.rollLock.isLocked())return;x();let N=!1,_=0;for(;!N;){if(_++>m.config.maxStackModelLoop)throw new k("Max stack model loop reached");let w=m.getLiveGame().next();if(!w){if(m.getLiveGame().stackModel&&!m.getLiveGame().stackModel.isEmpty())continue;break}if(v.isAwaitable(w)){if(K.current===w)break;K.current=w,w.onSettled(()=>{w.isFailed()||(K.current===w&&(K.current=null),ue())}),w.onFailed(ze=>{K.current===w&&(K.current=null),S.logger.error("Player",ze)}),N=!0;break}if(w instanceof tn){if(se.current===w)break;se.current=w,w.nextUnlock().then(()=>{se.current===w&&(se.current=null),ue()}),N=!0;break}if(Oe.isCalledActionResult(w)&&w.wait&&Oe.isStackModelsAwaiting(w.wait.type,w.wait.stackModels)){if(K.current===w)break;if(K.current=w,w.wait){let ze=Oe.executeStackModelGroup(w.wait.type,w.wait.stackModels);ze.then(()=>{K.current===w&&(K.current=null),ue()}),ze.onFailed(xt=>{K.current===w&&(K.current=null),S.logger.error("Player",xt)})}N=!0;break}S.handle(w)}S.stage.update()}bt(()=>{S.audioManager.initialize()},[]),bt(()=>(m.getLiveGame().setGameState(S),o&&!m.getLiveGame().isPlaying()&&m.getLiveGame().loadStory(o),S.playerCurrent=L.current,S.mainContentNode=O.current,()=>{m.getLiveGame().setGameState(void 0),S.playerCurrent=null}),[m,o]),bt(()=>je(()=>{R(!0);let x=S.getLastScene(),N=[];x?N.push(x.events.once("event:scene.mount",()=>{S.stage.next()}).cancel):S.stage.next();let _=S.events.on(E.EventTypes["event:state.end"],()=>{c&&c({game:m,gameState:S,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()})});return S.stage.update(),()=>{x&&N.forEach(w=>w()),_.cancel()}}),[]),bt(()=>je(()=>{A&&i&&!j.current&&(j.current=!0,S.stage.forceUpdate(),m.hooks.trigger("init",[]),i({game:m,gameState:S,liveGame:m.getLiveGame(),storable:m.getLiveGame().getStorable()}))}),[A]),bt(()=>je(()=>{if(ke&&s&&!Be.current){Be.current=!0;let x=Z.current||S.getLastScene()||S.getPreloadingScene(),N=ye(x);s(N)}}),[ke]),bt(()=>je(()=>{if(ge&&!ie.current){ie.current=!0;let x=Z.current||S.getLastScene()||S.getPreloadingScene(),N=ye(x);m.markPreloadComplete(N)&&r&&r(N)}}),[ge]),bt(()=>S.events.on(E.EventTypes["event:state.scene.mount"],x=>{Z.current||(Z.current=x,T())}).cancel,[]),bt(()=>{if(!ge||!u||q.current||m.isFirstSceneReady())return;let x=Z.current||S.getLastScene();if(!x)return;let N=null,_=null,w=!1;q.current=!0;let ze=()=>{w=!0,q.current=!1;let xt=ye(x);m.markFirstSceneReady(xt)&&a&&a(xt)};return typeof requestAnimationFrame=="function"?N=requestAnimationFrame(()=>{_=setTimeout(ze,0)}):_=setTimeout(ze,0),()=>{w||(q.current=!1,N!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(N),_!==null&&clearTimeout(_))}},[u,f,d,ge]),bt(()=>Ge.events.depends([Ge.events.on(Me.EventTypes["event:preloaded.ready"],()=>{At(!0),S.stage.update(),o&&m.getLiveGame().isPlaying()&&ue()}),Ge.events.on(Me.EventTypes["event:preloaded.complete"],()=>{G(!0)})]).cancel,[]),bt(()=>{S.flushDep=d},[d]);let ae=e||m.config.width,V=t||m.config.height;return W.createElement(Yi,{onError:l},W.createElement("div",{style:{width:typeof ae=="number"?`${ae}px`:ae,height:typeof V=="number"?`${V}px`:V},className:na(n,"__narraleaf_content-player"),ref:L,tabIndex:0},W.createElement(rr,{className:na("flex-grow overflow-auto"),gameState:S},W.createElement(Wo,{gameState:S}),W.createElement(ea,{gameState:S}),W.createElement(vt,{className:"absolute",ref:O,style:{cursor:S.game.config.cursor?"none":"auto",overflow:S.game.config.showOverflow?"visible":"hidden"}},m.config.cursor&&W.createElement(sr,{src:m.config.cursor,width:m.config.cursorWidth,height:m.config.cursorHeight}),W.createElement(Kl,{show:ke&&u,key:h},W.createElement(Uo,null,W.createElement(Ms,{state:S}),W.createElement(Fs,{state:S}),S.getSceneElements().map(x=>W.createElement(nr,{key:"scene-"+x.scene.getId(),state:S,elements:x})),S.getVideos().map((x,N)=>W.createElement("div",{className:"w-full h-full absolute",key:"video-"+N,"data-element-type":"video"},W.createElement(or,{gameState:S,video:x}))),W.createElement(Vl,{NvlComponent:m.config.nvlDialog}))),W.createElement(Vs,{state:S}),W.createElement(Cs,null,p),W.createElement(cr,{gameState:S})))))}function Kl({children:o,show:e}){return W.createElement(W.Fragment,null,e?o:null)}function Vl({NvlComponent:o}){let{dialogs:e,state:t}=St(),i=P().getLiveGame().getGameState(),r=W.useMemo(()=>e.map((s,a)=>{let c=s.sentence.evaluate(Se.getCtx({gameState:i})),l=t.activeDialogId===s.id,p=l&&t.phase==="typing";return{entry:s,index:a,isActive:l,gameState:i,words:c,useTypeEffect:p}}),[e,i,t.activeDialogId,t.phase]);return W.createElement(o,{dialogs:r})}import"client-only";import vn from"react";function sa({children:o,game:e}){return vn.createElement(vn.Fragment,null,vn.createElement(is,null,vn.createElement(Zr,{game:e},vn.createElement(Ks,null,vn.createElement(ns,null,o)))))}var Wl=(r=>(r.image="narraleaf:image",r.text="narraleaf:text",r.layer="narraleaf:layer",r.scene="narraleaf:scene",r.video="narraleaf:video",r))(Wl||{});import Bl from"clsx";import Ct,{useEffect as aa,useRef as zl}from"react";import{motion as $l,useIsPresent as jl}from"motion/react";var ql={defaultColor:"#000",fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif"};function Ql({children:o,initial:e,transition:t,...n}){let i=P(),r=ct(),{ratio:s}=fe(),[a]=at(J.Preferences.showDialog),c=zl(null),[l]=Xt("nextAction"),p=jl();function u(){r.requestComplete()}return aa(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
48
|
+
at Say.tsx: onElementClick`);return}let d=f=>{i.keyMap.match("nextAction",f.key)&&r.requestComplete()};window.addEventListener("keyup",d);let g=r.events.on(Ce.Events.simulateClick,()=>{c.current&&c.current.click()});return()=>{window.removeEventListener("keyup",d),g.cancel()}},[r,l]),aa(()=>{let d=i.preference.onPreferenceChange(J.Preferences.autoForward,g=>{g&&r.isEnded()?r.tryScheduleAutoForward():r.cancelAutoForward()});return()=>{d.cancel()}},[r]),Ct.createElement("div",{"data-element-type":"dialog",className:"absolute w-full h-full"},Ct.createElement("div",{className:Bl("absolute bottom-0 w-full h-full",!a&&"invisible pointer-events-auto"),onClick:u,style:{...ii(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},Ct.createElement($l.div,{...n,initial:r.config.suppressInitialAnimation?!1:e,transition:r.config.suppressInitialAnimation&&p?{duration:0}:t},o)))}function ca({children:o,...e}){let t=ct();return!t.config.action.sentence||!t.config.action.words?null:Ct.createElement(Ql,{...e},o)}var cl=ca;function la(){return Ct.createElement(ca,null,Ct.createElement("div",{className:"dialog-content",style:{display:"flex",alignItems:"flex-start",gap:16,width:"100%",height:"100%"}},Ct.createElement(Do,null),Ct.createElement("div",{className:"dialog-text-content",style:{minWidth:0,flex:"1 1 auto"}},Ct.createElement(Lt,null),Ct.createElement(Ft,{...ql}))))}var Bn={say:la,menu:Ws,notification:ta,nvlDialog:Ko};var Ji=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 zn=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 ua=(e=>(e.game="game",e))(ua||{}),Ke=class Ke{constructor(e){this.hooks=new _n;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new Rn(Ke.DefaultPreference);this.keyMap=new zn({skipAction:["Control"],nextAction:[" "]});this.lifecycleEvents=new Q;this.preloadCompleteContext=null;this.firstSceneReadyContext=null;this.config=U(Ke.DefaultConfig,e),this.plugins=new Ji(this),this.router=new Ut(this)}configure(e){let[t,n]=Gr(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=U(this.config,t),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}onPreloadComplete(e){return this.lifecycleEvents.on(Ke.LifecycleEventTypes["event:game.preloadComplete"],e)}oncePreloadComplete(e){return this.lifecycleEvents.once(Ke.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(Ke.LifecycleEventTypes["event:game.firstSceneReady"],e)}onceFirstSceneReady(e){return this.lifecycleEvents.once(Ke.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(Ke.LifecycleEventTypes["event:game.preloadComplete"],e),!0)}markFirstSceneReady(e){return this.firstSceneReadyContext?!1:(this.firstSceneReadyContext=e,this.lifecycleEvents.emit(Ke.LifecycleEventTypes["event:game.firstSceneReady"],e),!0)}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new ht(this)}};Ke.defaultSettings={volume:1},Ke.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,voiceFadeDuration:0,voiceEndMode:"stop",bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:500,skipInterval:100},Ke.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"},Ke.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,allowSkipBackgroundTransition:!1,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,notification:Bn.notification,menu:Bn.menu,dialog:Bn.say,nvlDialog:Bn.nvlDialog,onError:e=>{console.error(e)},stage:null,maxStackModelLoop:1e3,maxActionHistory:100},Ke.GameSettingsNamespace=ua,Ke.LifecycleEventTypes={"event:game.preloadComplete":"event:game.preloadComplete","event:game.firstSceneReady":"event:game.firstSceneReady"};var J=Ke;var Zi=class Zi extends z{static executeActionsAsync(e,t){let n=e.game.getLiveGame().requestAsyncStackModel([{type:t.type,node:t.contentNode}]);return e.game.getLiveGame().executeAsyncStackModel(n)}checkActionChain(e){if(e.some(t=>!!t.contentNode.getChild()))throw new Error("Invalid action chain. Actions are chained unexpectedly.");return e}executeAction(e,t){let n=this.contentNode,[i]=n.getContent();if(this.type===Ae.do)return[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:i[0].contentNode}];if(this.type===Ae.doAsync){let r=Zi.executeActionsAsync(e,i[0]);return e.timelines.attachTimeline(r),super.executeAction(e,t)}else if(this.type===Ae.any){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().createStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:r}}}else if(this.type===Ae.all){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().createStackModel([{type:s.type,node:s.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:r}}}else if(this.type===Ae.allAsync){if(i.length===0)return{type:this.type,node:this.contentNode.getChild()};let r=this.checkActionChain(i).map(s=>e.game.getLiveGame().requestAsyncStackModel([{type:s.type,node:s.contentNode}]));return e.timelines.attachTimeline(v.all(...r.map(s=>e.game.getLiveGame().executeAsyncStackModel(s)))),super.executeAction(e,t)}else if(this.type===Ae.repeat){let[r,s]=this.contentNode.getContent();if(s<=0||r.length===0)return super.executeAction(e,t);let a=Oe.createCountLoop(e.game.getLiveGame(),s,this.checkActionChain(r));return e.logger.debug("ControlAction","repeat",r,s),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[a]}}}else if(this.type===Ae.while){let[r,s]=this.contentNode.getContent();if(r.length===0)return super.executeAction(e,t);if(!s.evaluate({gameState:e}).value)return super.executeAction(e,t);let a=Oe.createConditionLoop(e.game.getLiveGame(),s,this.getId(),this.checkActionChain(r));return e.logger.debug("ControlAction","while",r),{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:[a]}}}else if(this.type===Ae.break){if(!t.stackModel.isLoop())throw new Error("Control.breakLoop() can only be used inside a loop (repeat/while)");return t.stackModel.breakLoop(),{type:this.type,node:null}}else if(this.type===Ae.sleep){let[,r]=this.contentNode.getContent(),s;typeof r=="number"?s=v.delay(r):v.isAwaitable(r)?s=r:s=v.fromPromise(r);let a=new v,c=new we(s);return e.timelines.attachTimeline(c),s.then(()=>{a.resolve({type:this.type,node:this.contentNode.getChild()})}),a.onSkipControllerRegister(l=>{l.onAbort(()=>{c.abort()})}),a}else if(this.type===Ae.waitForClick){if(e.consumeStageClick())return{type:this.type,node:this.contentNode.getChild()};let r=new v,s=new v,a=new we(s);e.timelines.attachTimeline(a);let c=e.game.preference,l=c.getPreference(J.Preferences.autoForward),p=c.getPreference(J.Preferences.gameSpeed),u=l?e.game.config.autoForwardDelay/p:null,d=!1,g=null,f=null,T=null,h=()=>{f?.cancel(),T?.cancel(),g&&(clearTimeout(g),g=null)},y=()=>{d||(d=!0,h(),s.resolve())};return f=e.events.on(E.EventTypes["event:state.player.stageClick"],y),T=e.events.on(E.EventTypes["event:state.player.skip"],y),u!==null&&(g=setTimeout(y,u)),s.then(()=>{r.resolve({type:this.type,node:this.contentNode.getChild()})}),r.onSkipControllerRegister(m=>{m.onAbort(()=>{d||(d=!0,h(),a.abort())})}),r}throw new Error("Unknown control action type: "+this.type)}getFutureActions(e,t){if(this.callee.config.allowFutureScene===!1&&t.allowFutureScene===!1)return[...super.getFutureActions(e,t)];if(this.type===Ae.break||this.type===Ae.waitForClick)return super.getFutureActions(e,t);let n=this.contentNode.getContent()[0],i=super.getFutureActions(e,t);return[...n??[],...i]}stringify(e,t,n){if(this.type===Ae.break)return super.stringifyWithContent("Control","break");if(this.type===Ae.waitForClick)return super.stringifyWithContent("Control","waitForClick");let i=this.contentNode,[r]=i.getContent();return super.stringifyWithContent("Control",r.map(s=>s.stringify(e,t,n)).join(";"))}};Zi.ActionTypes=Ae;var de=Zi;var Le=class o extends oe{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()}do(t){return this.push(de.ActionTypes.do,t)}doAsync(t){return this.push(de.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(de.ActionTypes.any,t)}all(t){return this.pushUnchained(de.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(de.ActionTypes.allAsync,t)}repeat(t,n){return this.push(de.ActionTypes.repeat,n,t)}whileLoop(t,n){let i=F.from(t);return this.pushWithLambda(de.ActionTypes.while,n,i)}breakLoop(){let t=new de(this.chain(),de.ActionTypes.break,new b().setContent([]));return this.chain(t)}sleep(t){return this.push(de.ActionTypes.sleep,[],t)}waitForClick(){let t=new de(this.chain(),de.ActionTypes.waitForClick,new b().setContent([]));return this.chain(t)}push(t,n,...i){let r=this.narrativeToActions(n),s=new de(this.chain(),t,new b().setContent([this.construct(r),...i]));return this.chain(s)}pushUnchained(t,n,...i){let r=this.narrativeToActions(n),s=new de(this.chain(),t,new b().setContent([r,...i]));return this.chain(s)}pushWithLambda(t,n,i){let r=this.narrativeToActions(n),s=new de(this.chain(),t,new b().setContent([this.construct(r),i]));return this.chain(s)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?kt.say(n).getActions():Ee.toActions([n]))}};var ne=class ne extends mt{static getInitialSrc(e){if(this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return C.isStaticImageData(t)?C.srcToURL(t):C.isColor(t)?t:C.isImageSrc(t)?C.srcToURL(t):ne.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isTagDefinition(e){return typeof e=="object"&&e!==null&&!C.isImageSrc(e)&&!C.isColor(e)&&"defaults"in e}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(C.isImageSrc(t)||C.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:ne.isTagSrc(e)?ne.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):ne.isStaticSrc(e)?C.isStaticImageData(e.state.currentSrc)?C.srcToURL(e.state.currentSrc):C.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static fromSrc(e){return new ne({src:e})}constructor(e={}){super();let t=ne.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 Le,n=>{if(C.isImageSrc(e)||C.isColor(e)){if(C.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 re(n,re.ActionTypes.setAppearance,new b().setContent([e,t?.copy()]));return n.chain(i).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new Le,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 he("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:ne.StateSerializer.serialize(this.state),transformState:be.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=ne.StateSerializer.deserialize(e.state),this.transformState=be.deserialize(e.transformState),this}_applyTransition(e,t){return new De(this.chain(),Pe.applyTransition,new b().setContent([e,t]))}_init(e,t){return new De(this.chain(),Pe.init,new b().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new re(this.chain(),re.ActionTypes.initWearable,new b().setContent([e]))}_flush(){return new re(this.chain(),re.ActionTypes.flush,new b)}reset(){return this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!ne.isTagSrc(this))throw new Error(`Tag not defined
|
|
49
49
|
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}_mixedSrcError(){throw new he(`Trying to mix src and tags
|
|
50
50
|
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
|
|
51
51
|
Wearable must be an Image with isWearable set to true
|
|
@@ -55,7 +55,7 @@ Image below violates the rule:
|
|
|
55
55
|
Tag "${r}" is conflicting with another tag
|
|
56
56
|
Error found in config.tag.defaults`);if(!n.has(r))throw new Error(`Tag not found
|
|
57
57
|
Tag "${r}" is not defined in tagDefinitions
|
|
58
|
-
Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}}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 re(e,re.ActionTypes.setDarkness,new b().setContent([t,n,i]))}};ne.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",ne.StateSerializer=new $e,ne.DefaultUserConfig=new X({name:"(anonymous)",autoInit:!0,src:ne.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...be.DefaultTransformState.getDefaultConfig()},{position:e=>L.tryParsePosition(e)}),ne.DefaultImageConfig=new X({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),ne.DefaultImageState=new X({currentSrc:ne.DefaultImagePlaceholder,darkness:0});var M=ne;var le=class extends ft{_setPrevSrc(e){return this._prevSrc=e,this}_setTargetSrc(e){return this._targetSrc=e,this}_setCurrentSrc(e){return this._currentSrc=e,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(e){let t=super.requestAnimations(e);return t.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),t}asPrev(e){return super.asPrev((...t)=>U(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>U(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(C.isColor(e))return{src:M.DefaultImagePlaceholder,style:{backgroundColor:C.isRGBAColor(e)?C.RGBAColorToHex(e):e}};if(C.isImageSrc(e))return{src:C.srcToURL(e)};throw new he("Image transition src cannot be identified, using: "+e)}};var _i=class o extends le{constructor(t,n,i,r){super();this.prevDarkness=t;this.targetDarkness=n;this.duration=i;this.easing=r}createTask(){return{animations:[{type:0,start:this.prevDarkness,end:this.targetDarkness,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{filter:`brightness(${1-t})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o(this.prevDarkness,this.targetDarkness,this.duration,this.easing)}};var $n=class $n extends z{static resolveTagSrc(e,t){if(!M.isTagSrc(e))throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return M.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(M.isStaticSrc(e))return C.isImageSrc(e.state.currentSrc)?C.srcToURL(e.state.currentSrc):e.state.currentSrc;if(M.isTagSrc(e))return M.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===Je.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new v(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===Je.setSrc){let n=this.contentNode.getContent()[0];if(C.isColor(n)&&!this.callee.config.isBackground)throw new he("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(),super.executeAction(e,t)}else{if(this.type===Je.flush)return super.executeAction(e,t);if(this.type===Je.setAppearance){let[n,i]=this.contentNode.getContent();if(!M.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],c=M.getSrcFromTags(s,this.callee.config.src.resolve),l=()=>{this.callee.state.currentSrc=a};if(e.logger.debug("Image - Set Appearance",s,c),i){let p=new v(f=>f).registerSkipController(new H(()=>super.executeAction(e,t)));i._setPrevSrc($n.resolveCurrentSrc(this.callee))._setTargetSrc(c);let d=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,p.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(p).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},l,[]),p}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},l),super.executeAction(e,t)}else if(this.type===Je.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&&r){let l=$n.resolveCurrentSrc(this.callee),p=new v(f=>f),u=new _i(s,n,i,r)._setPrevSrc(l)._setTargetSrc(l),d=c.applyTransition(u,()=>{this.callee.state.darkness=n,p.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(p).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},()=>{p.isSettled()||p.abort(),d.abort(),a()}),p}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")}};$n.ActionTypes=Je;var re=$n;var Rt=class Rt extends z{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 Rt.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 he("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)}applyTransition(e,t,n){let i=new v().registerSkipController(new H(()=>(e.logger.info("Background Transition","Skipped"),super.executeAction(e,n))));return e.getExposedStateForce(this.callee.background).applyTransition(t,()=>{i.resolve(super.executeAction(e,n))}),e.timelines.attachTimeline(i),i}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 v(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===B.action)return super.executeAction(e,t);if(this.is(Rt,"scene:init")){let n=new v(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 Rt.handleSceneInit(this.callee,r,e,v.forward(n,r))}else if(this.type===B.exit){let n=Rt.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new v(s=>s);e.timelines.attachTimeline(r),Rt.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),Rt.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===B.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===B.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===B.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===B.transitionToScene){let[n,i,r]=this.contentNode.getContent();return n._setPrevSrc(re.resolveCurrentSrc(this.callee.background)),i?n._setTargetSrc(re.resolveCurrentSrc(i.background)):r&&n._setTargetSrc(r),this.applyTransition(e,n,t)}else if(this.type===B.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===B.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=v.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===B.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=v.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===B.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===B.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===B.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 he(`Scene with name ${e} not found
|
|
58
|
+
Error found in config.tag.defaults`);n.get(r)?.forEach(s=>i.add(s))}}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 re(e,re.ActionTypes.setDarkness,new b().setContent([t,n,i]))}};ne.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",ne.StateSerializer=new $e,ne.DefaultUserConfig=new X({name:"(anonymous)",autoInit:!0,src:ne.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...be.DefaultTransformState.getDefaultConfig()},{position:e=>D.tryParsePosition(e)}),ne.DefaultImageConfig=new X({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),ne.DefaultImageState=new X({currentSrc:ne.DefaultImagePlaceholder,darkness:0});var M=ne;var le=class extends ft{_setPrevSrc(e){return this._prevSrc=e,this}_setTargetSrc(e){return this._targetSrc=e,this}_setCurrentSrc(e){return this._currentSrc=e,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(e){let t=super.requestAnimations(e);return t.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),t}asPrev(e){return super.asPrev((...t)=>U(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>U(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(C.isColor(e))return{src:M.DefaultImagePlaceholder,style:{backgroundColor:C.isRGBAColor(e)?C.RGBAColorToHex(e):e}};if(C.isImageSrc(e))return{src:C.srcToURL(e)};throw new he("Image transition src cannot be identified, using: "+e)}};var _i=class o extends le{constructor(t,n,i,r){super();this.prevDarkness=t;this.targetDarkness=n;this.duration=i;this.easing=r}createTask(){return{animations:[{type:0,start:this.prevDarkness,end:this.targetDarkness,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{filter:`brightness(${1-t})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new o(this.prevDarkness,this.targetDarkness,this.duration,this.easing)}};var $n=class $n extends z{static resolveTagSrc(e,t){if(!M.isTagSrc(e))throw e._mixedSrcError();let n=e.state.currentSrc,i=e.resolveTags(n,t);return M.getSrcFromTags(i,e.config.src.resolve)}static resolveCurrentSrc(e){if(M.isStaticSrc(e))return C.isImageSrc(e.state.currentSrc)?C.srcToURL(e.state.currentSrc):e.state.currentSrc;if(M.isTagSrc(e))return M.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===Je.initWearable){let[n]=this.contentNode.getContent(),i=e.getExposedStateForce(this.callee),r=new v(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===Je.setSrc){let n=this.contentNode.getContent()[0];if(C.isColor(n)&&!this.callee.config.isBackground)throw new he("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(),super.executeAction(e,t)}else{if(this.type===Je.flush)return super.executeAction(e,t);if(this.type===Je.setAppearance){let[n,i]=this.contentNode.getContent();if(!M.isTagSrc(this.callee))throw this.callee._mixedSrcError();let r=this.callee.state.currentSrc,s=this.callee.resolveTags(r,n),a=[...r],c=M.getSrcFromTags(s,this.callee.config.src.resolve),l=()=>{this.callee.state.currentSrc=a};if(e.logger.debug("Image - Set Appearance",s,c),i){let p=new v(f=>f).registerSkipController(new H(()=>super.executeAction(e,t)));i._setPrevSrc($n.resolveCurrentSrc(this.callee))._setTargetSrc(c);let d=e.getExposedStateForce(this.callee).applyTransition(i,()=>{this.callee.state.currentSrc=s,p.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(p).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},l,[]),p}return this.callee.state.currentSrc=s,e.actionHistory.push({action:this,stackModel:t.stackModel},l),super.executeAction(e,t)}else if(this.type===Je.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&&r){let l=$n.resolveCurrentSrc(this.callee),p=new v(f=>f),u=new _i(s,n,i,r)._setPrevSrc(l)._setTargetSrc(l),d=c.applyTransition(u,()=>{this.callee.state.darkness=n,p.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(p).attachChild(d);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},()=>{p.isSettled()||p.abort(),d.abort(),a()}),p}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")}};$n.ActionTypes=Je;var re=$n;var Rt=class Rt extends z{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 Rt.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 he("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)}applyTransition(e,t,n){let i=new v().registerSkipController(new H(()=>(e.logger.info("Background Transition","Skipped"),super.executeAction(e,n))));return e.getExposedStateForce(this.callee.background).applyTransition(t,()=>{i.resolve(super.executeAction(e,n))}),e.timelines.attachTimeline(i),i}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 v(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===B.action)return super.executeAction(e,t);if(this.is(Rt,"scene:init")){let n=new v(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 Rt.handleSceneInit(this.callee,r,e,v.forward(n,r))}else if(this.type===B.exit){let n=Rt.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{let r=new v(s=>s);e.timelines.attachTimeline(r),Rt.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,r),Rt.restoreSceneSnapshot(i,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===B.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===B.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===B.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===B.transitionToScene){let[n,i,r]=this.contentNode.getContent();return n._setPrevSrc(re.resolveCurrentSrc(this.callee.background)),i?n._setTargetSrc(re.resolveCurrentSrc(i.background)):r&&n._setTargetSrc(r),this.applyTransition(e,n,t)}else if(this.type===B.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===B.nvlShow){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!0,n,t),s=v.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===B.nvlHide){let[n]=this.contentNode.getContent(),i=e.getNvlState().visible,r=this.applyNvlVisibility(e,!1,n,t),s=v.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===B.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===B.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===B.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 he(`Scene with name ${e} not found
|
|
59
59
|
Make sure you have registered the scene using story.register
|
|
60
60
|
Action: (id: ${this.getId()}) ${this.type}
|
|
61
61
|
At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===B.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")}};Rt.ActionTypes=B;var ee=Rt;var lr=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)}},ut=class ut{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)||ut.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return ut.isHexString(e)||ut.isNamedColor(e)||ut.isRGBAColor(e)}static isNamedColor(e){return Ir(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(ut.isHexString(e))return e;if(ut.isNamedColor(e))return e;if(ut.isRGBAColor(e))return ut.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),p=n.invertX?{right:c}:{left:c},u=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...p,...u}}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)}};ut.RGBColor=lr;var C=ut,ur=class o extends Error{static isUseError(e){return e instanceof o}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},xe=class o extends ur{static isWarning(e){return e instanceof o}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},Si=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 re)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof ee){let s=t.callee;if(i.has(s.config.name)){if(i.get(s.config.name)!==s){let a=`Scene with name: ${s.config.name} is duplicated
|