narraleaf-react 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -98,7 +98,22 @@ export declare class StackModel {
98
98
  getTopSync(): CalledActionResult | null;
99
99
  executeActions(result: CalledActionResult): CalledActionResult | Awaitable<CalledActionResult> | null;
100
100
  isWaiting(): boolean;
101
- serialize(): StackModelRawData;
101
+ /**
102
+ * Serialize current StackModel into a plain JSON-serialisable structure.
103
+ *
104
+ * @param frozen - When true (default), the snapshot also contains the
105
+ * action currently executing at the top of the stack
106
+ * (waitingAction). This is required by save/load so that
107
+ * reloading a save resumes exactly at the current dialog or
108
+ * async node, keeping the runtime state self-consistent.
109
+ * When false, waitingAction is excluded and the snapshot
110
+ * reflects the state *before* the current action started.
111
+ * The undo/history system will then re-insert the action
112
+ * manually (see LiveGame.undo) to avoid having two copies
113
+ * of the same action after deserialisation.
114
+ * @returns Snapshot that can be passed to {@link StackModel.deserialize}.
115
+ */
116
+ serialize(frozen?: boolean): StackModelRawData;
102
117
  reset(): void;
103
118
  deserialize(data: StackModelRawData, actionMap: Map<string, LogicAction.Actions>): this;
104
119
  isEmpty(): boolean;
package/dist/main.js CHANGED
@@ -1,6 +1,6 @@
1
1
  var ae={action:"displayable:action",applyTransform:"displayable:applyTransform",applyTransition:"displayable:applyTransition",init:"displayable:init"},Rn={say:"character:say",action:"character:action",setName:"character:setName"},_={action:"scene:action",init:"scene:init",exit:"scene:exit",jumpTo:"scene:jumpTo",setBackgroundMusic:"scene:setBackgroundMusic",preUnmount:"scene:preUnmount",transitionToScene:"scene:transitionToScene"};var we={action:"image:action",setSrc:"image:setSrc",flush:"image:flush",initWearable:"image:initWearable",setAppearance:"image:setAppearance",setDarkness:"image:setDarkness"},Di={action:"condition:action"},Ri={action:"script:action"},Li={action:"menu:action"},mt={action:"sound:action",play:"sound:play",stop:"sound:stop",setVolume:"sound:setVolume",setRate:"sound:setRate",pause:"sound:pause",resume:"sound:resume"},We={action:"control:action",do:"control:do",doAsync:"control:doAsync",any:"control:any",all:"control:all",allAsync:"control:allAsync",repeat:"control:repeat",sleep:"control:sleep"},Ln={action:"text:action",setText:"text:setText",setFontSize:"text:setFontSize"},Xt={action:"persistent:action",set:"persistent:set",assign:"persistent:assign"},vt={action:"layer:action",setZIndex:"layer:setZIndex"},Gt={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 Ii=(m=>(m[m.string=0]="string",m[m.number=1]="number",m[m.boolean=2]="boolean",m[m.object=3]="object",m[m.array=4]="array",m[m.function=5]="function",m[m.symbol=6]="symbol",m[m.undefined=7]="undefined",m[m.null=8]="null",m[m.date=9]="date",m[m.regexp=10]="regexp",m[m.other=11]="other",m))(Ii||{}),No=function(s){return typeof s=="string"?0:typeof s=="number"?1:typeof s=="boolean"?2:typeof s=="object"?Array.isArray(s)?4:s===null?8:s instanceof Date?9:s instanceof RegExp?10:3:typeof s=="function"?5:typeof s=="symbol"?6:typeof s>"u"?7:11};No.DataTypes=Ii;function D(s,e,...t){let n=(r,a)=>Object.prototype.hasOwnProperty.call(r,a),o={},i=(r,a,c)=>No(a)===3&&No(c)===3?a.constructor!==Object||c.constructor!==Object?c||a:D(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 r in s)n(s,r)&&(o[r]=i(r,s[r],e[r]));for(let r in e)n(e,r)&&!n(o,r)&&(typeof e[r]=="object"&&e[r]!==null?e[r].constructor===Object?o[r]=D({},e[r]):Array.isArray(e[r])?o[r]=[...e[r]]:o[r]=e[r]:o[r]=e[r]);if(t.length){let[r,...a]=t;return D(o,r,...a)}return o}var ye=class ye{constructor(e=n=>n,t){this.solved=!1;this.aborted=!1;this.listeners=[];this.onRegisterSkipController=[];this.receiver=e,this.skipController=t,this.__stack=Ho()}static isAwaitable(e){return e instanceof ye}static fromPromise(e){let t=new ye;return e.then(n=>t.resolve(n)),t}static resolve(e){let t=new ye;return t.resolve(e),t}static delay(e){let t=new ye;return setTimeout(()=>t.resolve(),e),t}static create(e){let t=new ye;return e(t),t}static wait(e){let t=new ye;return e.then(()=>t.resolve()),t}static race(e){let t=new ye;return e.length===0?(t.resolve(void 0),t):(e.forEach(n=>{n.then(o=>{e.forEach(i=>{i!==n&&i.skipController?.abort()}),t.resolve(o)})}),t.registerSkipController(new L(()=>{e.forEach(n=>n.skipController?.abort())})),t)}static forward(e,t,n){let o=new ye().registerSkipController(n||new L(()=>t));e.then(()=>o.resolve(t));let i=e.skipController?.onAbort(()=>{o.skipController?.abort(),i?.cancel(),r?.cancel()}),r=o.skipController?.onAbort(()=>{e.skipController?.abort(),i?.cancel(),r?.cancel()});return o}static toPromise(e){return new Promise(t=>{e.then(t)})}static toPromiseForce(e){return new Promise(t=>{e.onSettled(t)})}static any(...e){let t=new ye;return e.forEach(n=>{n.onSettled(()=>t.resolve())}),t}static all(...e){let t=new ye,n=0;return e.forEach(o=>{o.onSettled(()=>{n++,n===e.length&&t.resolve()})}),t}registerSkipController(e){this.skipController=e;for(let t of this.onRegisterSkipController)t(e);return this}resolve(e){if(!this.solved){this.result=this.receiver(e),this.solved=!0,this.skipController&&this.skipController.cancel();for(let t of this.listeners)t(this.result)}}then(e){return this.solved?e(this.result):this.pushListener(e),this}onSettled(e){if(this.solved)e();else{this.pushListener(e);let t=[];return t.push(this.onSkipControllerRegister(n=>{t.push(n.onAbort(()=>{e()}))})),{cancel:()=>{t.forEach(n=>n.cancel()),this.offListener(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.aborted=!0,this.skipController?this.skipController.abort():this.result}isSolved(){return this.solved&&!this.aborted}isAborted(){return this.aborted}isSettled(){return this.solved||this.aborted}pushListener(e){return this.listeners.length>=ye.maxListeners&&console.warn("NarraLeaf-React: Awaitable has too many listeners, this may cause performance issues."),this.listeners.push(e),this}offListener(e){let t=this.listeners.indexOf(e);return t!==-1&&this.listeners.splice(t,1),this}};ye.nothing=e=>e,ye.maxListeners=8;var h=ye;function Mi(s){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 i=[];for(let r of n)i.push(t(r));return i}let o={};for(let i in n)Object.prototype.hasOwnProperty.call(n,i)&&(o[i]=t(n[i]));return o}return t(s)}function At(s){return typeof s=="string"?s:`#${(s.r||0).toString(16).padStart(2,"0")}${(s.g||0).toString(16).padStart(2,"0")}${(s.b||0).toString(16).padStart(2,"0")}${s.a===void 0?"":s.a.toString(16).padStart(2,"0")}`}var K=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(o=>{o(...t)}),n}once(e,t){let n=(...o)=>{t(...o),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 o="event:EventDispatcher.register",i=this.on(o,(r,a)=>{if(r===e){this.off(o,i);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 Ho(s=1){let e=new Error().stack;return e?e.split(`
2
2
  `).slice(s+1).join(`
3
- `).trim():""}function Kn(s){return new Promise(e=>setTimeout(e,s))}var Un=class Un{constructor(e){this.abortHandler=e;this.events=new K;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Un.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Un.EventTypes={"event:skipController.abort":"event:skipController.abort"};var L=Un;var Jt=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}},Nt=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Jt;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 Fn(s,e,t={}){return s?e:t}function Gi(s,e){if(e<=0)return s;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{s(...n)},e)}}var In=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,o=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(o),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function Ni(s,e){let t=[];for(let n=0;n<Math.max(s.length,e.length);n++)n<s.length&&t.push(s[n]),n<e.length&&t.push(e[n]);return t}async function Hi(s,e){return new Promise((t,n)=>{fetch(s,e).then(o=>o.blob()).then(o=>{let i=new FileReader;i.onload=()=>{t(i.result)},i.readAsDataURL(o)}).catch(n)})}var Yt=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 Kn(this.delay),await e()};await e()}};function Ie(s){let e,t=Promise.resolve().then(()=>{e=s()});return()=>{t.then(()=>{e&&e()})}}function Ui(s,e){let t={};for(let n in s)e.includes(n)||(t[n]=s[n]);return t}var Se=class s{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},o={...this.deserializer,...t};return new s(n,o)}};function Ki(s){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(s)}var dt=class extends h{constructor(t){super();this.tasks=[];t&&this.registerSkipController(t)}addTask(t){return t?(this.tasks.push(t),this):this}abort(){this.current&&this.current.abort(),this.tasks.forEach(([t,n])=>{n&&n.abort()}),super.abort()}resolve(){}run(){return this.current?this:(this.onTaskComplete(),this)}onTaskComplete(){if(this.tasks.length===0){super.resolve();return}let[t,n]=this.tasks.shift(),o=new h(h.nothing,n);this.current=o,this.current.then(()=>this.onTaskComplete()),t(o)}};function Fi(s){return s.constructor.name==="AsyncFunction"||Object.prototype.toString.call(s)==="[object AsyncFunction]"}function Uo(s){let e={};for(let t in s)s[t]!==void 0&&(e[t]=s[t]);return e}function Ko(s,e=new WeakSet){if(s===null||typeof s!="object"||Array.isArray(s)||s instanceof Date||s instanceof RegExp||Object.getPrototypeOf(s)!==Object.prototype||e.has(s))return!1;e.add(s);for(let t in s)if(Object.prototype.hasOwnProperty.call(s,t)){let n=s[t];if(n!==null&&typeof n=="object"&&!Ko(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Mn=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Wi(s=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let o=0;o<s;o++)e+=t.charAt(Math.floor(Math.random()*n));return e}function Oi(s=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<s;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Gn=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Nn=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 o=n.map(i=>i(...t));return()=>{o.forEach(i=>i&&i())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let o=n.map(i=>i(...t()));return()=>{o.forEach(i=>i&&i())}}};var Hn=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 Vi(s,e){let t={},n=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&(e.includes(o)?n.push(o):t[o]=s[o]);return[t,n]}function zi(s){let e=3421674724,t=2216829733;for(let n=0;n<s.length;n++){let o=s.charCodeAt(n);e^=o;let i=e>>>0,r=t>>>0,a=435,c=16777216,l=i*a>>>0,d=i*c+r*a>>>0,p=r*c+(d>>>0)>>>0;e=l,t=p}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Zt=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Ho(),this._id=""}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}getId(){return this._id}setId(e){this._id=e}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]:[]}};Zt.ActionTypes={action:"action"};var M=class extends Zt{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 h(o=>o);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 Fo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},y=class s extends Fo{static create(e){return new s().setContent(e)}static forEachParent(e,t){let n=new Set,o=e;for(;o&&!n.has(o);)n.add(o),t(o),o=o.getParent()}static forEachChild(e,t){let n=new Set,o=e;for(;o&&!n.has(o);)n.add(o),t(o),o=o.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 Wn={center:"center",left:"left",right:"right"};import{animate as es}from"motion/react";var _t=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(_t||{}),$i={left:"33.33%",center:"50%",right:"66.66%"},Me=class Me{static isUnknown(e){return e===Me.Unknown}static D2PositionToCSS(e,t=!1,n=!1){let o=this.calc(e.y,e.yoffset),i=this.calc(e.x,e.xoffset),r=n?{bottom:o}:{top:o},a=t?{right:i}:{left:i};return this.wrap({...r,...a})}static calc(e,t){return!e||Me.isUnknown(e)?"auto":t===void 0||Me.isUnknown(t)?`calc(${e} + 0px)`:`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`}static toCoord2D(e){if(Ge.isCommonPositionType(e))return be.fromCommonPosition(e);if(be.isCoord2DPosition(e))return e;if(Ct.isAlignPosition(e))return be.fromAlignPosition(e);if(typeof e=="object"&&["x","y","xoffset","yoffset"].some(t=>t in e)){let t=e;return new be(t)}else throw new Error("Invalid position type")}static orUnknown(e){return Me.isUnknown(e)||e===void 0?Me.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),o=this.toCoord2D(t);return be.merge(n,o)}static serializePosition(e){let t=this.toCoord2D(e);return{x:Me.isUnknown(t.x)?0:t.x,y:Me.isUnknown(t.y)?0:t.y,xoffset:Me.isUnknown(t.xoffset)?0:t.xoffset,yoffset:Me.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(_t).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"&&("xalign"in e||"yalign"in e||"xoffset"in e||"yoffset"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof Ge||e instanceof be||e instanceof Ct}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return be.fromCommonPosition(new Ge(e));if(this.isRawCoord2DPosition(e))return new be(e);if(this.isRawAlignPosition(e))return be.fromAlignPosition(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}}};Me.Unknown=Symbol("Unknown");var C=Me,On=class On{static isCommonPositionType(e){return e instanceof On}constructor(e){this.position=e}toCSS(){return{x:$i[this.position],y:"50%",xoffset:0,yoffset:0}}};On.Positions=_t;var Ge=On,be=class s{static isCoord2DPosition(e){return e instanceof s}static fromCommonPosition(e){return new s({x:$i[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||C.isUnknown(n)?C.Unknown:`${n*100}%`;return new s({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new s({x:C.isUnknown(t.x)?e.x:t.x,y:C.isUnknown(t.y)?e.y:t.y,xoffset:C.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:C.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=C.orUnknown(e.x),this.y=C.orUnknown(e.y),this.xoffset=C.orUnknown(e.xoffset),this.yoffset=C.orUnknown(e.yoffset)):(this.x=C.orUnknown(e),this.y=C.orUnknown(t),this.xoffset=C.Unknown,this.yoffset=C.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}}},Ct=class s{static isAlignPosition(e){return e instanceof s}constructor(e,t){typeof e=="object"?(this.xalign=C.orUnknown(e.xalign),this.yalign=C.orUnknown(e.yalign),this.xoffset=C.orUnknown(e.xoffset),this.yoffset=C.orUnknown(e.yoffset)):(this.xalign=C.orUnknown(e),this.yalign=C.orUnknown(t),this.xoffset=C.Unknown,this.yoffset=C.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:C.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:C.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var N=class s{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Wo(this.mergeWithDefaultConfig(e))}copy(){return new s(D({},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)?D({},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}},Wo=class s{constructor(e){this.config=e}get(){return this.config}copy(){return new s(D({},this.config))}join(e){let t=Ui(this.config,Object.keys(e));return new s(Object.assign(t,e instanceof s?e.get():e))}extract(e){let t={},n={};for(let o of e)t[o]=this.config[o];for(let o in this.config)e.includes(o)||(n[o]=this.config[o]);return[new s(t),new s(n)]}assign(e){return new s(Object.assign({},this.config,e))}};var ts={[Wn.left]:"25.33%",[Wn.center]:"50%",[Wn.right]:"75.66%"},Oe=class Oe{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new Oe(Oe.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?C.toCoord2D(C.tryParsePosition(e||t)):C.mergePosition(C.tryParsePosition(e),C.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=Oe.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 Uo(F.constructStyle(e,this.state,t))}toStyle(e,t){return Uo(F.constructStyle(e,this.state,t))}serialize(){return Oe.TransformStateSerializer.serialize(this.state)}clone(){return new Oe(Oe.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=Oe.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};Oe.DefaultTransformState=new N({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new Ge("center"),opacity:0,alt:""}),Oe.TransformStateSerializer=new Se({position:e=>C.serializePosition(C.tryParsePosition(e))},{position:e=>C.toCoord2D(e)});var ie=Oe,oe=class oe{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},oe.defaultConfig,t||{});else{let[n,o]=[e,t||oe.defaultOptions];this.sequences.push({props:n,options:o||oe.defaultOptions}),this.config=Object.assign({},oe.defaultConfig)}}static isPosition(e){return Ge.isCommonPositionType(e)||be.isCoord2DPosition(e)||Ct.isAlignPosition(e)}static immediate(e){return new oe(e,{duration:0,ease:"linear"})}static left(e,t){return new oe({position:Ge.Positions.Left},{duration:e,ease:t})}static right(e,t){return new oe({position:Ge.Positions.Right},{duration:e,ease:t})}static center(e,t){return new oe({position:Ge.Positions.Center},{duration:e,ease:t})}static create(e){return new oe([],e)}static positionToCSS(e,t,n){return e?C.isRawPosition(e)?C.D2PositionToCSS(C.rawPositionToCoord2D(e),n,t):C.D2PositionToCSS(e.toCSS(),n,t):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?C.toCoord2D(C.tryParsePosition(e||t)):C.mergePosition(C.tryParsePosition(e),C.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...D(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:o,invertX:i}=e.getStory().getInversionConfig(),{translate:r=[]}=n||{},a=t.zoom??1,c=function(m,g,u){return typeof m>"u"?u?g(u):"":g(m)},l=r[0]||(i?"":"-")+"50%",d=r[1]||(o?"":"-")+"50%";return[`translate(${l}, ${d})`,c(t.rotation,m=>`rotate(${m}deg)`,0),c(t.scaleX,m=>`scaleX(${m*a})`,1),c(t.scaleY,m=>`scaleY(${m*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:o,invertX:i}=e.getStory().getInversionConfig(),{overwrite:r}=n||{};return{...oe.positionToCSS(t.position,o,i),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?At(t.fontColor):void 0,transform:oe.propToCSSTransform(e,t),...r?r(t):{}}}animate(e,{gameState:t,ref:n,overwrites:o}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:i,sequences:r,options:a}=this.constructAnimation({gameState:t,transformState:e,overwrites:o,current:n.current});r.length||t.logger.warn("Transform","No sequences to animate.");let c=!1,l=e.lock(),d=es(r,a),p=()=>{e.overwrite(l,i.get()).unlock(l),d.complete(),c=!0},m=new h().registerSkipController(new L(p)),g=()=>{c||e.overwrite(l,i.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,o)),m.resolve()};return d.then(g,u=>{t.logger.error("Failed to animate transform. "+(u?.toString?.()||""))}),d.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:i,sequences:r,options:a},this),m}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...oe.defaultOptions};let{duration:t,ease:n,delay:o,at:i}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(o,void 0),at:this.atToSeconds(i)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:o}){let i=t.clone(),r=i.lock(),a=this.sequences.map(({props:c,options:l})=>{let d=i.assign(r,c).toFramesDefinition(e,n);return[o,d,this.getOptions(l)]});return{finalState:i.unlock(r).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 oe(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})}constructCommit(e,t){let n={props:{},options:t};for(let o of e)n.props[o.key]=o.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 Q("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[o,i,r]=n,a=Number(r);if(isNaN(a))throw new Q("Invalid number in at definition.");let c=a/1e3;return i==="+"?`+${c}`:`-${c}`}};oe.defaultConfig={sync:!0},oe.defaultOptions={duration:0,ease:"linear"},oe.CommonImagePositionMap=ts;var F=oe;var AC={};var Vn=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 zn=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 re=class s{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),Ie(()=>{this.preventAttach()})}static proxy(e){let t=new h,n=new h,o=new s(n);return o.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[i,r]=o.catSettled();e(i,r)}),t.onSkipControllerRegister(i=>{i.onAbort(()=>{o.abort()})}),[t,o]}static any(e){if(e.length===0)throw new b("Cannot create an 'any' timeline with no awaitables.");let t=new h,n=new h,o=new s(n),i=!1;for(let r of e)o.attachChild(r),r.then(a=>{i||(i=!0,t.resolve(a))});return t.onSkipControllerRegister(r=>{r.onAbort(()=>{o.abort()})}),[t,o]}static all(e){if(e.length===0)throw new b("Cannot create an 'all' timeline with no awaitables.");let t=new h,n=new h,o=new s(n),i=new Array(e.length),r=0;for(let a=0;a<e.length;a++){let c=e[a];o.attachChild(c),c.then(l=>{i[a]=l,r++,r===e.length&&t.resolve(i)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{o.abort()})}),[t,o]}static sequence(e,t){let n=t,o=null,i=new h,r=()=>{if(o){let a;o.onSkipControllerRegister(c=>{a=c.onAbort(()=>{i.abort()})}),o.then(c=>{a?.cancel(),n=c,o=e(c),o?Ie(()=>r()):i.resolve(n)})}else i.resolve(n)};return i.registerSkipController(new L(()=>(o&&o.abort(),t))),o=e(t),o?Ie(()=>r()):Ie(()=>i.resolve(n)),i}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onSettled(e){this.isSettled()?Ie(e):(this.onResolved(e),this.onCancelled(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 b(`Attaching to this timeline violates the timeline's state.
3
+ `).trim():""}function Kn(s){return new Promise(e=>setTimeout(e,s))}var Un=class Un{constructor(e){this.abortHandler=e;this.events=new K;this.aborted=!1}abort(...e){this.aborted||(this.aborted=!0,this.abortHandler(...e),this.events.emit(Un.EventTypes["event:skipController.abort"]))}isAborted(){return this.aborted}cancel(){this.aborted=!0}onAbort(e){return this.events.on("event:skipController.abort",e)}};Un.EventTypes={"event:skipController.abort":"event:skipController.abort"};var L=Un;var Jt=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}},Nt=class{constructor(){this.locks=[]}unlock(e){return e.unlock(),this.off(e),e}register(e){let t=e||new Jt;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 Fn(s,e,t={}){return s?e:t}function Gi(s,e){if(e<=0)return s;let t=null;return function(...n){t&&clearTimeout(t),t=setTimeout(()=>{s(...n)},e)}}var In=class{constructor(){this.taskToken=null}scheduleTask(e,t){this.taskToken&&this.taskToken.cancel();let n=!1,o=setTimeout(()=>{n||e()},t);return this.taskToken={cancel:()=>{clearTimeout(o),n=!0},isCancelled:()=>n},this.taskToken}cancelTask(){return this.taskToken&&(this.taskToken.cancel(),this.taskToken=null),this}};function Ni(s,e){let t=[];for(let n=0;n<Math.max(s.length,e.length);n++)n<s.length&&t.push(s[n]),n<e.length&&t.push(e[n]);return t}async function Hi(s,e){return new Promise((t,n)=>{fetch(s,e).then(o=>o.blob()).then(o=>{let i=new FileReader;i.onload=()=>{t(i.result)},i.readAsDataURL(o)}).catch(n)})}var Yt=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 Kn(this.delay),await e()};await e()}};function Ie(s){let e,t=Promise.resolve().then(()=>{e=s()});return()=>{t.then(()=>{e&&e()})}}function Ui(s,e){let t={};for(let n in s)e.includes(n)||(t[n]=s[n]);return t}var Se=class s{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},o={...this.deserializer,...t};return new s(n,o)}};function Ki(s){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(s)}var dt=class extends h{constructor(t){super();this.tasks=[];t&&this.registerSkipController(t)}addTask(t){return t?(this.tasks.push(t),this):this}abort(){this.current&&this.current.abort(),this.tasks.forEach(([t,n])=>{n&&n.abort()}),super.abort()}resolve(){}run(){return this.current?this:(this.onTaskComplete(),this)}onTaskComplete(){if(this.tasks.length===0){super.resolve();return}let[t,n]=this.tasks.shift(),o=new h(h.nothing,n);this.current=o,this.current.then(()=>this.onTaskComplete()),t(o)}};function Fi(s){return s.constructor.name==="AsyncFunction"||Object.prototype.toString.call(s)==="[object AsyncFunction]"}function Uo(s){let e={};for(let t in s)s[t]!==void 0&&(e[t]=s[t]);return e}function Ko(s,e=new WeakSet){if(s===null||typeof s!="object"||Array.isArray(s)||s instanceof Date||s instanceof RegExp||Object.getPrototypeOf(s)!==Object.prototype||e.has(s))return!1;e.add(s);for(let t in s)if(Object.prototype.hasOwnProperty.call(s,t)){let n=s[t];if(n!==null&&typeof n=="object"&&!Ko(n,e)||typeof n=="function"||typeof n=="symbol")return!1}return!0}var Mn=class{constructor(e=""){this.prefix=e;this.counter=0}next(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}};function Wi(s=16){let e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=t.length;for(let o=0;o<s;o++)e+=t.charAt(Math.floor(Math.random()*n));return e}function Oi(s=16){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let n=0;n<s;n++)t+=e[Math.floor(Math.random()*e.length)];return t}var Gn=class{constructor(e=""){this.prefix=e;this.counter=0}generateId(){return`${this.prefix?this.prefix+"-":""}${this.counter++}`}},Nn=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 o=n.map(i=>i(...t));return()=>{o.forEach(i=>i&&i())}}rawTrigger(e,t){let n=this.hooks[e];if(!n)return()=>{};let o=n.map(i=>i(...t()));return()=>{o.forEach(i=>i&&i())}}};var Hn=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 Vi(s,e){let t={},n=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&(e.includes(o)?n.push(o):t[o]=s[o]);return[t,n]}function zi(s){let e=3421674724,t=2216829733;for(let n=0;n<s.length;n++){let o=s.charCodeAt(n);e^=o;let i=e>>>0,r=t>>>0,a=435,c=16777216,l=i*a>>>0,d=i*c+r*a>>>0,p=r*c+(d>>>0)>>>0;e=l,t=p}return("00000000"+t.toString(16)).slice(-8)+("00000000"+e.toString(16)).slice(-8)}var Zt=class{constructor(e,t,n){this.callee=e,this.type=t,this.contentNode=n,this.__stack=Ho(),this._id=""}executeAction(e,t){return{type:this.type,node:this.contentNode.getChild()}}getId(){return this._id}setId(e){this._id=e}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]:[]}};Zt.ActionTypes={action:"action"};var M=class extends Zt{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 h(o=>o);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 Fo=class{constructor(e){this.type=e,this.content=void 0}setContent(e){return this.content=e,this}getContent(){return this.content}},y=class s extends Fo{static create(e){return new s().setContent(e)}static forEachParent(e,t){let n=new Set,o=e;for(;o&&!n.has(o);)n.add(o),t(o),o=o.getParent()}static forEachChild(e,t){let n=new Set,o=e;for(;o&&!n.has(o);)n.add(o),t(o),o=o.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 Wn={center:"center",left:"left",right:"right"};import{animate as es}from"motion/react";var _t=(n=>(n.Left="left",n.Center="center",n.Right="right",n))(_t||{}),$i={left:"33.33%",center:"50%",right:"66.66%"},Me=class Me{static isUnknown(e){return e===Me.Unknown}static D2PositionToCSS(e,t=!1,n=!1){let o=this.calc(e.y,e.yoffset),i=this.calc(e.x,e.xoffset),r=n?{bottom:o}:{top:o},a=t?{right:i}:{left:i};return this.wrap({...r,...a})}static calc(e,t){return!e||Me.isUnknown(e)?"auto":t===void 0||Me.isUnknown(t)?`calc(${e} + 0px)`:`calc(${typeof e=="number"?`${e}px`:e} + ${t}px)`}static toCoord2D(e){if(Ge.isCommonPositionType(e))return be.fromCommonPosition(e);if(be.isCoord2DPosition(e))return e;if(Ct.isAlignPosition(e))return be.fromAlignPosition(e);if(typeof e=="object"&&["x","y","xoffset","yoffset"].some(t=>t in e)){let t=e;return new be(t)}else throw new Error("Invalid position type")}static orUnknown(e){return Me.isUnknown(e)||e===void 0?Me.Unknown:e}static mergePosition(e,t){let n=this.toCoord2D(e),o=this.toCoord2D(t);return be.merge(n,o)}static serializePosition(e){let t=this.toCoord2D(e);return{x:Me.isUnknown(t.x)?0:t.x,y:Me.isUnknown(t.y)?0:t.y,xoffset:Me.isUnknown(t.xoffset)?0:t.xoffset,yoffset:Me.isUnknown(t.yoffset)?0:t.yoffset}}static isRawCommonPositionType(e){return Object.values(_t).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"&&("xalign"in e||"yalign"in e||"xoffset"in e||"yoffset"in e)}static isRawPosition(e){return this.isRawCommonPositionType(e)||this.isRawCoord2DPosition(e)||this.isRawAlignPosition(e)}static isPosition(e){return e instanceof Ge||e instanceof be||e instanceof Ct}static rawPositionToCoord2D(e){if(this.isRawCommonPositionType(e))return be.fromCommonPosition(new Ge(e));if(this.isRawCoord2DPosition(e))return new be(e);if(this.isRawAlignPosition(e))return be.fromAlignPosition(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}}};Me.Unknown=Symbol("Unknown");var C=Me,On=class On{static isCommonPositionType(e){return e instanceof On}constructor(e){this.position=e}toCSS(){return{x:$i[this.position],y:"50%",xoffset:0,yoffset:0}}};On.Positions=_t;var Ge=On,be=class s{static isCoord2DPosition(e){return e instanceof s}static fromCommonPosition(e){return new s({x:$i[e.position],y:"50%"})}static fromAlignPosition(e){let t=n=>!n||C.isUnknown(n)?C.Unknown:`${n*100}%`;return new s({x:t(e.xalign),y:t(e.yalign),xoffset:e.xoffset,yoffset:e.yoffset})}static merge(e,t){return new s({x:C.isUnknown(t.x)?e.x:t.x,y:C.isUnknown(t.y)?e.y:t.y,xoffset:C.isUnknown(t.xoffset)?e.xoffset:t.xoffset,yoffset:C.isUnknown(t.yoffset)?e.yoffset:t.yoffset})}constructor(e,t){typeof e=="object"?(this.x=C.orUnknown(e.x),this.y=C.orUnknown(e.y),this.xoffset=C.orUnknown(e.xoffset),this.yoffset=C.orUnknown(e.yoffset)):(this.x=C.orUnknown(e),this.y=C.orUnknown(t),this.xoffset=C.Unknown,this.yoffset=C.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}}},Ct=class s{static isAlignPosition(e){return e instanceof s}constructor(e,t){typeof e=="object"?(this.xalign=C.orUnknown(e.xalign),this.yalign=C.orUnknown(e.yalign),this.xoffset=C.orUnknown(e.xoffset),this.yoffset=C.orUnknown(e.yoffset)):(this.xalign=C.orUnknown(e),this.yalign=C.orUnknown(t),this.xoffset=C.Unknown,this.yoffset=C.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:C.isUnknown(this.xalign)?this.xalign:`${this.xalign*100}%`,y:C.isUnknown(this.yalign)?this.yalign:`${this.yalign*100}%`,xoffset:this.xoffset,yoffset:this.yoffset}}};var N=class s{constructor(e,t){this.defaultConfig=e;this.handlers=t||{}}create(e={}){return new Wo(this.mergeWithDefaultConfig(e))}copy(){return new s(D({},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)?D({},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}},Wo=class s{constructor(e){this.config=e}get(){return this.config}copy(){return new s(D({},this.config))}join(e){let t=Ui(this.config,Object.keys(e));return new s(Object.assign(t,e instanceof s?e.get():e))}extract(e){let t={},n={};for(let o of e)t[o]=this.config[o];for(let o in this.config)e.includes(o)||(n[o]=this.config[o]);return[new s(t),new s(n)]}assign(e){return new s(Object.assign({},this.config,e))}};var ts={[Wn.left]:"25.33%",[Wn.center]:"50%",[Wn.right]:"75.66%"},Oe=class Oe{constructor(e={}){this.state={};this.locked=null;this.frozen=!1;this.state=e}static deserialize(e){return new Oe(Oe.TransformStateSerializer.deserialize(e))}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?C.toCoord2D(C.tryParsePosition(e||t)):C.mergePosition(C.tryParsePosition(e),C.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=Oe.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 Uo(F.constructStyle(e,this.state,t))}toStyle(e,t){return Uo(F.constructStyle(e,this.state,t))}serialize(){return Oe.TransformStateSerializer.serialize(this.state)}clone(){return new Oe(Oe.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=Oe.mergeState(this.state,t),this}forceOverwrite(e){return this.state=e,this}};Oe.DefaultTransformState=new N({scaleX:1,scaleY:1,zoom:1,rotation:0,position:new Ge("center"),opacity:0,alt:""}),Oe.TransformStateSerializer=new Se({position:e=>C.serializePosition(C.tryParsePosition(e))},{position:e=>C.toCoord2D(e)});var ie=Oe,oe=class oe{constructor(e,t){this.sequences=[];this.stagedChanges=[];if(Array.isArray(e))this.sequences.push(...e),this.config=Object.assign({},oe.defaultConfig,t||{});else{let[n,o]=[e,t||oe.defaultOptions];this.sequences.push({props:n,options:o||oe.defaultOptions}),this.config=Object.assign({},oe.defaultConfig)}}static isPosition(e){return Ge.isCommonPositionType(e)||be.isCoord2DPosition(e)||Ct.isAlignPosition(e)}static immediate(e){return new oe(e,{duration:0,ease:"linear"})}static left(e,t){return new oe({position:Ge.Positions.Left},{duration:e,ease:t})}static right(e,t){return new oe({position:Ge.Positions.Right},{duration:e,ease:t})}static center(e,t){return new oe({position:Ge.Positions.Center},{duration:e,ease:t})}static create(e){return new oe([],e)}static positionToCSS(e,t,n){return e?C.isRawPosition(e)?C.D2PositionToCSS(C.rawPositionToCoord2D(e),n,t):C.D2PositionToCSS(e.toCSS(),n,t):{}}static mergePosition(e,t){if(!e&&!t)throw new Error("No position found.");return!e||!t?C.toCoord2D(C.tryParsePosition(e||t)):C.mergePosition(C.tryParsePosition(e),C.tryParsePosition(t))}static mergeState(e,t){let n=this.mergePosition(e.position,t.position);return{...D(e,t),position:n}}static propToCSSTransform(e,t,n){let{invertY:o,invertX:i}=e.getStory().getInversionConfig(),{translate:r=[]}=n||{},a=t.zoom??1,c=function(m,g,u){return typeof m>"u"?typeof u<"u"?g(u):"":g(m)},l=r[0]||(i?"":"-")+"50%",d=r[1]||(o?"":"-")+"50%";return[`translate(${l}, ${d})`,c(t.rotation,m=>`rotate(${m}deg)`,0),c(t.scaleX,m=>`scaleX(${m*a})`,1),c(t.scaleY,m=>`scaleY(${m*a})`,1)].filter(Boolean).join(" ")}static constructStyle(e,t,n){let{invertY:o,invertX:i}=e.getStory().getInversionConfig(),{overwrite:r}=n||{};return{...oe.positionToCSS(t.position,o,i),opacity:t.opacity,color:"fontColor"in t&&t.fontColor?At(t.fontColor):void 0,transform:oe.propToCSSTransform(e,t),...r?r(t):{}}}animate(e,{gameState:t,ref:n,overwrites:o}){if(!n.current)throw new Error("No ref found when animating.");this.commit();let{finalState:i,sequences:r,options:a}=this.constructAnimation({gameState:t,transformState:e,overwrites:o,current:n.current});r.length||t.logger.warn("Transform","No sequences to animate.");let c=!1,l=e.lock(),d=es(r,a),p=()=>{e.overwrite(l,i.get()).unlock(l),d.complete(),c=!0},m=new h().registerSkipController(new L(p)),g=()=>{c||e.overwrite(l,i.get()).unlock(l),c=!0,t.logger.debug("Transform","Transform Completed",e.toStyle(t,o)),m.resolve()};return d.then(g,u=>{t.logger.error("Failed to animate transform. "+(u?.toString?.()||""))}),d.play(),t.logger.debug("Transform","Ready to animate transform.",{finalState:i,sequences:r,options:a},this),m}repeat(e){let t=this.copy();return t.config.repeat||(t.config.repeat=1),t.config.repeat*=e,t}getOptions(e){if(!e)return{...oe.defaultOptions};let{duration:t,ease:n,delay:o,at:i}=e;return{duration:this.toSeconds(t,void 0),ease:n,delay:this.toSeconds(o,void 0),at:this.atToSeconds(i)}}constructAnimation({gameState:e,transformState:t,overwrites:n={},current:o}){let i=t.clone(),r=i.lock(),a=this.sequences.map(({props:c,options:l})=>{let d=i.assign(r,c).toFramesDefinition(e,n);return[o,d,this.getOptions(l)]});return{finalState:i.unlock(r).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 oe(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})}constructCommit(e,t){let n={props:{},options:t};for(let o of e)n.props[o.key]=o.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 Q("Invalid at definition. At definition must be a number or a string in the format of `+n` or `-n`.");let[o,i,r]=n,a=Number(r);if(isNaN(a))throw new Q("Invalid number in at definition.");let c=a/1e3;return i==="+"?`+${c}`:`-${c}`}};oe.defaultConfig={sync:!0},oe.defaultOptions={duration:0,ease:"linear"},oe.CommonImagePositionMap=ts;var F=oe;var AC={};var Vn=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 zn=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 re=class s{constructor(e,t){this.awaitable=e;this.guard=t;this.children=[];this._onResolved=[];this._onCancelled=[];this._onTimelineRegistered=[];this._ableToAttach=!0;this._status="pending";e.onSettled(()=>{this.resolveStatus()}),Ie(()=>{this.preventAttach()})}static proxy(e){let t=new h,n=new h,o=new s(n);return o.onTimelineRegistered(()=>{n.resolve()}).onSettled(()=>{let[i,r]=o.catSettled();e(i,r)}),t.onSkipControllerRegister(i=>{i.onAbort(()=>{o.abort()})}),[t,o]}static any(e){if(e.length===0)throw new b("Cannot create an 'any' timeline with no awaitables.");let t=new h,n=new h,o=new s(n),i=!1;for(let r of e)o.attachChild(r),r.then(a=>{i||(i=!0,t.resolve(a))});return t.onSkipControllerRegister(r=>{r.onAbort(()=>{o.abort()})}),[t,o]}static all(e){if(e.length===0)throw new b("Cannot create an 'all' timeline with no awaitables.");let t=new h,n=new h,o=new s(n),i=new Array(e.length),r=0;for(let a=0;a<e.length;a++){let c=e[a];o.attachChild(c),c.then(l=>{i[a]=l,r++,r===e.length&&t.resolve(i)})}return t.onSkipControllerRegister(a=>{a.onAbort(()=>{o.abort()})}),[t,o]}static sequence(e,t){let n=t,o=null,i=new h,r=()=>{if(o){let a;o.onSkipControllerRegister(c=>{a=c.onAbort(()=>{i.abort()})}),o.then(c=>{a?.cancel(),n=c,o=e(c),o?Ie(()=>r()):i.resolve(n)})}else i.resolve(n)};return i.registerSkipController(new L(()=>(o&&o.abort(),t))),o=e(t),o?Ie(()=>r()):Ie(()=>i.resolve(n)),i}get status(){return this._status}isSettled(){return this._status!=="pending"}isResolved(){return this._status==="resolved"}isCancelled(){return this._status==="cancelled"}onResolved(e){this._onResolved.push(e)}onCancelled(e){this._onCancelled.push(e)}onSettled(e){this.isSettled()?Ie(e):(this.onResolved(e),this.onCancelled(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 b(`Attaching to this timeline violates the timeline's state.
4
4
  Timeline attaching is only allowed synchronously after the timeline is created.
5
5
  Current _ableToAttach: `+this._ableToAttach);let t=h.isAwaitable(e)?new s(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(){this.awaitable.solved&&this.children.every(e=>e.isSettled())?this.setStatus("resolved",this.emitEvents.bind(this)):this.awaitable.skipController?.isAborted()&&this.setStatus("cancelled",this.emitEvents.bind(this))}emitEvents(){this.isResolved()?this._onResolved.forEach(e=>e()):this.isCancelled()&&this._onCancelled.forEach(e=>e()),this._onResolved=[],this._onCancelled=[]}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())}},$n=class{constructor(e){this.guard=e;this.timelines=[]}attachTimeline(e){this.cleanupSettled();let t=e instanceof re?e:new re(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 en=class en extends M{static executeActionsAsync(e,t){return e.game.getLiveGame().requestAsyncStackModel([{type:t.type,node:t.contentNode}]).execute()}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,[o]=n.getContent();if(this.type===We.do)return[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:o[0].contentNode}];if(this.type===We.doAsync){let i=en.executeActionsAsync(e,o[0]);return e.timelines.attachTimeline(i),super.executeAction(e,t)}else if(this.type===We.any){if(o.length===0)return{type:this.type,node:this.contentNode.getChild()};let i=this.checkActionChain(o).map(r=>e.game.getLiveGame().requestAsyncStackModel([{type:r.type,node:r.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"any",stackModels:i}}}else if(this.type===We.all){if(o.length===0)return{type:this.type,node:this.contentNode.getChild()};let i=this.checkActionChain(o).map(r=>e.game.getLiveGame().requestAsyncStackModel([{type:r.type,node:r.contentNode}]));return{type:this.type,node:this.contentNode.getChild(),wait:{type:"all",stackModels:i}}}else if(this.type===We.allAsync){if(o.length===0)return{type:this.type,node:this.contentNode.getChild()};let i=this.checkActionChain(o).map(r=>e.game.getLiveGame().requestAsyncStackModel([{type:r.type,node:r.contentNode}]));return e.timelines.attachTimeline(h.all(...i.map(r=>r.execute()))),super.executeAction(e,t)}else if(this.type===We.repeat){let[i,r]=this.contentNode.getContent();if(r<=0)return super.executeAction(e,t);let a=re.sequence(c=>{if(c>=r)return null;let l=en.executeActionsAsync(e,i[0]);return e.timelines.attachTimeline(l),h.forward(l,c+1)},0);return e.logger.debug("ControlAction","repeat",i,r),h.forward(a,{type:this.type,node:this.contentNode.getChild()})}else if(this.type===We.sleep){let[,i]=this.contentNode.getContent(),r;typeof i=="number"?r=h.delay(i):h.isAwaitable(i)?r=i:r=h.fromPromise(i);let a=new h,c=new re(r);return e.timelines.attachTimeline(c),r.then(()=>{a.resolve({type:this.type,node:this.contentNode.getChild()})}),a.onSkipControllerRegister(l=>{l.onAbort(()=>{c.abort()})}),a}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)];let n=this.contentNode.getContent()[0],o=super.getFutureActions(e,t);return[...n,...o]}stringify(e,t,n){let o=this.contentNode,[i]=o.getContent();return super.stringifyWithContent("Control",i.map(r=>r.stringify(e,t,n)).join(";"))}};en.ActionTypes=We;var ee=en;var ji=Symbol("_Chained"),qi;qi=ji;var Oo=class Oo{constructor(e){this[qi]=!0;this.__actions=[];this.__self=e}static isChained(e){return e&&e[ji]}static toActions(e){return e.flat(2).map(t=>Oo.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()}},de=Oo,Ht=class extends Vn{chain(e){let t=de.isChained(this)?this:this.proxy(this,new de(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(o,i){if(i in t)return t[i];let r=o[i];return typeof r=="function"?r.bind(n):r},set:function(o,i,r){return o[i]=r,!0}});return n}combineActions(e,t){let n=t(this.chain().newChain()),o=new ee(e.chain(),ee.ActionTypes.do,new y().setContent([this.construct(de.toActions([n]))]));return this.chain(o)}};var j=class extends Ht{constructor(){super()}toData(){return null}fromChained(e){return e.getActions()}};var Te=class s{static from(e){return s.isPauseConstructor(e)?new s:e}static wait(e){return new s({duration:e})}static isPause(e){return this.isPauseConstructor(e)||e instanceof s}static isPauseConstructor(e){return e===s}constructor(e={}){this.config=e}};var ce=class ce{static isWord(e){return e instanceof ce}static color(e,t){return ce.isWord(e)?e.copy().assign({color:t}):new ce(e,{color:t})}static bold(e){return ce.isWord(e)?e.copy().assign({bold:!0}):new ce(e,{bold:!0})}static italic(e){return ce.isWord(e)?e.copy().assign({italic:!0}):new ce(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=D(ce.defaultConfig,t)}evaluate(e){if(Te.isPause(this.text))return[this];if(typeof this.text=="function"){let t=this.text(e);return Array.isArray(t)?t.map(n=>ce.isWord(n)?n.inherit(this.config).evaluate(e):new ce(n,this.config)).flat():ce.isWord(t)?t.inherit(this.config).evaluate(e):[new ce(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=D(this.config,e),this}copy(){return new ce(this.text,this.config)}isPause(){return Te.isPause(this.text)}toString(){return typeof this.text=="string"?this.text:""}};ce.defaultConfig={},ce.defaultColor="#000";var H=ce;var ke=class extends M{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===mt.play){let[o]=this.contentNode.getContent(),i=this.callee.toData(),r=h.forward(e.audioManager.play(this.callee,o),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(r),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[i]),r}else if(this.type===mt.stop){let[o]=this.contentNode.getContent(),i=this.callee.toData(),r=h.forward(e.audioManager.stop(this.callee,o.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(r),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[i]),r}else if(this.type===mt.setVolume){let[o,i]=this.contentNode.getContent(),r=this.callee.toData(),a=h.forward(e.audioManager.setVolume(this.callee,o,i),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(a),e.actionHistory.push(n,c=>{c&&this.callee.fromData(c)},[r]),a}else if(this.type===mt.setRate){let[o]=this.contentNode.getContent(),i=this.callee.toData(),r=h.forward(e.audioManager.setRate(this.callee,o),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(r),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[i]),r}else if(this.type===mt.pause){let[o]=this.contentNode.getContent(),i=this.callee.toData(),r=h.forward(e.audioManager.pause(this.callee,o.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(r),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[i]),r}else if(this.type===mt.resume){let[o]=this.contentNode.getContent(),i=this.callee.toData(),r=h.forward(e.audioManager.resume(this.callee,o.duration),{type:this.type,node:this.contentNode?.getChild()});return e.timelines.attachTimeline(r),e.actionHistory.push(n,a=>{a&&this.callee.fromData(a)},[i]),r}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("SoundAction")}};ke.ActionTypes=mt;var tn=(n=>(n.Voice="voice",n.Bgm="bgm",n.Sound="sound",n))(tn||{}),J=class J extends j{static toSound(e){return e==null?null:typeof e=="string"?new J({src:e}):e}static isSound(e){return e instanceof J}static voice(e){let t=typeof e=="string"?{src:e}:e;return new J({...t,type:"voice"})}static bgm(e){let t=typeof e=="string"?{src:e}:e;return new J({...t,type:"bgm"})}static sound(e){let t=typeof e=="string"?{src:e}:e;return new J({...t,type:"sound"})}constructor(e={}){super();let t=typeof e=="string"?{src:e}:e,n=J.DefaultUserConfig.create(t),[o]=n.extract(J.DefaultConfig.keys());this.config=o.get(),this.state=this.getInitialState(n),this.userConfig=n}play(e){if(this.config.type==="bgm")throw new Ae(`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(ke.ActionTypes.play,[{end:this.state.volume,duration:e||0}])}stop(e){return this.pushAction(ke.ActionTypes.stop,[{end:0,duration:e||0}])}setVolume(e,t){return this.pushAction(ke.ActionTypes.setVolume,[e,t||0])}setRate(e){return this.pushAction(ke.ActionTypes.setRate,[e])}pause(e){return this.pushAction(ke.ActionTypes.pause,[{end:0,duration:e||0}])}resume(e){return this.pushAction(ke.ActionTypes.resume,[{end:this.state.volume,duration:e||0}])}getSrc(){return this.config.src}toData(){return{state:J.StateSerializer.serialize(this.state)}}fromData(e){return this.state=J.StateSerializer.deserialize(e.state),this}copy(){return new J(this.userConfig.get())}reset(){return this.state=this.getInitialState(this.userConfig),this}getInitialState(e){return J.DefaultState.create({...e.get()}).get()}pushAction(e,t){return this.chain(new ke(this.chain(),e,new y().setContent(t)))}};J.noSound="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgA",J.DefaultUserConfig=new N({src:J.noSound,loop:!1,volume:1,streaming:!1,rate:1,seek:0,type:"sound"}),J.DefaultConfig=new N({src:J.noSound,loop:!1,streaming:!1,seek:0,type:"sound"}),J.DefaultState=new N({volume:1,rate:1,paused:!1}),J.StateSerializer=new Se;var ve=J;var Ce=class Ce{static isSentence(e){return e instanceof Ce}static toSentence(e){return Ce.isSentence(e)?e:new Ce(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 H.isWord(e)?e:new H(e)}static formatStaticWord(e,t){return Array.isArray(e)?e.map(n=>this.formatStaticWord(n,t)).flat(2):[H.isWord(e)?e:new H(e,t)]}static isSentencePrompt(e){return Array.isArray(e)?e.every(Ce.isSingleWord):Ce.isSingleWord(e)}static isSingleWord(e){return typeof e=="string"||H.isWord(e)||Te.isPause(e)||typeof e=="function"}constructor(e,t={}){this.text=Ce.format(e),this.config=D(Ce.defaultConfig,{...t,voice:ve.toSound(t.voice)}),this.state=Mi(Ce.defaultState)}toData(){return null}fromData(e){return this.state=D(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 o=this.text[n].evaluate(e);t.push(...Ce.formatStaticWord(o))}return t}copy(){return new Ce([...this.text],this.config)}};Ce.defaultConfig={pause:!0,voice:null,character:null,voiceId:null},Ce.defaultState={};var te=Ce;var Bn=class Bn extends M{static getVoice(e,t){let n=e.getLastScene();if(!n)throw new Error("No scene found when trying to play voice");let{voiceId:o,voice:i}=t.config;return!o&&!i?null:ve.toSound(n.getVoice(o)||i)}executeAction(e,t){if(this.type===Rn.say){let n=new h(d=>d).registerSkipController(new L(()=>{c.cancel()})),o=new re(n),i=this.contentNode.getContent(),r=Bn.getVoice(e,i);if(r){let d=e.audioManager.play(r);o.attachChild(d)}let a=e.idManager.generateId(),c=e.createDialog(a,i,()=>{if(r){let d=e.audioManager.stop(r);e.timelines.attachTimeline(d)}e.gameHistory.resolvePending(l),n.resolve({type:this.type,node:this.contentNode.getChild()})});e.getLiveGame().setLastDialog(c.text,this.callee.state.name),e.timelines.attachTimeline(o);let{id:l}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:o},()=>{if(r&&e.audioManager.isPlaying(r)){let d=e.audioManager.stop(r);o.attachChild(d)}c.cancel()});return e.gameHistory.push({token:l,action:this,element:{type:"say",text:c.text,voice:r?r.getSrc():null,character:this.callee.state.name},isPending:!0}),n}else if(this.type===Rn.setName){let n=this.callee.state.name;return this.callee.state.name=this.contentNode.getContent()[0],e.actionHistory.push({action:this,stackModel:t.stackModel},o=>{this.callee.state.name=o},[n]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("CharacterAction")}};Bn.ActionTypes=Rn;var tt=Bn;var nn=class nn extends j{constructor(e,t={}){super(),this.config=D(nn.defaultConfig,t),this.state={name:e||""};let n=this,o=function(i,r,...a){return n.call(i,r,...a)};return new Proxy(o,{get(i,r){return n[r]},set(i,r,a){return n[r]=a,!0},has(i,r){return r in n}})}say(e,t,...n){if(Array.isArray(e)&&e.every(c=>typeof c=="string")&&[t,...n].length>0&&[t,...n].every(c=>te.isSingleWord(c))){let c=e,l=te.format([t,...n]),d=new te(Ni(c,l),{character:this}),p=new tt(this.chain(),tt.ActionTypes.say,new y().setContent(d));return this.chain(p)}let o=t||{},i=e,r=Array.isArray(i)?new te(i,{...o,character:this}):(te.isSentence(i)?i:new te(i,{...o,character:this})).copy();r.setCharacter(this);let a=new tt(this.chain(),tt.ActionTypes.say,new y().setContent(r));return this.chain(a)}setName(e){let t=new tt(this.chain(),tt.ActionTypes.setName,new y().setContent([e]));return this.chain(t)}apply(e,t,...n){return this.say.apply(this,[e,t,...n])}call(e,t,...n){return Array.isArray(e)&&"raw"in e?t&&te.isSingleWord(t)?this.say(e,t,...n):this.say(e):typeof e=="string"?this.say(e,t):te.isSentence(e)?this.say(e):this.say(e,t)}};nn.defaultCharacterColor="#000",nn.defaultConfig={};var jn=nn,ft=new jn(null);var je=class s extends j{constructor(t={}){super();this.config=t}static do(t){return new s().do(t)}static doAsync(t){return new s().doAsync(t)}static any(t){return new s().any(t)}static all(t){return new s().all(t)}static allAsync(t){return new s().allAsync(t)}static repeat(t,n){return new s().repeat(t,n)}static sleep(t){return new s().sleep(t)}do(t){return this.push(ee.ActionTypes.do,t)}doAsync(t){return this.push(ee.ActionTypes.doAsync,t)}any(t){return this.pushUnchained(ee.ActionTypes.any,t)}all(t){return this.pushUnchained(ee.ActionTypes.all,t)}allAsync(t){return this.pushUnchained(ee.ActionTypes.allAsync,t)}repeat(t,n){return this.push(ee.ActionTypes.repeat,n,t)}sleep(t){return this.push(ee.ActionTypes.sleep,[],t)}push(t,n,...o){let i=this.narrativeToActions(n),r=new ee(this.chain(),t,new y().setContent([this.construct(i),...o]));return this.chain(r)}pushUnchained(t,n,...o){let i=this.narrativeToActions(n),r=new ee(this.chain(),t,new y().setContent([i,...o]));return this.chain(r)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?ft.say(n).getActions():de.toActions([n]))}};var le=class extends M{executeAction(e,t){if(this.type===ae.applyTransform){let[n]=this.contentNode.getContent(),o=this.callee;return this.applyTransform(e,o,n,t)}else if(this.type===ae.applyTransition){let[n,o]=this.contentNode.getContent(),i=this.callee,r=o?o(n):n;return this.applyTransition(e,i,r,t)}else if(this.type===ae.init){let[n,o,i]=this.contentNode.getContent(),r=this.callee;return this.initDisplayable(e,n,r,o||null,i,t)}throw this.unknownTypeError()}applyTransform(e,t,n,o,i){let r=new h().registerSkipController(new L(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,o)))),a=e.getExposedStateForce(t),c=t.transformState.clone(),l=a.applyTransform(n,()=>{i?.(),r.resolve(super.executeAction(e,o))}),d=e.timelines.attachTimeline(r).attachChild(l);return e.actionHistory.push({action:this,stackModel:o.stackModel,timeline:d},p=>{r.isSettled()||r.abort(),l.abort(),t.transformState.forceOverwrite(p.state)},[c]),r}applyTransition(e,t,n,o,i){let r=new h().registerSkipController(new L(()=>(e.logger.info("Displayable Transition","Skipped"),super.executeAction(e,o)))),c=e.getExposedStateForce(t).applyTransition(n,()=>{i?.(),r.resolve(super.executeAction(e,o))}),l=e.timelines.attachTimeline(r).attachChild(c);return e.actionHistory.push({action:this,stackModel:o.stackModel,timeline:l},()=>{r.isSettled()||r.abort(),c.abort()}),r}initDisplayable(e,t,n,o,i=!0,r){if(i!==!1){let l=e.findElementByDisplayable(this.callee,o);l&&e.disposeDisplayable(n,l.scene,o),e.createDisplayable(n,t,o)}e.flush();let a=new h().registerSkipController(new L(()=>super.executeAction(e,r)));e.getExposedStateAsync(n,l=>{l.initDisplayable(()=>{a.resolve(super.executeAction(e,r))})});let c=e.timelines.attachTimeline(a);return e.actionHistory.push({action:this,stackModel:r.stackModel,timeline:c},()=>{i!==!1&&e.findElementByDisplayable(n,o)&&e.disposeDisplayable(n,t,o)}),a}stringify(e,t,n){return super.stringifyWithName("DisplayableAction")}};le.ActionTypes=ae;var xt=class xt{constructor(){this.src=[];this.future=[]}static catSrc(e){let t=new Set,n=new Set,o=new Set;return e.forEach(({type:i,src:r})=>{i===xt.SrcTypes.image?t.add(r):i===xt.SrcTypes.video?n.add(r):o.add(r)}),{image:Array.from(t),video:Array.from(n),audio:Array.from(o)}}static getSrc(e){return typeof e=="string"?e:e instanceof I?I.getSrcURL(e):e.type==="image"?I.getSrcURL(e.src):e.type==="video"?e.src:e.type==="audio"?e.src.getSrc():""}static getPreloadableSrc(e,t){if(t.is(se,_.jumpTo)){let n=t.contentNode.getContent()[0],i=e.getScene(n,!0).state.backgroundImage;if(S.isImageURL(i.config.src))return{type:"image",src:i.config.src,activeType:"once"}}else if(t instanceof V){let n=t;if(t.is(V,we.setSrc)){let o=t.contentNode.getContent()[0];if(S.isImageSrc(o))return{type:"image",src:S.srcToURL(o),activeType:"scene"}}else{if(t.type===we.initWearable)return{type:"image",src:t.contentNode.getContent()[0],activeType:"scene"};if(t.type===we.setAppearance){let o=t.contentNode.getContent()[0];if(!n.callee.config.src||typeof n.callee.config.src?.resolve!="function")throw n.callee._invalidSrcHandlerError();if(I.isTagSrc(n.callee)&&o.length===n.callee.config.src.groups.length)return{type:"image",src:I.getSrcFromTags(o,n.callee.config.src.resolve),activeType:"scene"}}}}return null}register(e,t){if(Array.isArray(e))e.forEach(n=>this.register(n));else if(e instanceof ve){if(this.isSrcRegistered(e.getSrc()))return this;this.src.push({type:"audio",src:e})}else if(e instanceof I||S.isStaticImageData(e)){if(e instanceof I){if(!S.isImageURL(e.state.currentSrc))return this;if(this.isSrcRegistered(I.getSrcURL(e)))return this}else if(this.isSrcRegistered(S.srcToURL(e.src)))return this;this.src.push({type:"image",src:S.isStaticImageData(e)?S.srcToURL(e):e.state.currentSrc})}else if(typeof e=="object"){if(this.isSrcRegistered(e.src||""))return this;this.src.push(e)}else if(e==="audio"){if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t instanceof ve?t:new ve({src:t})})}else{if(this.isSrcRegistered(t||""))return this;this.src.push({type:e,src:t})}return this}registerRawSrc(e){return this.isSrcRegistered(e)?this:(this.src.push({type:"image",src:e}),this)}isSrcRegistered(e){if(!e)return!1;let t=e instanceof ve?e.getSrc():e;return this.src.some(n=>n.type===xt.SrcTypes.audio?t===n.src.getSrc():n.type===xt.SrcTypes.image?t===I.getSrcURL(n.src):t===n.src)}getSrc(){return[...this.src]}getSrcByType(e){return this.src.filter(t=>t.type===e)}registerFuture(e){return this.future.includes(e)||this.hasFuture(e)?this:(this.future.push(e),this)}hasFuture(e){return this.future.includes(e)}getFutureSrc(){return this.future.map(e=>e.getSrc()).flat(2)}};xt.SrcTypes={image:"image",video:"video",audio:"audio"};var fe=xt;var qe=class extends j{constructor(){super(...arguments);this.srcManager=new fe}pos(t,n,o){return this.transform(new F({position:t},{duration:n,ease:o}))}zoom(t,n,o){return this.transform(new F({zoom:t},{duration:n,ease:o}))}scaleX(t,n,o){return this.transform(new F({scaleX:t},{duration:n,ease:o}))}scaleY(t,n,o){return this.transform(new F({scaleY:t},{duration:n,ease:o}))}scale(t,n,o,i){return this.transform(new F({scaleX:t,scaleY:n},{duration:o,ease:i}))}scaleXY(t,n,o,i){return this.scale(t,n,o,i)}rotate(t,n,o){return this.transform(new F({rotation:t},{duration:n,ease:o}))}opacity(t,n,o){return this.transform(new F({opacity:t},{duration:n,ease:o}))}transform(t){let n=this.chain(),o=new le(n,ae.applyTransform,new y().setContent([t.copy()]));return n.chain(o)}show(t){let n=this.chain(),o=t instanceof F?t.copy():new F({opacity:1},t),i=new le(n,ae.applyTransform,new y().setContent([o]));return n.chain(i)}hide(t){let n=this.chain(),o=t instanceof F?t.copy():new F({opacity:0},t),i=new le(n,ae.applyTransform,new y().setContent([o]));return n.chain(i)}};var W=class W extends qe{static getInitialSrc(e){if(this.isTagDefinition(e.src))return[...e.src.defaults];let t=e.src;return S.isStaticImageData(t)?S.srcToURL(t):S.isColor(t)?t:S.isImageSrc(t)?S.srcToURL(t):W.DefaultImagePlaceholder}static isTagSrc(e){return!!e.config.src}static isTagDefinition(e){return typeof e=="object"&&e!==null&&!S.isImageSrc(e)&&!S.isColor(e)&&"defaults"in e}static isStaticSrc(e){let t=e.userConfig.get().src;return!this.isTagSrc(e)&&(S.isImageSrc(t)||S.isColor(t))}static getSrcURL(e){return typeof e=="string"?e:W.isTagSrc(e)?W.getSrcFromTags(e.state.currentSrc,e.config.src.resolve):W.isStaticSrc(e)?S.isStaticImageData(e.state.currentSrc)?S.srcToURL(e.state.currentSrc):S.isColor(e.state.currentSrc)?null:e.state.currentSrc:null}static getSrcFromTags(e,t){return t(...e)}static fromSrc(e){return new W({src:e})}constructor(e={}){super();let t=W.DefaultUserConfig.create(e),n=this.createImageConfig(t);this.userConfig=t,this.config=n.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(t),this.checkConfig().registerSrc()}char(e,t){return this.combineActions(new je,n=>{if(S.isImageSrc(e)||S.isColor(e)){if(S.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 o=new V(n,V.ActionTypes.setAppearance,new y().setContent([e,t?.copy()]));return n.chain(o).chain(this._flush())}})}darken(e,t,n){return this.combineActions(new je,o=>o.chain(this._setDarkness(o,e,t,n)))}addWearable(e){let t=Array.isArray(e)?e:[e];for(let n of t){if(n===this)throw new Q("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:W.StateSerializer.serialize(this.state),transformState:ie.TransformStateSerializer.serialize(this.transformState.get())}}fromData(e){return this.state=W.StateSerializer.deserialize(e.state),this.transformState=ie.deserialize(e.transformState),this}_applyTransition(e,t){return new le(this.chain(),ae.applyTransition,new y().setContent([e,t]))}_init(e,t){return new le(this.chain(),ae.init,new y().setContent([e,t||this.config.layer||null]))}_initWearable(e){return new V(this.chain(),V.ActionTypes.initWearable,new y().setContent([e]))}_flush(){return new V(this.chain(),V.ActionTypes.flush,new y)}reset(){return this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig),this}resolveTags(e,t){if(!W.isTagSrc(this))throw new Error(`Tag not defined
@@ -42,12 +42,12 @@ Returned value ${i} violates the above rules`)}t[o]=i}}),t}deserializeServices(t
42
42
  Use video.show() to add the video to the game`);let o=this.callee,i=new h,r=e.getExposedStateAsync(o,async a=>{e.logger.debug("Video Component state exposed",a),await t(a),i.resolve(super.executeAction(e,n))});return i.registerSkipController(new L(r.cancel)),i}changeState(e,t,n){return this.changeStateBase(e,t,n)}changeStateAsync(e,t,n){return this.changeStateBase(e,t,n)}stringify(e,t,n){return super.stringifyWithName("VideoAction")}};Xe.ActionTypes=Gt;var to=Xe;var Vt=class Vt extends j{constructor(e){super();let t=Vt.DefaultVideoConfig.create(e);if(this.config=t.get(),this.state=this.getInitialState(),!this.config.src)throw new Q("Video must have a src")}show(){return this.chain(this.createAction(Gt.show,[]))}hide(){return this.chain(this.createAction(Gt.hide,[]))}play(){return this.chain(this.createAction(Gt.play,[]))}toData(){return{state:{display:this.state.display}}}fromData(e){let{state:t}=e;return this.state={display:t.display},this}reset(){return this.state=this.getInitialState(),this}getInitialState(){return Vt.DefaultVideoState.create().get()}createAction(e,t){return new to(this.chain(),e,y.create(t))}};Vt.DefaultVideoConfig=new N({src:"",muted:!1}),Vt.DefaultVideoState=new N({display:!1});var Qo=Vt;import*as Qi from"howler";var no=class{constructor(e,t){this.game=e,this.prefix=t}log(e,...t){this.isEnabled("log")&&console.log(...this.colorLog("gray",e,...t))}info(e,...t){this.isEnabled("info")&&console.info(...this._log(e,...t))}warn(e,...t){this.isEnabled("warn")&&console.warn(...this._log(e,...t))}error(e,...t){this.isEnabled("error")&&console.error(...this._log(e,...t))}debug(e,...t){this.isEnabled("debug")&&console.debug(...this.colorLog("gray",e,...t))}trace(e,...t){this.isEnabled("trace")&&console.trace(this._log(e,...t))}weakWarn(e,...t){this.isEnabled("warn")&&console.log(...this.colorLog("yellow",e,...t))}weakError(e,...t){this.isEnabled("error")&&console.log(...this.colorLog("red",e,...t))}verbose(e,...t){this.isEnabled("verbose")&&console.log(...this.colorLog("gray",e,...t))}group(e,t=!1){let n=this._log(e).join(" ");return this.isEnabled("info")&&(t?console.groupCollapsed(n):console.group(n)),{end:()=>{this.isEnabled("info")&&console.groupEnd()}}}isEnabled(e){return typeof this.game.config.app.logger=="boolean"?this.game.config.app.logger:this.game.config.app.logger[e]}_log(e,...t){return t.length===0?[this.prefix||"",e]:[`${this.prefix||""} [${e}]`,...t]}colorLog(e,t,...n){if(n.length===0)return[`%c${this.prefix||""} ${t}`,`color: ${e}`];let o=[],i=[],r=[];return this.prefix?(o.push(`%c${this.prefix} [${t}]`),i.push(`color: ${e}`)):(o.push(`%c[${t}]`),i.push(`color: ${e}`)),n.forEach(a=>{typeof a=="string"?(o.push(`%c${a}`),i.push(`color: ${e}`)):(o.push("%O"),r.push(a),i.push(""))}),[o.join(" ")].concat(i,r)}};import*as Xo from"howler";var oo=class{constructor(e){this.gameState=e;this.state=new Map;this.tasks=new Map;this.groups=new Map;Object.values(tn).forEach(t=>{this.groups.set(t,{volume:1,sounds:new Set})}),this.setupGroupVolume()}play(e,t={end:1,duration:0}){this.state.has(e)&&this.abortTask(this.getState(e).group);let{group:n,token:o,onPlayTask:i,onEndTask:r}=this.initSound(e),a=this.groups.get(e.config.type)?.volume??1,c=t.end*a;return this.state.set(e,{group:n,token:o,originalVolume:t.end}),this.pushTask(n,new dt().addTask(i).addTask(this.fadeTo(n,o,{...t,start:0,end:c})).addTask(this.createTask(l=>{e.state.volume=t.end,e.state.paused=!1,l()})).addTask(r).run())}stop(e,t=0){let n=this.getState(e);return this.abortTask(n.group),t===0?(n.group.stop(n.token),h.resolve(void 0)):this.pushTask(n.group,new dt().addTask(this.fadeTo(n.group,n.token,{start:e.state.volume,end:0,duration:t})).addTask(this.createTask(o=>{n.group.volume(e.state.volume,n.token),o()})).addTask(this.stopSound(n.group,n.token)).run())}setVolume(e,t,n=0){let o=this.getState(e);this.abortTask(o.group),o.originalVolume=t;let i=this.groups.get(e.config.type)?.volume??1,r=t*i;return n===0?(o.group.volume(r,o.token),h.resolve(void 0)):this.pushTask(o.group,new dt().addTask(this.fadeTo(o.group,o.token,{start:e.state.volume,end:r,duration:n})).addTask(this.createTask(a=>{e.state.volume=t,a()})).run())}pause(e,t=0){let n=this.getState(e);return this.abortTask(n.group),t===0?(n.group.pause(n.token),h.resolve(void 0)):this.pushTask(n.group,new dt().addTask(this.fadeTo(n.group,n.token,{start:e.state.volume,end:0,duration:t})).addTask(this.pauseSound(n.group,n.token)).addTask(this.createTask(o=>{this.applyEffectiveVolume(e),e.state.paused=!0,o()})).run())}resume(e,t=0){let n=this.getState(e);if(this.abortTask(n.group),t===0)return n.group.play(n.token),h.resolve(void 0);let o=this.groups.get(e.config.type)?.volume??1,i=n.originalVolume*o;return this.pushTask(n.group,new dt().addTask(this.fadeTo(n.group,n.token,{start:0,end:i,duration:t})).addTask(this.resumeSound(n.group,n.token)).addTask(this.createTask(r=>{e.state.paused=!1,r()})).run())}setRate(e,t){let n=this.getState(e);return this.abortTask(n.group),n.group.rate(t,n.token),e.state.rate=t,h.resolve(void 0)}getPosition(e){let t=this.getState(e);return t.group.seek(t.token)}isPlaying(e){if(!this.isManaged(e))return!1;let t=this.getState(e);return t.group.playing(t.token)}toData(){return{sounds:[...this.state.entries()].map(([e,t])=>[e.getId(),{isPlaying:t.group.playing(t.token),position:t.group.seek(t.token)}]),groups:[...this.groups.entries()].map(([e,t])=>[e,t.volume])}}fromData(e,t){return e.groups?.forEach(([n,o])=>{let i=this.groups.get(n);i&&(i.volume=o,i.sounds.forEach(r=>{this.applyEffectiveVolume(r)}))}),e.sounds.forEach(([n,o])=>{let i=t.get(n);if(!i)throw new b(`Sound not found (id: "${n}")
43
43
  NarraLeaf cannot find the element with the id from the saved game`);this.soundFromData(i,o)}),this}soundFromData(e,t){let n=this.getState(e);n.group.playing(n.token)&&n.group.stop(n.token);let o=this.initSound(e);this.state.set(e,o),o.group.seek(t.position,o.token),e.state.paused?o.group.pause(o.token):t.isPlaying||o.group.stop(o.token)}isManaged(e){return this.state.has(e)}reset(){this.state.forEach(e=>{e.group.stop(e.token)}),this.state.clear(),this.tasks.forEach(e=>{e.awaitable.abort()}),this.tasks.clear(),this.groups.forEach(e=>{e.volume=1,e.sounds.clear()}),this.setupGroupVolume()}setGroupVolume(e,t){let n=this.groups.get(e);if(!n)throw new b(`Sound group not found (type: "${e}")`);n.volume=t,n.sounds.forEach(o=>{this.applyEffectiveVolume(o)})}setGlobalVolume(e){Xo.Howler.volume(e)}getGlobalVolume(){return Xo.Howler.volume()}getGroupVolume(e){return this.groups.get(e)?.volume??1}setupGroupVolume(){let{soundVolume:e,bgmVolume:t,voiceVolume:n}=this.gameState.game.preference.getPreferences();this.setGroupVolume("sound",e),this.setGroupVolume("bgm",t),this.setGroupVolume("voice",n)}initSound(e){if(this.state.has(e))return this.state.get(e);let t=this.groups.get(e.config.type);t&&t.sounds.add(e);let n=this,[o,i]=this.wrapTask(),[r,a]=this.wrapTask(),c=this.groups.get(e.config.type)?.volume??1,l=e.state.volume*c,d=Reflect.construct(this.gameState.getHowl(),[this.getHowlConfig(e,{volume:l,onend(){r.resolve()},onplay(){o.resolve()},onloaderror(g,u){let v=u,T={1:"The fetching process for the media resource was aborted by the user agent at the user's request.",2:"A network error of some description caused the user agent to stop fetching the media resource, after the resource was established to be usable.",3:"An error of some description occurred while decoding the media resource, after the resource was established to be usable.",4:"The media resource indicated by the src attribute or assigned media provider object was not suitable."};n.gameState.logger.error("AudioManager",`Failed to load sound (src: "${e.config.src}")
44
44
  ${T[v]}
45
- For more information, see https://github.com/goldfire/howler.js?tab=readme-ov-file#onloaderror-function`)}})]),p=d.play(),m={group:d,token:p,originalVolume:e.state.volume};return this.state.set(e,m),d.seek(e.config.seek,p).rate(e.state.rate,p),e.state.paused&&d.pause(p),{...m,onPlayTask:i,onEndTask:a}}pushTask(e,t){return this.tasks.set(e,{awaitable:t}),t}getState(e){if(!this.state.has(e))throw new b(`Sound not initialized (src: "${e.config.src}")`);return this.state.get(e)}abortTask(e){let t=this.tasks.get(e);t&&(t.awaitable.abort(),this.tasks.delete(e))}fadeTo(e,t,n){let o,i,r=n.start??e.volume(),a=n.end??e.volume(),c=n.duration,l=new L(()=>{e.volume(a,t),o()});return[p=>{e.volume(r,t),e.fade(r,a,c,t),o=()=>{p.isSolved()||(i&&(i(),i=void 0),p.resolve())},i=this.gameState.schedule(()=>{i=void 0,o()},c)},l]}stopSound(e,t){return[()=>{e.stop(t)}]}pauseSound(e,t){return[()=>{e.pause(t)}]}resumeSound(e,t){return[()=>{e.play(t)}]}getHowlConfig(e,t={}){return{src:e.config.src,volume:e.state.volume,loop:e.config.loop,rate:e.state.rate,html5:e.config.streaming,...t}}createTask(e){return[t=>{e(t.resolve.bind(t))}]}wrapTask(){let e=new h;return[e,[t=>{e.isSolved()?t.resolve():e.then(()=>{t.resolve()})}]]}applyEffectiveVolume(e){if(!this.isManaged(e))return;let t=this.getState(e),n=this.groups.get(e.config.type)?.volume??1,o=t.originalVolume*n;t.group.volume(o,t.token)}};import*as ss from"html-to-image";var io=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new K}addNotification(e){this.notifications.push(e),this.flush()}removeNotification(e){this.notifications=this.notifications.filter(t=>t!==e),this.flush()}clearNotifications(){this.notifications=[],this.flush()}consume(e){let t=new h,n=new re(t);return t.registerSkipController(new L(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};var ro=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let o=Wi(6),{action:i,timeline:r,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize();if(this.history.push({action:i,id:o,args:n||[],undo:t,timeline:r,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(d=>d(l))}return{id:o}}undoUntil(e){let t=-1;for(let i=this.history.length-1;i>=0;i--)if(this.history[i].id===e){t=i;break}if(t===-1)return null;let n=[];for(let i=this.history.length-1;i>=t;i--)this.history[i].timeline&&!this.history[i].timeline.isSettled()&&this.history[i].timeline.abort(),console.log("NarraLeaf-React [ActionHistory] Undoing",this.history[i].action.type,this.history[i]),this.history[i].undo?.(...this.history[i].args||[]),n.push(this.history[i]);this.history.length=t,this.hooks.onUndo.forEach(i=>i(n));let o=this.liveGame.getStackModelForce().serialize();if(o){let[i]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(o,i)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let o=t.length-1;o>=0;o--)if(t[o].isPending!==!0){n=t[o];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var so=class{constructor(e){this.history=[];this.actionHistoryMgr=e,this.actionHistoryMgr.onUndo(t=>{this.crossFilter(t)}),this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){return this.history.push(e),this}getHistory(){return this.history}reset(){this.history=[]}updateByToken(e,t){let n=this.history.find(o=>o.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(n=>n.id));this.history=this.history.filter(n=>!t.has(n.token))}};var zt=class zt{constructor(e,t){this.state={sounds:[],videos:[],srcManagers:[],elements:[]};this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new Jt;this.htmlToImage=ss;this.pageRouter=null;this.stage=t,this.game=e,this.events=new K,this.logger=new no(e,"NarraLeaf-React"),this.audioManager=new oo(this),this.guard=new zn(e.config.app.guard).observe(this),this.timelines=new $n(this.guard),this.notificationMgr=new io(this,[]),this.idManager=new Gn,this.actionHistory=new ro(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new so(this.actionHistory)}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let o of n.layers.values())if(o.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=Pe.isScene(e)?e:e.entryScene;if(!t)throw new b("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(zt.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){return this.state.elements[this.state.elements.length-1]?.scene||null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],o=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:i=>{n.push(i)}})},t);return()=>{n.forEach(i=>i()),clearTimeout(o)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,o){let i=this.findElementByScene(this.getLastSceneIfNot(o))?.texts;if(!i)throw this.sceneNotFound();let r=t.evaluate(He.getCtx({gameState:this}));this.game.getLiveGame().events.emit(yt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:H.getText(r)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:r},()=>{i.splice(i.indexOf(a),1),n&&n()});return i.push(a),this.stage.update(),{cancel:()=>{let c=i.indexOf(a);c!==-1&&i.splice(c,1)},text:H.getText(r)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let o=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!o)throw this.sceneNotFound();let i=e.prompt?.evaluate(He.getCtx({gameState:this}))||null,r=this.createWaitableAction({...e,words:i},a=>{o.splice(o.indexOf(r),1),t&&t(a),this.game.getLiveGame().events.emit(yt.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return o.push(r),{cancel:()=>{let a=o.indexOf(r);a!==-1&&o.splice(a,1)},prompt:i?H.getText(i):null}}createDisplayable(e,t=null,n=null){let o=this.getLastSceneIfNot(t),i=this.findElementByScene(o);if(!i)throw this.sceneNotFound();let r=i.layers.get(n||o.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();return r.push(e),this}disposeDisplayable(e,t=null,n=null){let o=this.getLastSceneIfNot(t),i=this.findElementByScene(o)?.layers.get(n||o.config.defaultDisplayableLayer);if(!i)throw this.layerNotFound();let r=i.indexOf(e);if(r===-1)throw new b(`Displayables not found when disposing. (disposing: ${e.getId()})`);return i.splice(r,1),this}forceReset(){this.state.elements.forEach(({scene:e})=>{this.offSrcManager(e.srcManager),this.removeScene(e),e.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return Qi.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new b("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=re.proxy(h.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(o=>{o instanceof qe&&n.push(o)}),n.forEach(o=>{let i=this.getExposedStateForce(o),r=i.applyTransform(F.immediate({}),()=>{});t.attachChild(r),i.updateStyleSync()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new ge("State already mounted");if(!e)throw new ge("Invalid state key");return this.exposedState.set(e,t),this.events.emit(zt.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new b("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let o=this.events.on(zt.EventTypes["event.state.onExpose"],(i,r)=>{i===e&&(t(r),o.cancel())});return o}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(o=>o.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()])}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:o,audio:i,videos:r}=e;o.forEach(({sceneId:a,elements:c})=>{this.logger.debug("Loading scene: "+a);let l=t.get(a);if(!l)throw new b("Scene not found, id: "+a+`
45
+ For more information, see https://github.com/goldfire/howler.js?tab=readme-ov-file#onloaderror-function`)}})]),p=d.play(),m={group:d,token:p,originalVolume:e.state.volume};return this.state.set(e,m),d.seek(e.config.seek,p).rate(e.state.rate,p),e.state.paused&&d.pause(p),{...m,onPlayTask:i,onEndTask:a}}pushTask(e,t){return this.tasks.set(e,{awaitable:t}),t}getState(e){if(!this.state.has(e))throw new b(`Sound not initialized (src: "${e.config.src}")`);return this.state.get(e)}abortTask(e){let t=this.tasks.get(e);t&&(t.awaitable.abort(),this.tasks.delete(e))}fadeTo(e,t,n){let o,i,r=n.start??e.volume(),a=n.end??e.volume(),c=n.duration,l=new L(()=>{e.volume(a,t),o()});return[p=>{e.volume(r,t),e.fade(r,a,c,t),o=()=>{p.isSolved()||(i&&(i(),i=void 0),p.resolve())},i=this.gameState.schedule(()=>{i=void 0,o()},c)},l]}stopSound(e,t){return[()=>{e.stop(t)}]}pauseSound(e,t){return[()=>{e.pause(t)}]}resumeSound(e,t){return[()=>{e.play(t)}]}getHowlConfig(e,t={}){return{src:e.config.src,volume:e.state.volume,loop:e.config.loop,rate:e.state.rate,html5:e.config.streaming,...t}}createTask(e){return[t=>{e(t.resolve.bind(t))}]}wrapTask(){let e=new h;return[e,[t=>{e.isSolved()?t.resolve():e.then(()=>{t.resolve()})}]]}applyEffectiveVolume(e){if(!this.isManaged(e))return;let t=this.getState(e),n=this.groups.get(e.config.type)?.volume??1,o=t.originalVolume*n;t.group.volume(o,t.token)}};import*as ss from"html-to-image";var io=class{constructor(e,t){this.gameState=e;this.notifications=t;this.events=new K}addNotification(e){this.notifications.push(e),this.flush()}removeNotification(e){this.notifications=this.notifications.filter(t=>t!==e),this.flush()}clearNotifications(){this.notifications=[],this.flush()}consume(e){let t=new h,n=new re(t);return t.registerSkipController(new L(()=>{this.removeNotification(e)})),this.addNotification(e),e.duration&&this.gameState.schedule(()=>{t.resolve(),this.removeNotification(e)},e.duration),this.gameState.timelines.attachTimeline(n),t}onFlush(e){return this.events.on("event:notifications.flush",e)}toArray(){return[...this.notifications]}flush(){this.events.emit("event:notifications.flush")}};var ro=class{constructor(e=100,t){this.liveGame=t;this.history=[];this.hooks={onUndo:[],onHistoryLimit:[]};this.maxHistorySize=e}push(e,t,n){let o=Wi(6),{action:i,timeline:r,stackModel:a}=e,c=this.liveGame.getStackModelForce().serialize(!1);if(this.history.push({action:i,id:o,args:n||[],undo:t,timeline:r,rootStackSnapshot:c,stackModel:a}),this.history.length>this.maxHistorySize){let l=this.history.splice(0,this.history.length-this.maxHistorySize);this.hooks.onHistoryLimit.forEach(d=>d(l))}return{id:o}}undoUntil(e){let t=-1;for(let i=this.history.length-1;i>=0;i--)if(this.history[i].id===e){t=i;break}if(t===-1)return null;let n=[];for(let i=this.history.length-1;i>=t;i--)this.history[i].timeline&&!this.history[i].timeline.isSettled()&&this.history[i].timeline.abort(),console.log("NarraLeaf-React [ActionHistory] Undoing",this.history[i].action.type,this.history[i]),this.history[i].undo?.(...this.history[i].args||[]),n.push(this.history[i]);this.history.length=t,this.hooks.onUndo.forEach(i=>i(n));let o=this.liveGame.getStackModelForce().serialize();if(o){let[i]=this.liveGame.constructMaps();this.liveGame.getStackModelForce().deserialize(o,i)}return n[n.length-1]||null}undo(e){if(!this.ableToUndo(e))return null;let t=e.getHistory(),n;for(let o=t.length-1;o>=0;o--)if(t[o].isPending!==!0){n=t[o];break}return n?this.undoUntil(n.token):null}ableToUndo(e){return this.history.length>0&&e.getHistory().some(t=>t.isPending!==!0)}onUndo(e){return this.hooks.onUndo.push(e),{cancel:()=>this.offUndo(e)}}offUndo(e){this.hooks.onUndo=this.hooks.onUndo.filter(t=>t!==e)}getHistory(){return this.history}onHistoryLimit(e){return this.hooks.onHistoryLimit.push(e),{cancel:()=>this.offHistoryLimit(e)}}offHistoryLimit(e){this.hooks.onHistoryLimit=this.hooks.onHistoryLimit.filter(t=>t!==e)}reset(){this.history.forEach(e=>{e.timeline&&!e.timeline.isSettled()&&e.timeline.abort()}),this.history=[]}};var so=class{constructor(e){this.history=[];this.actionHistoryMgr=e,this.actionHistoryMgr.onUndo(t=>{this.crossFilter(t)}),this.actionHistoryMgr.onHistoryLimit(t=>{this.crossFilter(t)})}push(e){return this.history.push(e),this}getHistory(){return this.history}reset(){this.history=[]}updateByToken(e,t){let n=this.history.find(o=>o.token===e);t(n||null)}resolvePending(e){let t=this.history.find(n=>n.token===e);t&&(t.isPending=!1)}crossFilter(e){let t=new Set(e.map(n=>n.id));this.history=this.history.filter(n=>!t.has(n.token))}};var zt=class zt{constructor(e,t){this.state={sounds:[],videos:[],srcManagers:[],elements:[]};this.currentHandling=null;this.playerCurrent=null;this.mainContentNode=null;this.exposedState=new Map;this.preloadingScene=null;this.flushDep=0;this.rollLock=new Jt;this.htmlToImage=ss;this.pageRouter=null;this.stage=t,this.game=e,this.events=new K,this.logger=new no(e,"NarraLeaf-React"),this.audioManager=new oo(this),this.guard=new zn(e.config.app.guard).observe(this),this.timelines=new $n(this.guard),this.notificationMgr=new io(this,[]),this.idManager=new Gn,this.actionHistory=new ro(e.config.maxActionHistory,this.game.getLiveGame()),this.gameHistory=new so(this.actionHistory)}get deps(){return this.flushDep}addVideo(e){return this.state.videos.push(e),this}removeVideo(e){let t=this.state.videos.indexOf(e);return t===-1?(this.logger.weakWarn("Video not found when removing",e.getId()),this):(this.state.videos.splice(t,1),this)}isVideoAdded(e){return this.state.videos.includes(e)}getVideos(){return this.state.videos}findElementByScene(e){return this.state.elements.find(t=>t.scene===e)||null}findElementByDisplayable(e,t=null){return this.state.elements.find(n=>{if(t)return n.layers.get(t)?.includes(e)||!1;for(let o of n.layers.values())if(o.includes(e))return!0;return!1})||null}getLiveGame(){return this.game.getLiveGame()}removeElement(e){let t=this.state.elements.indexOf(e);return t===-1?(this.logger.weakWarn("Element not found when removing",e.scene.getId()),this):(this.logger.debug("GameState","Removing element",e.scene.getId()),this.state.elements.splice(t,1),this)}preloadScene(e){let t=Pe.isScene(e)?e:e.entryScene;if(!t)throw new b("Trying to preload a story but the story is not loaded");return this.preloadingScene=t,this.events.emit(zt.EventTypes["event:state:flushPreloadedScenes"]),this}getPreloadingScene(){return this.preloadingScene}addElement(e){return this.state.elements.push(e),this.logger.debug("GameState","Adding element",e.scene.getId()),this}addScene(e){return this.sceneExists(e)?this:(this.state.elements.unshift({scene:e,texts:[],menus:[],layers:new Map(e.config.layers.map(t=>[t,[]]))}),this.logger.debug("GameState","Adding scene",e.getId()),this)}flush(){return this.stage.update(),this}popScene(){let e=this.state.elements.pop();return e?(this.removeElements(e.scene),this.logger.debug("GameState","Popping scene",e.scene.getId()),this):this}removeScene(e){return this.removeElements(e),this.logger.debug("GameState","Removing scene",e.getId()),this}getSceneElements(){return this.state.elements}getLastScene(){return this.state.elements[this.state.elements.length-1]?.scene||null}sceneExists(e){return e?this.state.elements.some(t=>t.scene===e):!!this.getLastScene()}isSceneActive(e){for(let{scene:t}of this.state.elements)if(t===e)return!0;return!1}wait(e){return new Promise(t=>setTimeout(t,e))}schedule(e,t){let n=[],o=setTimeout(()=>{e({retry:()=>{this.schedule(e,0)},onCleanup:i=>{n.push(i)}})},t);return()=>{n.forEach(i=>i()),clearTimeout(o)}}notify(e){this.notificationMgr.addNotification(e)}handle(e){if(this.currentHandling===e)return this;switch(this.currentHandling=e,e.type){case"condition:action":break}return this}createDialog(e,t,n,o){let i=this.findElementByScene(this.getLastSceneIfNot(o))?.texts;if(!i)throw this.sceneNotFound();let r=t.evaluate(He.getCtx({gameState:this}));this.game.getLiveGame().events.emit(yt.EventTypes["event:character.prompt"],{character:t.config.character,sentence:t,text:H.getText(r)});let a=this.createWaitableAction({character:t.config.character,sentence:t,id:e,words:r},()=>{i.splice(i.indexOf(a),1),n&&n()});return i.push(a),this.stage.update(),{cancel:()=>{let c=i.indexOf(a);c!==-1&&i.splice(c,1)},text:H.getText(r)}}createMenu(e,t,n){if(!e.choices.length)throw new Error("Menu must have at least one choice");let o=this.findElementByScene(this.getLastSceneIfNot(n))?.menus;if(!o)throw this.sceneNotFound();let i=e.prompt?.evaluate(He.getCtx({gameState:this}))||null,r=this.createWaitableAction({...e,words:i},a=>{o.splice(o.indexOf(r),1),t&&t(a),this.game.getLiveGame().events.emit(yt.EventTypes["event:menu.choose"],{sentence:a.prompt,text:a.evaluated})});return o.push(r),{cancel:()=>{let a=o.indexOf(r);a!==-1&&o.splice(a,1)},prompt:i?H.getText(i):null}}createDisplayable(e,t=null,n=null){let o=this.getLastSceneIfNot(t),i=this.findElementByScene(o);if(!i)throw this.sceneNotFound();let r=i.layers.get(n||o.config.defaultDisplayableLayer);if(!r)throw this.layerNotFound();return r.push(e),this}disposeDisplayable(e,t=null,n=null){let o=this.getLastSceneIfNot(t),i=this.findElementByScene(o)?.layers.get(n||o.config.defaultDisplayableLayer);if(!i)throw this.layerNotFound();let r=i.indexOf(e);if(r===-1)throw new b(`Displayables not found when disposing. (disposing: ${e.getId()})`);return i.splice(r,1),this}forceReset(){this.state.elements.forEach(({scene:e})=>{this.offSrcManager(e.srcManager),this.removeScene(e),e.events.clear()}),this.state.elements=[],this.state.srcManagers=[],this.state.videos=[],this.audioManager.reset(),this.timelines.abortAll(),this.gameHistory.reset(),this.actionHistory.reset(),this.logger.debug("GameState","Force reset")}getHowl(){return Qi.Howl}registerSrcManager(e){return this.state.srcManagers.push(e),this}offSrcManager(e){return this.state.srcManagers=this.state.srcManagers.filter(t=>t!==e),this}getStorable(){return this.game.getLiveGame().getStorable()}getSceneByName(e){return this.game.getLiveGame().story?.getScene(e)||null}getStory(){if(!this.game.getLiveGame().story)throw new b("Story not loaded");return this.game.getLiveGame().story}setInterval(e,t){return setInterval(e,t)}clearInterval(e){clearInterval(e)}setTimeout(e,t){return setTimeout(e,t)}clearTimeout(e){clearTimeout(e)}forceAnimation(){let[e,t]=re.proxy(h.nothing),n=[];return Array.from(this.exposedState.keys()).forEach(o=>{o instanceof qe&&n.push(o)}),n.forEach(o=>{let i=this.getExposedStateForce(o),r=i.applyTransform(F.immediate({}),()=>{});t.attachChild(r),i.updateStyleSync()}),this.timelines.attachTimeline(t),e}mountState(e,t){if(this.exposedState.has(e))throw new ge("State already mounted");if(!e)throw new ge("Invalid state key");return this.exposedState.set(e,t),this.events.emit(zt.EventTypes["event.state.onExpose"],e,t),{unMount:()=>{this.unMountState(e)}}}unMountState(e){return this.exposedState.has(e)||this.guard.warn("invalidExposedStateUnmounting","State not found when unmounting"),this.exposedState.delete(e),this}initVideo(e){return this.state.videos.push(e),this}isStateMounted(e){return this.exposedState.has(e)}getExposedState(e){return this.exposedState.get(e)||null}getExposedStateForce(e){let t=this.getExposedState(e);if(!t)throw new b("State not found, key: "+e);return t}getExposedStateAsync(e,t){let n=this.getExposedState(e);if(n)return{cancel:this.schedule(()=>{t(n)},0)};{let o=this.events.on(zt.EventTypes["event.state.onExpose"],(i,r)=>{i===e&&(t(r),o.cancel())});return o}}dispose(){this.forceReset()}toData(){return{scenes:this.state.elements.map(e=>({sceneId:e.scene.getId(),elements:{layers:Object.fromEntries(Array.from(e.layers.entries()).map(([t,n])=>[t.getId(),n.map(o=>o.getId())]))}})),audio:this.audioManager.toData(),videos:this.state.videos.map(e=>[e.getId(),e.toData()])}}loadData(e,t){if(this.state.elements=[],!this.game.getLiveGame().story)throw new Error("No story loaded");let{scenes:o,audio:i,videos:r}=e;o.forEach(({sceneId:a,elements:c})=>{this.logger.debug("Loading scene: "+a);let l=t.get(a);if(!l)throw new b("Scene not found, id: "+a+`
46
46
  NarraLeaf cannot find the element with the id from the saved game`);let d={scene:l,layers:this.constructLayerMap(c.layers,t),menus:[],texts:[]};this.state.elements.push(d),this.registerSrcManager(l.srcManager),this.getExposedStateAsync(l,p=>{se.initBackgroundMusic(l,p)})}),this.audioManager.fromData(i,t),this.state.videos=r.map(([a,c])=>{let l=t.get(a);if(!l)throw new b("Video not found, id: "+a+`
47
47
  NarraLeaf cannot find the element with the id from the saved game`);return l.fromData(c),l})}getLastSceneIfNot(e){let t=e||this.getLastScene();if(!t||!this.sceneExists(t))throw new b('Scene not found, please call "scene.activate()" first.');return t}createElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(o=>[o,o.toData()])]))}}fromElementSnapshot(e){return{scene:e.scene,layers:new Map(Array.from(e.layers.entries()).map(([t,n])=>[t,n.map(([o,i])=>(o.fromData(i),o))])),texts:[],menus:[]}}removeElements(e){let t=this.state.elements.findIndex(n=>n.scene===e);return t===-1?(this.logger.weakWarn("Scene not found when removing elements",e.getId()),this):(this.resetLayers(this.state.elements[t].layers),this.state.elements.splice(t,1),this.logger.debug("GameState","Removing elements",e.getId()),this)}resetLayers(e){e.forEach(t=>{t.forEach(n=>{n.reset()})})}createWaitableAction(e,t){return{action:e,onClick:o=>{t&&t(o)}}}sceneNotFound(){return new b("Scene not found, target scene may not be activated. This is an internal error, please report this to the developer.")}layerNotFound(){return new b("Layer not found, target layer may not be activated. You may forget to add the layer to the scene config")}constructLayerMap(e,t){return new Map(Object.entries(e).map(([n,o])=>{let i=t.get(n);if(!i)throw new b("Layer not found, id: "+n+`
48
48
  NarraLeaf cannot find the element with the id from the saved game`);return[i,o.map(r=>{if(!t.has(r))throw new b("Displayable not found, id: "+r+`
49
49
  NarraLeaf cannot find the element with the id from the saved game
50
- This may be caused by the damage of the saved game file or the change of the story file`);return t.get(r)})]}))}};zt.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.requestFlush":"event:state.player.requestFlush","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes"};var U=zt;var Ee=class s{constructor(e,t=void 0){this.liveGame=e;this.__tag=void 0;this.waitingAction=null;this.__tag=t,this.stack=new Hn().addPushValidator(n=>{let o=this.stack.peek();if(n===o)throw new ge("StackModel: Unexpected self-push in stack.");if(s.isCalledActionResult(o)){if(o.wait&&s.isStackModelsAwaiting(o.wait.type,o.wait.stackModels))throw new ge("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(h.isAwaitable(o)&&!o.isSettled())throw new ge("StackModel: Unexpected unsettled Awaitable in stack.");if(!s.isCalledActionResult(n)&&!h.isAwaitable(n))throw new ge("StackModel: Unexpected non-CalledActionResult or Awaitable in stack.");return!0})}static isStackModel(e){return e instanceof s}static createStackModel(e,t,n){let o=new s(e);return o.deserialize(t,n),o}static isCalledActionResult(e){return!!e&&!this.isStackModel(e)&&!h.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?h.any(...t.map(n=>n.execute())):h.all(...t.map(n=>n.execute()))}static isStackModelsAwaiting(e,t){if(t.length===0)throw new Error("StackModel: StackModels are empty.");return e==="any"?t.every(n=>!n.isEmpty()):t.some(n=>!n.isEmpty())}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(h.isAwaitable(e)&&!e.isSettled())return e;if(s.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(s.isStackModelsAwaiting(e.wait.type,n))return n.forEach(o=>o.rollNext()),e}this.waitingAction=null;let t=this.stack.pop();if(h.isAwaitable(t)){let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=new h,t=null,n=!1;return(async()=>{let i=0;for(;!n;){if(i++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){n=!0;break}let r=this.rollNext();if(r){if(h.isAwaitable(r)){if(r.isSettled())continue;t=r,await r}else if(s.isCalledActionResult(r))if(r.wait)t=s.executeStackModelGroup(r.wait.type,r.wait.stackModels),await t;else continue}}})().then(()=>e.resolve()),e.onSkipControllerRegister(i=>{i.onAbort(()=>{t&&(n=!0,t.abort())})}),e}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&h.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):s.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(s.isCalledActionResult(n))return n;if(e)throw new ge("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}executeActions(e){if(!e.node?.action)return null;let t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this}),n=o=>o?h.isAwaitable(o)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",o),this.stack.push(o),o):o.node?.action?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",o),this.stack.push(o),o):null:null;if(Array.isArray(t)){let o=null;for(let i of t){let r=n(i);r&&(o=r)}return o}else{let o=n(t);if(o)return o}return null}isWaiting(){let e=this.stack.peek();return e?h.isAwaitable(e)?!e.isSettled():s.isCalledActionResult(e)&&e.wait?s.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(){let e=n=>{if(s.isCalledActionResult(n)){let o=n.node?.action?.getId()??null,i=n.node?.action?.type??null;return n.wait?.stackModels?{type:"link",actionType:i,action:o,stacks:n.wait.stackModels.map(r=>r.serialize()),stackWaitType:n.wait.type}:{type:"action",actionType:i,action:o}}return null},t=this.stack.map(e).filter(function(n){return n!==null});if(this.waitingAction){let n=e(this.waitingAction);n&&t.push(n)}return t}reset(){this.stack.forEach(e=>{s.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):h.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear()}deserialize(e,t){this.reset();for(let n of e)if(n.type==="action"){if(!n.action)continue;let{actionType:o,action:i}=n,r=t.get(i);if(!r)throw new Error(`Action not found: ${i}`);this.stack.push({type:o,node:r.contentNode,wait:null})}else if(n.type==="link"){let{actionType:o,action:i,stacks:r,stackWaitType:a}=n;if(a==null)throw new Error(`Missing stackWaitType for link action: ${i}`);this.stack.push({type:o,node:i?t.get(i)?.contentNode??null:null,wait:{type:a,stackModels:r.map(c=>s.createStackModel(this.liveGame,c,t))}})}return this}isEmpty(){return this.stack.isEmpty()}push(...e){return this.stack.push(...e),this}};var st=class st{constructor(e){this.events=new K;this.story=null;this.gameLock=new Nt;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.lastDialog=null;this.mapCache=null;this.game=e,this._storable=new an,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new it(st.GameSpacesKey.game,st.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");let n=this._storable.toData(),o=e.toData(),i=t.getAllElementStates(),r=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(c=>c.serialize());return{name:this.currentSavedGame.name,meta:{created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:t.hash()},game:{store:n,stage:o,elementStates:i,stackModel:r,asyncStackModels:a,services:t.serializeServices()}}}deserialize(e){this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:o,stage:i,elementStates:r,services:a,stackModel:c,asyncStackModels:l}}=e,[d,p]=this.constructMaps();this._storable.clear().load(o),r.forEach(({id:m,data:g})=>{t.logger.debug("restore element",m);let u=p.get(m);if(!u)throw new Error("Element not found, id: "+m+`
50
+ This may be caused by the damage of the saved game file or the change of the story file`);return t.get(r)})]}))}};zt.EventTypes={"event:state.end":"event:state.end","event:state.player.skip":"event:state.player.skip","event:state.player.requestFlush":"event:state.player.requestFlush","event.state.onExpose":"event.state.onExpose","event:state.onRender":"event:state.onRender","event:state:flushPreloadedScenes":"event:state:flushPreloadedScenes"};var U=zt;var Ee=class s{constructor(e,t=void 0){this.liveGame=e;this.__tag=void 0;this.waitingAction=null;this.__tag=t,this.stack=new Hn().addPushValidator(n=>{let o=this.stack.peek();if(n===o)throw new ge("StackModel: Unexpected self-push in stack.");if(s.isCalledActionResult(o)){if(o.wait&&s.isStackModelsAwaiting(o.wait.type,o.wait.stackModels))throw new ge("StackModel: Unexpected waiting action in stack. (is calledActionResult: true, wait: true)")}else if(h.isAwaitable(o)&&!o.isSettled())throw new ge("StackModel: Unexpected unsettled Awaitable in stack.");if(!s.isCalledActionResult(n)&&!h.isAwaitable(n))throw new ge("StackModel: Unexpected non-CalledActionResult or Awaitable in stack.");return!0})}static isStackModel(e){return e instanceof s}static createStackModel(e,t,n){let o=new s(e);return o.deserialize(t,n),o}static isCalledActionResult(e){return!!e&&!this.isStackModel(e)&&!h.isAwaitable(e)&&"type"in e}static fromAction(e){return{type:e.type,node:e.contentNode}}static executeStackModelGroup(e,t){return e==="any"?h.any(...t.map(n=>n.execute())):h.all(...t.map(n=>n.execute()))}static isStackModelsAwaiting(e,t){if(t.length===0)throw new Error("StackModel: StackModels are empty.");return e==="any"?t.every(n=>!n.isEmpty()):t.some(n=>!n.isEmpty())}rollNext(){if(this.stack.isEmpty())return null;let e=this.stack.peek();if(h.isAwaitable(e)&&!e.isSettled())return e;if(s.isCalledActionResult(e)&&e.wait){let n=e.wait.stackModels;if(!n.length)throw new Error("StackModel: Waiting action contains empty stackModels.");if(s.isStackModelsAwaiting(e.wait.type,n))return n.forEach(o=>o.rollNext()),e}this.waitingAction=null;let t=this.stack.pop();if(h.isAwaitable(t)){let n=t.result;if(n)return this.stack.push(n),this.liveGame.getGameStateForce().logger.debug("next action (resolved awaitable)",n.node?.action),n}else return this.waitingAction=t,this.executeActions(t);return null}execute(){let e=new h,t=null,n=!1;return(async()=>{let i=0;for(;!n;){if(i++>this.liveGame.game.config.maxStackModelLoop)throw new Error("StackModel: Suspiciously long waiting loop.");if(this.stack.isEmpty()){n=!0;break}let r=this.rollNext();if(r){if(h.isAwaitable(r)){if(r.isSettled())continue;t=r,await r}else if(s.isCalledActionResult(r))if(r.wait)t=s.executeStackModelGroup(r.wait.type,r.wait.stackModels),await t;else continue}}})().then(()=>e.resolve()),e.onSkipControllerRegister(i=>{i.onAbort(()=>{t&&(n=!0,t.abort())})}),e}abortStackTop(){if(this.stack.isEmpty())return null;let e=this.stack.peek();return e&&h.isAwaitable(e)?(this.stack.pop().abort(),this.waitingAction=null):s.isCalledActionResult(e)&&e.wait&&(e.wait.stackModels.forEach(t=>t.abortStackTop()),this.waitingAction=null),this.waitingAction}getTopSync(){if(this.stack.isEmpty())return null;let e=!1;for(let t=this.stack.size()-1;t>=0;t--){let n=this.stack.get(t);if(n){if(s.isCalledActionResult(n))return n;if(e)throw new ge("StackModel: Unexpected non-CalledActionResult in stack.")}else return null;e=!0}return null}executeActions(e){if(!e.node?.action)return null;let t=this.liveGame.executeAction(this.liveGame.getGameStateForce(),e.node.action,{stackModel:this}),n=o=>o?h.isAwaitable(o)?(this.liveGame.getGameStateForce().logger.debug("next action (executed awaitable)",o),this.stack.push(o),o):o.node?.action?(this.liveGame.getGameStateForce().logger.debug("next action (executed)",o),this.stack.push(o),o):null:null;if(Array.isArray(t)){let o=null;for(let i of t){let r=n(i);r&&(o=r)}return o}else{let o=n(t);if(o)return o}return null}isWaiting(){let e=this.stack.peek();return e?h.isAwaitable(e)?!e.isSettled():s.isCalledActionResult(e)&&e.wait?s.isStackModelsAwaiting(e.wait.type,e.wait.stackModels):!1:!1}serialize(e=!0){let t=o=>{if(s.isCalledActionResult(o)){let i=o.node?.action?.getId()??null,r=o.node?.action?.type??null;return o.wait?.stackModels?{type:"link",actionType:r,action:i,stacks:o.wait.stackModels.map(a=>a.serialize()),stackWaitType:o.wait.type}:{type:"action",actionType:r,action:i}}return null},n=this.stack.map(t).filter(function(o){return o!==null});if(e&&this.waitingAction){let o=t(this.waitingAction);o&&n.push(o)}return n}reset(){this.stack.forEach(e=>{s.isCalledActionResult(e)?e.wait?.stackModels.forEach(t=>t.reset()):h.isAwaitable(e)&&e.abort()}),this.waitingAction&&this.waitingAction.wait?.stackModels.forEach(e=>e.reset()),this.waitingAction=null,this.stack.clear()}deserialize(e,t){this.reset();for(let n of e)if(n.type==="action"){if(!n.action)continue;let{actionType:o,action:i}=n,r=t.get(i);if(!r)throw new Error(`Action not found: ${i}`);this.stack.push({type:o,node:r.contentNode,wait:null})}else if(n.type==="link"){let{actionType:o,action:i,stacks:r,stackWaitType:a}=n;if(a==null)throw new Error(`Missing stackWaitType for link action: ${i}`);this.stack.push({type:o,node:i?t.get(i)?.contentNode??null:null,wait:{type:a,stackModels:r.map(c=>s.createStackModel(this.liveGame,c,t))}})}return this}isEmpty(){return this.stack.isEmpty()}push(...e){return this.stack.push(...e),this}};var st=class st{constructor(e){this.events=new K;this.story=null;this.gameLock=new Nt;this.currentSavedGame=null;this.gameState=void 0;this.stackModel=null;this.asyncStackModels=new Set;this.lastDialog=null;this.mapCache=null;this.game=e,this._storable=new an,this.initNamespaces()}initNamespaces(){return this._storable.clear().addNamespace(new it(st.GameSpacesKey.game,st.DefaultNamespaces.game)),this.story&&this.story.initPersistent(this._storable),this}getStorable(){return this._storable}get storable(){return this._storable}loadStory(e){return this.story=e.constructStory(),this}serialize(){this.assertGameState();let e=this.gameState,t=this.story;if(!t)throw new Error("No story loaded");if(!this.currentSavedGame||!this.stackModel)throw new Error("Failed when trying to serialize the game: The game has not started");let n=this._storable.toData(),o=e.toData(),i=t.getAllElementStates(),r=this.stackModel.serialize(),a=Array.from(this.asyncStackModels).map(c=>c.serialize());return{name:this.currentSavedGame.name,meta:{created:this.currentSavedGame.meta.created,updated:Date.now(),id:this.currentSavedGame.meta.id,lastSentence:this.lastDialog?.sentence||null,lastSpeaker:this.lastDialog?.speaker||null,storyHash:t.hash()},game:{store:n,stage:o,elementStates:i,stackModel:r,asyncStackModels:a,services:t.serializeServices()}}}deserialize(e){if(!e)throw new Error("No saved game provided when trying to deserialize game state");this.assertGameState();let t=this.gameState,n=this.story;if(!n)throw new Error("No story loaded");t.rollLock.lock(),this.reset(),t.stage.forceRemount();let{game:{store:o,stage:i,elementStates:r,services:a,stackModel:c,asyncStackModels:l}}=e,[d,p]=this.constructMaps();this._storable.clear().load(o),r.forEach(({id:m,data:g})=>{t.logger.debug("restore element",m);let u=p.get(m);if(!u)throw new Error("Element not found, id: "+m+`
51
51
  NarraLeaf cannot find the element with the id from the saved game`);u.reset(),u.fromData(g)}),this.currentSavedGame=e,t.loadData(i,p),this.stackModel.deserialize(c,d),l.forEach(m=>this.asyncStackModels.add(Ee.createStackModel(this,m,d))),this.asyncStackModels.forEach(m=>t.timelines.attachTimeline(m.execute())),n.deserializeServices(a),t.events.once(U.EventTypes["event:state.onRender"],()=>{t.schedule(()=>{t.rollLock.unlock(),t.stage.next()},0)}),t.stage.forceUpdate()}getHistory(){return this.assertGameState(),this.gameState.gameHistory.getHistory()}undo(e){if(this.assertGameState(),!this.gameState.actionHistory.ableToUndo(this.gameState.gameHistory)){this.gameState.logger.warn("LiveGame.undo","No action to undo");return}let t=this.gameLock.register().lock();this.stackModel.abortStackTop();let n=e?this.gameState.actionHistory.undoUntil(e):this.gameState.actionHistory.undo(this.gameState.gameHistory);if(n){let[o]=this.constructMaps(),{rootStackSnapshot:i,stackModel:r}=n;this.stackModel.deserialize(i,o),r===this.stackModel&&this.stackModel.push(Ee.fromAction(n.action)),this.gameLock.off(t.unlock()),this.gameState.logger.info("LiveGame.undo","Undo until",e,"action",n),this.gameState.stage.forceUpdate(),this.gameState.stage.next(),this.gameState.schedule(()=>{this.gameState&&this.gameState.forceAnimation()},0)}else this.gameState.logger.warn("LiveGame.undo","No action found"),this.gameLock.off(t.unlock())}dispose(){this.events.clear(),this.gameState?.dispose()}notify(e,t=3e3){this.assertGameState();let n=this.gameState.idManager.generateId(),o=this.gameState.notificationMgr.consume({id:n,message:e,duration:t}),i=h.toPromiseForce(o);return{cancel:()=>{o.abort()},promise:i}}skipDialog(){this.assertGameState(),this.gameState.events.emit(U.EventTypes["event:state.player.skip"],!0)}assertScreenshot(){this.assertGameState(),this.assertPlayerElement()}capturePng(){return this.assertScreenshot(),this.gameState.htmlToImage.toPng(this.gameState.mainContentNode,this.getScreenshotOptions())}captureJpeg(){return this.assertScreenshot(),this.gameState.htmlToImage.toJpeg(this.gameState.mainContentNode,this.getScreenshotOptions())}captureSvg(){return this.assertScreenshot(),this.gameState.htmlToImage.toSvg(this.gameState.mainContentNode,this.getScreenshotOptions())}capturePngBlob(){return this.assertScreenshot(),this.assertGameState(),this.assertPlayerElement(),this.gameState.htmlToImage.toBlob(this.gameState.mainContentNode,this.getScreenshotOptions())}onCharacterPrompt(e){return this.events.on(st.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(st.EventTypes["event:menu.choose"],e)}newGame(){this.assertGameState();let e=this.gameState,t=e.logger.group("LiveGame (newGame)",!0);this.reset(),this.initNamespaces();let n=this.getNewSavedGame();n.name="NewGame-"+Date.now(),this.currentSavedGame=n;let o=this.story?.entryScene?.getSceneRoot();o?this.stackModel.push(Ee.fromAction(o)):e.logger.warn("No scene root found");let i=this.story?.getAllElementMap(this.story,this.story?.entryScene?.getSceneRoot()||[]);return i?i.forEach(r=>{e.logger.debug("reset element",r),r.reset()}):e.logger.warn("No elements found"),e.stage.forceUpdate(),e.stage.next(),t.end(),this}waitForRouterExit(){let e=null;return{promise:new Promise(t=>{e=this.game.router.onceExitComplete(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}waitForPageMount(){let e=null;return{promise:new Promise(t=>{e=this.game.router.oncePageMount(()=>{t()})}),cancel:()=>{e&&e.cancel()}}}requestFullScreen(e){this.assertGameState();let t="LiveGame.requestFullScreen";try{let n=this.gameState.playerCurrent;if(!n){this.gameState.logger.warn(t,"No player element found");return}if(n.requestFullscreen)return n.requestFullscreen(e);this.gameState.logger.warn(t,"Fullscreen is not supported")}catch(n){this.gameState.logger.error(t,n)}}exitFullScreen(){this.assertGameState();let e="LiveGame.exitFullScreen";try{if(document.exitFullscreen)return document.exitFullscreen();this.gameState.logger.warn(e,"Fullscreen is not supported")}catch(t){this.gameState.logger.error(e,t)}}constructMaps(){let e=this.story;if(!e)throw new Error("No story loaded");if(this.mapCache)return this.mapCache;let t=new Map,n=new Map;return e.forEachChild(e,e.entryScene?.getSceneRoot()||[],o=>{t.set(o.getId(),o),n.set(o.callee.getId(),o.callee)},{allowFutureScene:!0}),this.mapCache=[t,n],this.mapCache}getScreenshotOptions(){return{quality:this.game.config.screenshotQuality}}onPlayerEvent(e,t,n){this.assertPlayerElement();let o=this.gameState.playerCurrent;return o?(o.addEventListener(e,t,n),{cancel:()=>o.removeEventListener(e,t,n)}):(this.gameState.logger.warn("LiveGame.onEvent","No player element found"),{cancel:()=>{}})}onWindowEvent(e,t,n){return window.addEventListener(e,t,n),{cancel:()=>window.removeEventListener(e,t,n)}}reset(){this.assertGameState();let e=this.gameState;this.resetStackModels(),this.stackModel.reset(),this.currentSavedGame=null,this.lastDialog=null,e.forceReset()}next(){this.assertGameState();let e=this.gameState;if(this.gameLock.isLocked())return this.gameLock;if(!this.story)throw new Error("No story loaded");return this.stackModel.isEmpty()?(e.logger.weakWarn("LiveGame","No current action"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new Ee(this);return this.asyncStackModels.add(t),t.push(...e),t}createStackModel(e){let t=new Ee(this);return t.push(...e),t}resetStackModels(){this.asyncStackModels.forEach(e=>e.reset()),this.asyncStackModels.clear()}isPlaying(){return this.stackModel&&!this.stackModel.isEmpty()}executeAction(e,t,n){if(!this.stackModel)throw new Error("Stack model is not initialized");let o=t.executeAction(e,n);return h.isAwaitable(o)?o:o||null}setGameState(e){if(e&&this.gameState)throw new ge("GameState already set");return this.gameState=e,e&&!this.stackModel&&(this.stackModel=new Ee(this,"$root")),this}getGameState(){return this.gameState}getGameStateForce(){if(!this.gameState)throw new ge("GameState not set");return this.gameState}getAllPredictableActions(e,t,n){let o=t?.contentNode||null,i=[],r=[],a=new Set;for(;(o||r.length)&&!(n&&i.length>=n);){if(o||(o=r.pop().contentNode),[gt].some(c=>o?.action&&o.action instanceof c)){o=null;continue}if(o.action&&o.action.is(se,_.jumpTo)){let[c]=o.action.contentNode.getContent(),l=e.getScene(c);if(!l)throw o.action._sceneNotFoundError(o.action.getSceneName(c));if(a.has(l)){o=null;continue}a.add(l),o=l.getSceneRoot()?.contentNode||null;continue}else if(o.action&&o.action.is(ee,We.do)){let[c]=o.action.contentNode.getContent();o.getChild()?.action&&r.push(o.getChild().action),o=c[0]?.contentNode||null}o.action&&i.push(o.action),o=o.getChild()}return i}clearMainStack(){if(!this.stackModel)throw new ge("No stack model found");return this.stackModel.reset(),this}getStackModelForce(){if(!this.stackModel)throw new ge("No stack model found");return this.stackModel}getNewSavedGame(){return{name:"",meta:{created:Date.now(),updated:Date.now(),id:Oi(),lastSentence:null,lastSpeaker:null,storyHash:this.story?.hash()||""},game:{store:{},stage:{scenes:[],audio:{sounds:[],groups:[]},videos:[]},elementStates:[],services:{},stackModel:[],asyncStackModels:[]}}}assertGameState(){if(!this.gameState)throw new b("No game state found, make sure you call this method in effect hooks or event handlers")}assertPlayerElement(){if(this.assertGameState(),!this.gameState.playerCurrent)throw new b("Player Element Not Mounted")}};st.DefaultNamespaces={game:{}},st.GameSpacesKey={game:"game"},st.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose"};var yt=st;var un=class un{constructor(e){this.settings=e;this.events=new K;this.events.setMaxListeners(64)}setPreference(e,t){this.settings[e]=t,this.events.emit(un.EventTypes["event:game.preference.change"],e,t)}getPreference(e){return this.settings[e]}getPreferences(){return this.settings}onPreferenceChange(e,t){return this.events.on(un.EventTypes["event:game.preference.change"],(n,o)=>{typeof e=="string"?e===n&&t&&t(o):e(n,o)})}importPreferences(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setPreference(t,e[t])}exportPreferences(){let e={};for(let t in this.settings)Object.prototype.hasOwnProperty.call(this.settings,t)&&(e[t]=this.settings[t]);return e}togglePreference(e){if(typeof this.settings[e]!="boolean")throw new Error(`Preference ${e} is not a boolean`);this.setPreference(e,!this.getPreference(e))}};un.EventTypes={"event:game.preference.change":"event:game.preference.change"};var pn=un;import"client-only";import Tr,{useEffect as ua,useRef as ai}from"react";import"client-only";import Xi,{useContext as as,useState as cs}from"react";var Ji=Xi.createContext(null);function Yi({children:s,game:e}){"use client";let t=new q({}),[n]=cs(e||t);return Xi.createElement(Ji,{value:n},s)}function w(){let s=as(Ji);if(!s)throw new Error("useGame must be used within a GameProvider");return s}import ls,{createContext as us,useContext as Zi}from"react";var _i="/",ao=class ao{constructor(e,t=ao.rootPath){this.events=new K;this.currentPath="";this.currentQuery={};this.history=[];this.historyIndex=-1;this.mountedPaths=new Set;this.defaultHandlerPaths=new Set;this.unmountingPaths=new Set;this.updateSyncHooks=new Set;this.transitioning=!1;this.game=e;let{path:n,query:o}=this.parseUrl(t);this.currentPath=n,this.currentQuery=o,this.history.push(t),this.historyIndex=0}getCurrentPath(){return this.currentPath}getPathname(){return this.currentPath}getCurrentQuery(){return{...this.currentQuery}}getQueryParams(){return this.getCurrentQuery()}getCurrentUrl(){return this.buildUrl(this.currentPath,this.currentQuery)}parseUrl(e){let[t,n]=e.split("?"),o={};if(n){let i=n.split("&");for(let r of i){let[a,c]=r.split("=");a&&(o[decodeURIComponent(a)]=c?decodeURIComponent(c):"")}}return{path:t||"/",query:o}}buildUrl(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return`${e}?${n}`}getQueryParam(e){return this.currentQuery[e]}setQueryParam(e,t){return this.currentQuery[e]=t,this.updateHistory(),this.emitOnChange(),this}setQueryParams(e){return Object.assign(this.currentQuery,e),this.updateHistory(),this.emitOnChange(),this}removeQueryParam(e){return delete this.currentQuery[e],this.updateHistory(),this.emitOnChange(),this}clearQueryParams(){return this.currentQuery={},this.updateHistory(),this.emitOnChange(),this}hasQueryParam(e){return e in this.currentQuery}getQueryParamKeys(){return Object.keys(this.currentQuery)}getQueryParamCount(){return Object.keys(this.currentQuery).length}getHistory(){return[...this.history]}getHistoryIndex(){return this.historyIndex}canGoBack(){return this.historyIndex>0}canGoForward(){return this.historyIndex<this.history.length-1}navigate(e,t){let{path:n,query:o}=this.parseUrl(e),i=this.resolvePath(n),r={...o,...t};if(this.currentPath===i)return this.currentQuery=r,this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(i,r)),this.emitOnChange(),this;this.historyIndex<this.history.length-1&&(this.history.length=this.historyIndex+1);let a=this.buildUrl(i,r);return this.history.push(a),this.history.length>this.game.config.maxRouterHistory&&(this.history.shift(),this.historyIndex--),this.historyIndex++,this.currentPath=i,this.currentQuery=r,this.emitOnChange(),this.requestPageTransition(),this}back(){if(this.canGoBack()){this.historyIndex--;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}forward(){if(this.canGoForward()){this.historyIndex++;let{path:e,query:t}=this.parseUrl(this.history[this.historyIndex]);this.currentPath=e,this.currentQuery=t,this.emitOnChange(),this.requestPageTransition()}return this}replace(e,t){let{path:n,query:o}=this.parseUrl(e),i=this.resolvePath(n),r={...o,...t};return this.currentPath=i,this.currentQuery=r,this.historyIndex>=0?this.history[this.historyIndex]=this.buildUrl(i,r):(this.history.push(this.buildUrl(i,r)),this.historyIndex=0),this.emitOnChange(),this}clear(){return this.currentPath="",this.currentQuery={},this.history=[],this.historyIndex=-1,this.emitOnChange(),this.requestPageTransition(),this}cleanHistory(){return this.history=this.currentPath?[this.buildUrl(this.currentPath,this.currentQuery)]:[],this.historyIndex=this.currentPath?0:-1,this}parsePath(e){return e.split("/").filter(t=>t.length>0)}buildPath(e){return"/"+e.join("/")}getParentPath(e){let t=this.parsePath(e);return t.length<=1?"":this.buildPath(t.slice(0,-1))}matchPath(e,t){let n=this.parsePath(e),o=this.parsePath(t);if(n.length<o.length)return!1;for(let i=0;i<o.length;i++){let r=n[i],a=o[i];if(a!=="*"){if(a.startsWith(":"))continue;if(r!==a)return!1}}return!0}exactMatch(e,t){let n=this.parsePath(e),o=this.parsePath(t);if(n.length!==o.length)return!1;for(let i=0;i<o.length;i++){let r=n[i],a=o[i];if(a!=="*"){if(a.startsWith(":"))continue;if(r!==a)return!1}}return!0}extractParams(e,t){let n={},o=this.parsePath(e),i=this.parsePath(t);if(o.length!==i.length)return n;for(let r=0;r<i.length;r++){let a=i[r];if(a.startsWith(":")){let c=a.slice(1);n[c]=o[r]}}return n}onExitComplete(e){return this.events.on("event:router.onExitComplete",e)}onceExitComplete(e){return this.events.once("event:router.onExitComplete",e)}onPageMount(e){return this.events.on("event:router.onPageMount",e)}oncePageMount(e){return this.events.once("event:router.onPageMount",e)}onUpdate(e){return this.updateSyncHooks.add(e),{cancel:()=>{this.updateSyncHooks.delete(e)}}}emitUpdateSync(){this.updateSyncHooks.forEach(e=>e())}mount(e){if(this.mountedPaths.has(e))throw new b(`Path ${e} is already mounted. This may be caused by multiple capture segments in the same path.`);return this.mountedPaths.add(e),{cancel:()=>{this.unmount(e)}}}unmount(e){this.mountedPaths.delete(e)}mountDefaultHandler(e){if(this.defaultHandlerPaths.has(e))throw new b(`Default handler path ${e} is already mounted.`);return this.defaultHandlerPaths.add(e),{cancel:()=>{this.unmountDefaultHandler(e)}}}unmountDefaultHandler(e){this.defaultHandlerPaths.delete(e)}emitOnPageMount(){this.events.emit("event:router.onPageMount")}onRootExitComplete(e){return this.events.on("event:router.onExitComplete",e)}isActive(){return this.currentPath!==""}onChange(e){return this.events.on("event:router.onChange",e)}emitOnChange(){this.events.emit("event:router.onChange")}resolvePath(e){let t=e.split("?")[0];if(t.startsWith("/"))return t;if(t==="")return this.currentPath;let n=this.parsePath(this.currentPath),o=t.split("/"),i=[];i.push(...n);for(let r=0;r<o.length;r++){let a=o[r];a===""||a==="."||(a===".."?i.length>0&&i.pop():i.push(a))}return this.buildPath(i)}normalizePath(e){let t=e.replace(/\/\/+/g,"/").replace(/\/$/,"");return t===""?"/":(t.startsWith("/"),t)}joinPath(e,...t){let n=this.normalizePath(e),r=[n.startsWith("/")?n:"/"+n,...t.filter(a=>a.length>0)].join("/");return this.normalizePath(r)}updateHistory(){this.historyIndex>=0&&(this.history[this.historyIndex]=this.buildUrl(this.currentPath,this.currentQuery))}requestPageTransition(){let e=()=>{this.transitioning=!0,this.emitUpdateSync(),this.emitOnChange()},t=()=>{this.events.emit("event:router.onTransitionEnd"),this.transitioning=!1,this.emitUpdateSync(),this.emitOnChange(),this.events.emit("event:router.onExitComplete")};if(e(),this.isPathsUnmounting()){let n=this.events.on("event:router.onPathUnmount",()=>{this.isPathsUnmounting()||(n.cancel(),Ie(()=>{t()}))})}else Ie(()=>{t()})}registerUnmountingPath(e){this.unmountingPaths.add(e)}isPathsUnmounting(){return this.unmountingPaths.size>0}unregisterUnmountingPath(e){this.unmountingPaths.delete(e),this.events.emit("event:router.onPathUnmount")}isTransitioning(){return this.transitioning}createToken(e){return Symbol(e)}};ao.rootPath=_i;var Tt=ao,Jo=us(null);function er({children:s}){let e=w();return ls.createElement(Jo,{value:{router:e.router}},s)}function Je(){if(!Zi(Jo))throw new Error("useRouter must be used within a RouterProvider");return Zi(Jo).router}import nr from"react";import ys from"clsx";import ps,{createContext as ms,useContext as ds,useEffect as fs,useReducer as gs,useState as hs}from"react";var at=class at{constructor(){this.state={width:0,height:0,minWidth:800,minHeight:450,paused:!1,scale:0};this.events=new K().setMaxListeners(1/0);this.lockers=[];this.updater=null}update(e,t,n){this.state.width=e,this.state.height=t,this.state.scale=n,this.events.emit(at.EventTypes["event:aspectRatio.update"],e,t)}updateMin(e,t){this.state.minWidth=e,this.state.minHeight=t}lock(){let e=Symbol();return this.lockers.push(e),e}unlock(e){if(e&&!this.lockers.includes(e))throw new Error("Locker not found");return this.lockers=this.lockers.filter(t=>t!==e),this.triggerUpdate(),null}isLocked(){return!!this.lockers.length}getStyle(){return{width:`${this.state.width}px`,height:`${this.state.height}px`}}setUpdate(e){this.updater=e}pause(){this.state.paused=!0,this.events.emit(at.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(at.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(at.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(at.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(at.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};at.EventTypes={"event:aspectRatio.update":"event:aspectRatio.update","event:aspectRatio.pause":"event:aspectRatio.pause","event:aspectRatio.resume":"event:aspectRatio.resume","event:aspectRatio.requestUpdate":"event:aspectRatio.requestUpdate"};var Yo=at,Zo=ms(null);function tr({children:s}){"use client";let[e]=hs(()=>new Yo);return ps.createElement(Zo,{value:{ratio:e}},s)}function Y(){let s=ds(Zo),[,e]=gs(n=>n+1,0);if(!Zo||!s)throw new Error("useRatio must be used within a RatioProvider");let{ratio:t}=s;return fs(()=>t.onUpdate(()=>{e()}),[]),s}function Ye({children:s,className:e,style:t,ref:n,...o}){let{ratio:i}=Y(),r=i.getStyle();return nr.createElement("div",{className:ys("inset-0",e),style:{width:"100%",height:"100%",minWidth:`${i.state.minWidth}px`,minHeight:`${i.state.minHeight}px`},...o},nr.createElement("div",{style:{...r,position:"relative",...t||{}},...o||{},ref:n},s))}import Ts,{useEffect as Ss}from"react";function ze(s){let e=w(),[t,n]=Ts.useState(e.preference.getPreference(s)),o=i=>{e.preference.setPreference(s,i),n(i)};return Ss(()=>e.preference.onPreferenceChange(s,n).cancel,[s,e.preference,n]),[t,o]}import _o from"react";import co from"react";import or from"clsx";function lo({children:s,className:e,style:t,...n}){let{ratio:o}=Y(),i=w();return co.createElement(Ye,{className:or("absolute pointer-events-none w-full h-full"),style:{transform:`scale(${o.state.scale})`,transformOrigin:"left top",width:i.config.width,height:i.config.height,pointerEvents:"none"},"data-element-type":"full",...n},co.createElement("div",{className:"absolute inset-0 w-full h-full"},co.createElement("div",{className:"inset-0 w-full h-full"},co.createElement("div",{className:or("pointer-events-auto-rest",e),style:t},s))))}function bs({children:s,className:e,style:t}){return _o.createElement(_o.Fragment,null,_o.createElement(lo,{style:t,className:e,"data-element-type":"stage","data-code-source":"Stage.tsx"},s))}import ir from"clsx";import rr from"react";function uo({className:s,children:e,...t}){let{ratio:n}=Y();return rr.createElement("div",{style:{transform:`scale(${n.state.scale})`,transformOrigin:"left top"},className:ir("w-full h-full")},rr.createElement("div",{className:ir("z-20",s),...t},e))}import Hs from"clsx";import go,{useEffect as Us,useLayoutEffect as Ks,useRef as Fs,useState as Ws}from"react";import po from"react";var ei=po.createContext(null);function sr(){let s=po.useContext(ei);if(!s)throw new Error("useUIMenuContext must be used within a UIMenuContext");return s}var ti=po.createContext(null);function ar(){let s=po.useContext(ti);if(!s)throw new Error("useUIListContext must be used within a UIListContext");return s}import Ue,{useState as cr}from"react";import{motion as vs}from"motion/react";function mo({children:s,border:e="solid",color:t="red",tag:n,borderWidth:o=1,as:i="div",ref:r,...a}){let c=w(),[l,d]=cr(!1);if(!c.config.app.inspector)return Ue.createElement(i,{...a,ref:r},s);let p={...a,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{...a.style||{},outline:`${o}px ${e} ${t}`,zIndex:l?1e3:"auto"}};return Ue.createElement(i,{...p,ref:r},n&&l&&Ue.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black text-sm"},n),s)}function As({border:s="solid",color:e="red",tag:t,borderWidth:n=1,as:o="img",...i}){let r=w(),[a,c]=cr(!1);if(!r.config.app.inspector)return Ue.createElement(o,{...i});let l={...i,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{...i.style||{},outline:`${s} ${n}px ${e}`,zIndex:a?1e3:"auto"}};return Ue.createElement("div",null,Ue.createElement(o,{...l}),t&&a&&Ue.createElement("span",{className:"absolute top-0 left-0 bg-white text-black border-2 border-black"},t))}function Cs(s){return Ue.createElement(mo,{...s,as:"div"})}function xs(s){return Ue.createElement(mo,{...s,as:"span"})}function ws(s){return Ue.createElement(As,{...s,as:"img"})}function ks(s){return Ue.createElement(mo,{...s,as:"button"})}function Ps(s){return Ue.createElement(mo,{...s,as:vs.div,ref:s.ref,layout:s.layout})}var Es={Div:Cs,Span:xs,Button:ks,Img:ws,mDiv:Ps},Dt=Es;import pr from"clsx";import Rt,{useEffect as oi,useRef as Ms,useState as Gs}from"react";import{useEffect as Ds,useState as Rs}from"react";function $(s){let[e,t]=Rs(0);Ds(()=>{n()},s??[]);function n(){t(o=>o+1)}return[n,e]}import lr from"react";var ni=lr.createContext(null);function ct(){let s=lr.useContext(ni);if(!s)throw new Error("useDialogContext must be used within a DialogContext");return s}import fo,{useLayoutEffect as ur,useMemo as Ls,useState as Is}from"react";var $e=class $e{constructor(e){this.events=new K;this._forceSkipped=!1;this._idle=!1;this.config=e,this._state="pending",this.autoForwardScheduler=new In,this._count=0}get state(){return this._state}get deps(){return[this._count]}isIdle(){return this._idle}setIdle(e){this._idle=e}requestComplete(){this.state==="ended"?this.safeEmit($e.Events.complete):this.safeEmit($e.Events.requestComplete)}forceSkip(){this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit($e.Events.forceSkip))}dispatchComplete(){if(this.state==="ended"){this.config.gameState.logger.weakWarn("DialogState","Dialog is already ended. Cannot dispatch complete.");return}if(!this.events.hasListeners($e.Events.complete)){this.config.gameState.logger.weakWarn("DialogState","No listener for complete event. Cannot dispatch complete.");return}let e=this.config.gameState.game.preference;return this._state="ended",e.getPreference(q.Preferences.autoForward)&&this.scheduleAutoForward(),this.emitComplete(),this}emitComplete(){return this.safeEmit($e.Events.complete),this.emitFlush(),this}isEnded(){return this.state==="ended"}setPause(e){this.isEnded()||(e?this._state="paused":this._state="pending")}isForceSkipped(){return this._forceSkipped}tryScheduleAutoForward(){this.isEnded()&&this.scheduleAutoForward()}cancelAutoForward(){this.autoForwardScheduler.cancelTask()}emitFlush(){return this._count++,this.events.emit($e.Events.onFlush),this}onFlush(e){return this.events.on($e.Events.onFlush,e)}safeEmit(e,...t){return this.events.emit(e,...t)===0&&this.config.gameState.logger.weakWarn("DialogState",`Failed to emit event: ${e}. Target Component is not mounted.`),this}scheduleAutoForward(){let e=this.config.gameState.game.preference;!e.getPreference(q.Preferences.autoForward)||this.state!=="ended"||this.autoForwardScheduler.cancelTask().scheduleTask(()=>{this.events.emit($e.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(q.Preferences.gameSpeed))}};$e.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var De=$e;function mn({action:s,onFinished:e,useTypeEffect:t=!0,gameState:n}){let o=Ls(()=>s.sentence?.evaluate(He.getCtx({gameState:n})),[s.sentence,n]),[i]=Is(()=>new De({useTypeEffect:t,action:s,evaluatedWords:o||[],gameState:n})),r=n.game.config.dialog;return ur(()=>(n.logger.debug("NarraLeaf-React: Say","dialogState",i),i.events.on(De.Events.complete,a=>{n.logger.log("NarraLeaf-React: Say","Complete",i.isIdle()),i.isIdle()||a?e?.(!1):i.setIdle(!0)}).cancel),[i]),ur(()=>n.events.on(U.EventTypes["event:state.player.skip"],a=>{a?(i.setIdle(!0),i.forceSkip()):i.isIdle()?e?.(!0):i.forceSkip()}).cancel,[i]),fo.createElement(fo.Fragment,null,fo.createElement(ni,{value:i,key:s.id},fo.createElement(r,null)))}function*mr(s){let e=[...s];for(let t=0;t<e.length;t++){let n=e[t];if(Te.isPause(n.text)){yield Te.from(n.text);continue}for(let o=0;o<n.text.length;o++){let i=n.text[o];i===`
52
52
  `?yield`
53
53
  `:yield{text:i,config:n.config,tag:t,tag2:o,cps:n.config.cps}}}}function dr({defaultColor:s,className:e,style:t,dialog:n,...o}){let i=w(),r=i.getLiveGame().getGameState(),a=Ms(null),[c,l]=Gs(()=>n&&!n.config.useTypeEffect?g(n.config.evaluatedWords):[]),[d,p]=$();if(!n)throw new Error("Dialog state is required");oi(()=>{if(!(!n.config.action.sentence||a.current))return r.logger.info("Initializing the sentence",n,a.current),r.schedule(({onCleanup:f})=>{if(!n.config.useTypeEffect){n.dispatchComplete();return}l([]),a.current=m(),d(),a.current.onComplete(()=>{n.dispatchComplete()}),f(()=>{a.current?.timeline?.abort()})},0)},[]),oi(()=>n.events.depends([n.events.on(De.Events.requestComplete,()=>{a.current?.interact()}),n.events.on(De.Events.forceSkip,()=>{n.isEnded()||a.current?.forceSkip()})]).cancel,[n,p]),oi(()=>i.preference.events.depends([i.preference.onPreferenceChange(q.Preferences.gameSpeed,()=>{a.current?.update()}),i.preference.onPreferenceChange(q.Preferences.autoForward,()=>{a.current?.update()}),i.preference.onPreferenceChange(q.Preferences.cps,()=>{a.current?.update()})]).cancel,[]);function m(){let f=new h,A=new re(f).setGuard(r.guard),G=new Set,he=new Set,_e=new Set,Mt=mr(n.config.evaluatedWords),Ke=null,bt=[],Fe=[],pt=()=>{bt.forEach(P=>P()),bt.length=0},et=()=>{if(Fe.length!==0)return{done:!1,value:Fe.shift()};let{done:P,value:E}=Mt.next();return{done:P,value:E}},ne=P=>{let E=X=>{P(X),he.delete(E)};return he.add(E),{cancel:()=>{he.delete(E)}}},k=P=>{l(E=>{let X=E[E.length-1];return X&&X!==`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "narraleaf-react",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "A React visual novel player framework",
5
5
  "main": "./dist/main.js",
6
6
  "types": "./dist/index.d.ts",