narraleaf-react 0.8.1-beta.1 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -5,22 +5,12 @@ import { LogicAction } from "../../action/logicAction";
|
|
|
5
5
|
import { TypedAction } from "../../action/actions";
|
|
6
6
|
import { Story } from "../../elements/story";
|
|
7
7
|
import { ActionSearchOptions } from "../../types";
|
|
8
|
+
import { ActionExecutionInjection } from "../action";
|
|
8
9
|
export declare class ConditionAction<T extends typeof ConditionActionTypes[keyof typeof ConditionActionTypes] = typeof ConditionActionTypes[keyof typeof ConditionActionTypes]> extends TypedAction<ConditionActionContentType, T, Condition> {
|
|
9
10
|
static ActionTypes: {
|
|
10
11
|
readonly action: "condition:action";
|
|
11
12
|
};
|
|
12
|
-
executeAction(gameState: GameState): (
|
|
13
|
-
type: T;
|
|
14
|
-
node: import("../../action/tree/actionTree").RenderableNode | null;
|
|
15
|
-
wait?: undefined;
|
|
16
|
-
} | {
|
|
17
|
-
type: T;
|
|
18
|
-
node: null;
|
|
19
|
-
wait: {
|
|
20
|
-
type: "all";
|
|
21
|
-
stackModels: import("../stackModel").StackModel[];
|
|
22
|
-
};
|
|
23
|
-
})[];
|
|
13
|
+
executeAction(gameState: GameState, injection: ActionExecutionInjection): import("../action").ExecutedActionResult;
|
|
24
14
|
getFutureActions(story: Story, options: ActionSearchOptions): LogicAction.Actions[];
|
|
25
15
|
stringify(story: Story, seen: Set<LogicAction.Actions>, strict: boolean): string;
|
|
26
16
|
}
|
|
@@ -129,7 +129,7 @@ export declare class Gallery<Metadata extends Record<string, any>> extends Servi
|
|
|
129
129
|
* @param name - The name of the item to get the metadata of
|
|
130
130
|
* @returns The metadata of the item
|
|
131
131
|
*/
|
|
132
|
-
$get(name: string): Metadata;
|
|
132
|
+
$get(name: string): Metadata | undefined;
|
|
133
133
|
/**
|
|
134
134
|
* Set the metadata of an item
|
|
135
135
|
* @param name - The name of the item to set the metadata of
|
|
@@ -4,7 +4,7 @@ import { Chained, Proxied } from "../action/chain";
|
|
|
4
4
|
import { LambdaHandler, ActionStatements } from "../elements/type";
|
|
5
5
|
export declare class Lambda<T = any> {
|
|
6
6
|
}
|
|
7
|
-
export declare class Condition<Closed extends true | false = false> extends Actionable {
|
|
7
|
+
export declare class Condition<Closed extends true | false = false> extends Actionable<null, Condition<true | false>> {
|
|
8
8
|
/**
|
|
9
9
|
* @chainable
|
|
10
10
|
*/
|
|
@@ -24,24 +24,6 @@ export declare class Story extends Constructable<SceneAction<"scene:action">, St
|
|
|
24
24
|
* ```
|
|
25
25
|
*/
|
|
26
26
|
entry(scene: Scene): this;
|
|
27
|
-
/**
|
|
28
|
-
* Register a scene to the story
|
|
29
|
-
* @example
|
|
30
|
-
* ```typescript
|
|
31
|
-
* // register a scene
|
|
32
|
-
* const story = new Story("story");
|
|
33
|
-
* const scene1 = new Scene("scene1");
|
|
34
|
-
* const scene2 = new Scene("scene2");
|
|
35
|
-
*
|
|
36
|
-
* story.register(scene1); // Register scene1
|
|
37
|
-
*
|
|
38
|
-
* scene2.action([
|
|
39
|
-
* scene2.jump("scene1") // Jump to scene1
|
|
40
|
-
* ]);
|
|
41
|
-
* ```
|
|
42
|
-
*/
|
|
43
|
-
registerScene(name: string, scene: Scene): this;
|
|
44
|
-
registerScene(scene: Scene): this;
|
|
45
27
|
/**
|
|
46
28
|
* Register a Persistent to the story
|
|
47
29
|
*
|
package/dist/main.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
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"},
|
|
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"},dt={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"},At={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 vt(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"?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.
|
|
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 ft=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?vt(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 vC={};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
|
-
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===
|
|
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
|
|
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===dt.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===dt.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===dt.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===dt.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===dt.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===dt.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=dt;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 ve(`Sound (src: ${this.config.src}) is marked as bgm, but it is being played as a normal sound.
|
|
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 Ae=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:Ae.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:Ae.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 nt=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 nt(this.chain(),nt.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 nt(this.chain(),nt.ActionTypes.say,new y().setContent(r));return this.chain(a)}setName(e){let t=new nt(this.chain(),nt.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,gt=new jn(null);var Ve=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"?gt.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 Ae){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 Ae?t:new Ae({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 Ae?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 Ve,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 Ve,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
|
|
7
7
|
Tag must be defined in the image config`);let n=this.constructTagMap(this.config.src.groups),o=new Map,i=[];this.config.src.groups.forEach(a=>{o.set(a,null)});let r=a=>{a.forEach(c=>{let l=n.get(c);l&&o.set(l,c)})};return r(e),r(t),this.config.src.groups.forEach(a=>{let c=o.get(a);if(!c)throw new Error(`Invalid Tag Group. Tag group "${a.join(", ")}" is not resolved`);i.push(c)}),i}_mixedSrcError(){throw new Q(`Trying to mix src and tags
|
|
8
8
|
To better understand the behavior of the image, you cannot mix static src and tags in the same image. `)}_invalidSrcHandlerError(){throw new Error("Invalid src handler, If you are using tags, config.src must be a function that resolves the src from the tags. If you are using src, config.src must be a string or StaticImageData")}_invalidWearableError(e){throw new Error(`Invalid wearable
|
|
9
9
|
Wearable must be an Image with isWearable set to true
|
|
@@ -13,53 +13,53 @@ Image below violates the rule:
|
|
|
13
13
|
Tag "${i}" is conflicting with another tag
|
|
14
14
|
Error found in config.tag.defaults`);if(!n.has(i))throw new Error(`Tag not found
|
|
15
15
|
Tag "${i}" is not defined in tagDefinitions
|
|
16
|
-
Error found in config.tag.defaults`);n.get(i)?.forEach(r=>o.add(r))}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let o of n)t.set(o,n);return t}_setDarkness(e,t,n,o){return new V(e,V.ActionTypes.setDarkness,new y().setContent([t,n,o]))}};W.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",W.StateSerializer=new Se,W.DefaultUserConfig=new N({name:"(anonymous)",autoInit:!0,src:W.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...ie.DefaultTransformState.getDefaultConfig()},{position:e=>C.tryParsePosition(e)}),W.DefaultImageConfig=new N({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),W.DefaultImageState=new N({currentSrc:W.DefaultImagePlaceholder,darkness:0});var I=W;var wt=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(wt||{});import{animate as ns}from"motion/react";var Qe=class{requestAnimations(e){let t=e.map(p=>p.start),n=[],o=0,i=[],r=[],a=[];return{onUpdate:p=>(i.push(p),{cancel:()=>{let m=i.indexOf(p);m!==-1&&i.splice(m,1)}}),onComplete:p=>(r.push(p),{cancel:()=>{let m=r.indexOf(p);m!==-1&&r.splice(m,1)}}),onCanceled:p=>(a.push(p),{cancel:()=>{let m=a.indexOf(p);m!==-1&&a.splice(m,1)}}),complete:()=>{o!==e.length&&n.forEach(p=>p.complete())},start:()=>{if(n.length>0)throw new Error("Animation controllers are already started");e.forEach((p,m)=>{n.push(this.requestMotion(p,{onComplete:()=>{t[m]=p.end,i.forEach(g=>g(t)),o++,o===e.length&&r.forEach(g=>g())},onUpdate:g=>{t[m]=g,i.forEach(u=>u(t))}}))})},cancel:()=>{n.forEach(p=>p.cancel()),a.forEach(p=>p())}}}toFinalStyle(e){return e.resolve.map(t=>typeof t=="function"?t(...e.animations.map(n=>n.end)):t.resolver(...e.animations.map(n=>n.end)))}asPrev(e){return{resolver:e,key:"current"}}asTarget(e){return{resolver:e,key:"target"}}requestMotion(e,t){return ns(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Qe.AnimationType=wt;var nt=class extends Qe{_setPrevSrc(e){return this._prevSrc=e,this}_setTargetSrc(e){return this._targetSrc=e,this}_setCurrentSrc(e){return this._currentSrc=e,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(e){let t=super.requestAnimations(e);return t.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),t}asPrev(e){return super.asPrev((...t)=>D(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>D(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(S.isColor(e))return{src:I.DefaultImagePlaceholder,style:{backgroundColor:S.isRGBAColor(e)?S.RGBAColorToHex(e):e}};if(S.isImageSrc(e))return{src:S.srcToURL(e)};throw new Q("Image transition src cannot be identified, using: "+e)}};var qn=class s extends nt{constructor(t,n,o,i){super();this.prevDarkness=t;this.targetDarkness=n;this.duration=o;this.easing=i}createTask(){return{animations:[{type:0,start:this.prevDarkness,end:this.targetDarkness,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{filter:`brightness(${1-t})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new s(this.prevDarkness,this.targetDarkness,this.duration,this.easing)}};var on=class on extends M{static resolveTagSrc(e,t){if(!I.isTagSrc(e))throw e._mixedSrcError();let n=e.state.currentSrc,o=e.resolveTags(n,t);return I.getSrcFromTags(o,e.config.src.resolve)}static resolveCurrentSrc(e){if(I.isStaticSrc(e))return S.isImageSrc(e.state.currentSrc)?S.srcToURL(e.state.currentSrc):e.state.currentSrc;if(I.isTagSrc(e))return I.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===we.initWearable){let[n]=this.contentNode.getContent(),o=e.getExposedStateForce(this.callee),i=new h(r=>r);return o.createWearable(n),e.getExposedStateAsync(n,r=>{r.initDisplayable(()=>{i.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{o.disposeWearable(r)},[n]),i}else if(this.type===we.setSrc){let n=this.contentNode.getContent()[0];if(S.isColor(n)&&!this.callee.config.isBackground)throw new Q("Color src is not allowed for non-background image");let o=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.currentSrc=i},[o]),e.stage.update(),super.executeAction(e,t)}else{if(this.type===we.flush)return super.executeAction(e,t);if(this.type===we.setAppearance){let[n,o]=this.contentNode.getContent();if(!I.isTagSrc(this.callee))throw this.callee._mixedSrcError();let i=this.callee.state.currentSrc,r=this.callee.resolveTags(i,n),a=[...i],c=I.getSrcFromTags(r,this.callee.config.src.resolve),l=()=>{this.callee.state.currentSrc=a};if(e.logger.debug("Image - Set Appearance",r,c),o){let d=new h(u=>u).registerSkipController(new L(()=>super.executeAction(e,t)));o._setPrevSrc(on.resolveCurrentSrc(this.callee))._setTargetSrc(c);let m=e.getExposedStateForce(this.callee).applyTransition(o,()=>{this.callee.state.currentSrc=r,d.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(d).attachChild(m);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},l,[]),d}return this.callee.state.currentSrc=r,e.actionHistory.push({action:this,stackModel:t.stackModel},l),super.executeAction(e,t)}else if(this.type===we.setDarkness){let[n,o,i]=this.contentNode.getContent(),r=this.callee.state.darkness,a=()=>{this.callee.state.darkness=r},c=e.getExposedStateForce(this.callee);if(o&&i){let l=on.resolveCurrentSrc(this.callee),d=new h(u=>u),p=new qn(r,n,o,i)._setPrevSrc(l)._setTargetSrc(l),m=c.applyTransition(p,()=>{this.callee.state.darkness=n,d.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(d).attachChild(m);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},()=>{d.isSettled()||d.abort(),m.abort(),a()}),d}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};on.ActionTypes=we;var V=on;var ot=class ot extends M{static handleSceneInit(e,t,n,o){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,i=>{ot.initBackgroundMusic(e,i),o.resolve(t),n.logger.debug("Scene Action","Scene init")}),o)}static initBackgroundMusic(e,t){e.state.backgroundMusic&&t.setBackgroundMusic(e.state.backgroundMusic,e.config.backgroundMusicFade)}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new Q("Scene not found when creating snapshot (scene: "+e.getId()+")");return{state:e.toData(),local:e.local.getNamespace(t.getStorable()).toData(),element:t.createElementSnapshot(n),background:e.background.toData()}}static restoreSceneSnapshot(e,t){let n=e.element.scene,o=t.findElementByScene(n);o&&t.removeElement(o);let i=t.fromElementSnapshot(e.element);t.addElement(i),n.local.getNamespace(t.getStorable()).load(e.local),e.state&&n.fromData(e.state),e.background&&n.background.fromData(e.background)}applyTransition(e,t,n){let o=new h().registerSkipController(new L(()=>(e.logger.info("Background Transition","Skipped"),super.executeAction(e,n))));return e.getExposedStateForce(this.callee.background).applyTransition(t,()=>{o.resolve(super.executeAction(e,n))}),e.timelines.attachTimeline(o),o}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}executeAction(e,t){if(this.type===_.action)return super.executeAction(e,t);if(this.is(ot,"scene:init")){let n=new h(r=>r),o=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:o},()=>{this.exit(e)},[]);let i={type:this.type,node:this.contentNode.getChild()};return ot.handleSceneInit(this.callee,i,e,h.forward(n,i))}else if(this.type===_.exit){let n=ot.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},o=>{let i=new h(r=>r);e.timelines.attachTimeline(i),ot.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,i),ot.restoreSceneSnapshot(o,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===_.jumpTo){let n=this.contentNode.getContent()[0],o=e.getStory().getScene(n);if(!o)throw this._sceneNotFoundError(this.getSceneName(n));let i=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let[c]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,c)},[i]);let r=o.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:r}),null}else if(this.type===_.setBackgroundMusic){let[n,o]=this.contentNode.getContent(),i=this.callee,r=e.getExposedStateForce(i),a=i.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{c&&r.setBackgroundMusic(c,0)},[a]),r.setBackgroundMusic(n,o||0),this.callee.state.backgroundMusic=n,super.executeAction(e,t)}else{if(this.type===_.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===_.transitionToScene){let[n,o,i]=this.contentNode.getContent();return n._setPrevSrc(V.resolveCurrentSrc(this.callee.background)),o?n._setTargetSrc(V.resolveCurrentSrc(o.background)):i&&n._setTargetSrc(i),this.applyTransition(e,n,t)}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===_.jumpTo&&t.allowFutureScene!==!1){let o=this.contentNode.getContent()[0],i=e.getScene(o,!0);i.isSceneRootConstructed()||i.constructSceneRoot(e);let r=e.getScene(o,!0).getSceneRoot()?.contentNode;return r?.action?[r.action]:[]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new Q(`Scene with name ${e} not found
|
|
16
|
+
Error found in config.tag.defaults`);n.get(i)?.forEach(r=>o.add(r))}}return this}constructTagMap(e){let t=new Map;for(let n of e)for(let o of n)t.set(o,n);return t}_setDarkness(e,t,n,o){return new V(e,V.ActionTypes.setDarkness,new y().setContent([t,n,o]))}};W.DefaultImagePlaceholder="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='1' height='1'></svg>",W.StateSerializer=new Se,W.DefaultUserConfig=new N({name:"(anonymous)",autoInit:!0,src:W.DefaultImagePlaceholder,autoFit:!1,layer:void 0,...ie.DefaultTransformState.getDefaultConfig()},{position:e=>C.tryParsePosition(e)}),W.DefaultImageConfig=new N({wearables:[],isWearable:!1,name:"(anonymous)",autoInit:!0,src:null,autoFit:!1,layer:void 0,isBackground:!1}),W.DefaultImageState=new N({currentSrc:W.DefaultImagePlaceholder,darkness:0});var I=W;var wt=(t=>(t[t.Number=0]="Number",t[t.HexColor=1]="HexColor",t))(wt||{});import{animate as ns}from"motion/react";var Qe=class{requestAnimations(e){let t=e.map(p=>p.start),n=[],o=0,i=[],r=[],a=[];return{onUpdate:p=>(i.push(p),{cancel:()=>{let m=i.indexOf(p);m!==-1&&i.splice(m,1)}}),onComplete:p=>(r.push(p),{cancel:()=>{let m=r.indexOf(p);m!==-1&&r.splice(m,1)}}),onCanceled:p=>(a.push(p),{cancel:()=>{let m=a.indexOf(p);m!==-1&&a.splice(m,1)}}),complete:()=>{o!==e.length&&n.forEach(p=>p.complete())},start:()=>{if(n.length>0)throw new Error("Animation controllers are already started");e.forEach((p,m)=>{n.push(this.requestMotion(p,{onComplete:()=>{t[m]=p.end,i.forEach(g=>g(t)),o++,o===e.length&&r.forEach(g=>g())},onUpdate:g=>{t[m]=g,i.forEach(u=>u(t))}}))})},cancel:()=>{n.forEach(p=>p.cancel()),a.forEach(p=>p())}}}toFinalStyle(e){return e.resolve.map(t=>typeof t=="function"?t(...e.animations.map(n=>n.end)):t.resolver(...e.animations.map(n=>n.end)))}asPrev(e){return{resolver:e,key:"current"}}asTarget(e){return{resolver:e,key:"target"}}requestMotion(e,t){return ns(e.start,e.end,{duration:e.duration/1e3,onUpdate:n=>{t.onUpdate&&t.onUpdate(n)},onComplete:()=>{t.onComplete&&t.onComplete()},ease:e.ease})}};Qe.AnimationType=wt;var ot=class extends Qe{_setPrevSrc(e){return this._prevSrc=e,this}_setTargetSrc(e){return this._targetSrc=e,this}_setCurrentSrc(e){return this._currentSrc=e,this}_getPrevSrc(){return this._prevSrc}_getTargetSrc(){return this._targetSrc}_getCurrentSrc(){return this._currentSrc}requestAnimations(e){let t=super.requestAnimations(e);return t.onComplete(()=>{this._setCurrentSrc(this._getTargetSrc())}),t}asPrev(e){return super.asPrev((...t)=>D(e(...t),this._srcToProps(this._prevSrc)))}asTarget(e){return super.asTarget((...t)=>D(e(...t),this._srcToProps(this._targetSrc)))}_srcToProps(e){if(S.isColor(e))return{src:I.DefaultImagePlaceholder,style:{backgroundColor:S.isRGBAColor(e)?S.RGBAColorToHex(e):e}};if(S.isImageSrc(e))return{src:S.srcToURL(e)};throw new Q("Image transition src cannot be identified, using: "+e)}};var qn=class s extends ot{constructor(t,n,o,i){super();this.prevDarkness=t;this.targetDarkness=n;this.duration=o;this.easing=i}createTask(){return{animations:[{type:0,start:this.prevDarkness,end:this.targetDarkness,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{filter:`brightness(${1-t})`}})),this.asPrev(()=>({style:{opacity:0},height:0,width:0}))]}}copy(){return new s(this.prevDarkness,this.targetDarkness,this.duration,this.easing)}};var on=class on extends M{static resolveTagSrc(e,t){if(!I.isTagSrc(e))throw e._mixedSrcError();let n=e.state.currentSrc,o=e.resolveTags(n,t);return I.getSrcFromTags(o,e.config.src.resolve)}static resolveCurrentSrc(e){if(I.isStaticSrc(e))return S.isImageSrc(e.state.currentSrc)?S.srcToURL(e.state.currentSrc):e.state.currentSrc;if(I.isTagSrc(e))return I.getSrcFromTags(e.state.currentSrc,e.config.src.resolve);throw e._mixedSrcError()}executeAction(e,t){if(this.type===we.initWearable){let[n]=this.contentNode.getContent(),o=e.getExposedStateForce(this.callee),i=new h(r=>r);return o.createWearable(n),e.getExposedStateAsync(n,r=>{r.initDisplayable(()=>{i.resolve(super.executeAction(e,t))})}),e.actionHistory.push({action:this,stackModel:t.stackModel},r=>{o.disposeWearable(r)},[n]),i}else if(this.type===we.setSrc){let n=this.contentNode.getContent()[0];if(S.isColor(n)&&!this.callee.config.isBackground)throw new Q("Color src is not allowed for non-background image");let o=this.callee.state.currentSrc;return this.callee.state.currentSrc=n,e.logger.debug("Image Set Src",n),e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.currentSrc=i},[o]),e.stage.update(),super.executeAction(e,t)}else{if(this.type===we.flush)return super.executeAction(e,t);if(this.type===we.setAppearance){let[n,o]=this.contentNode.getContent();if(!I.isTagSrc(this.callee))throw this.callee._mixedSrcError();let i=this.callee.state.currentSrc,r=this.callee.resolveTags(i,n),a=[...i],c=I.getSrcFromTags(r,this.callee.config.src.resolve),l=()=>{this.callee.state.currentSrc=a};if(e.logger.debug("Image - Set Appearance",r,c),o){let d=new h(u=>u).registerSkipController(new L(()=>super.executeAction(e,t)));o._setPrevSrc(on.resolveCurrentSrc(this.callee))._setTargetSrc(c);let m=e.getExposedStateForce(this.callee).applyTransition(o,()=>{this.callee.state.currentSrc=r,d.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(d).attachChild(m);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},l,[]),d}return this.callee.state.currentSrc=r,e.actionHistory.push({action:this,stackModel:t.stackModel},l),super.executeAction(e,t)}else if(this.type===we.setDarkness){let[n,o,i]=this.contentNode.getContent(),r=this.callee.state.darkness,a=()=>{this.callee.state.darkness=r},c=e.getExposedStateForce(this.callee);if(o&&i){let l=on.resolveCurrentSrc(this.callee),d=new h(u=>u),p=new qn(r,n,o,i)._setPrevSrc(l)._setTargetSrc(l),m=c.applyTransition(p,()=>{this.callee.state.darkness=n,d.resolve(super.executeAction(e,t))}),g=e.timelines.attachTimeline(d).attachChild(m);return e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:g},()=>{d.isSettled()||d.abort(),m.abort(),a()}),d}return this.callee.state.darkness=n,e.actionHistory.push({action:this,stackModel:t.stackModel},a),c.updateStyleSync(),super.executeAction(e,t)}}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("ImageAction")}};on.ActionTypes=we;var V=on;var it=class it extends M{static handleSceneInit(e,t,n,o){return n.isSceneActive(e)?t:(n.registerSrcManager(e.srcManager).addScene(e).flush(),e.local.init(n.getStorable()),n.getExposedStateAsync(e,i=>{it.initBackgroundMusic(e,i),o.resolve(t),n.logger.debug("Scene Action","Scene init")}),o)}static initBackgroundMusic(e,t){e.state.backgroundMusic&&t.setBackgroundMusic(e.state.backgroundMusic,e.config.backgroundMusicFade)}static createSceneSnapshot(e,t){let n=t.findElementByScene(e);if(!n)throw new Q("Scene not found when creating snapshot (scene: "+e.getId()+")");return{state:e.toData(),local:e.local.getNamespace(t.getStorable()).toData(),element:t.createElementSnapshot(n),background:e.background.toData()}}static restoreSceneSnapshot(e,t){let n=e.element.scene,o=t.findElementByScene(n);o&&t.removeElement(o);let i=t.fromElementSnapshot(e.element);t.addElement(i),n.local.getNamespace(t.getStorable()).load(e.local),e.state&&n.fromData(e.state),e.background&&n.background.fromData(e.background)}applyTransition(e,t,n){let o=new h().registerSkipController(new L(()=>(e.logger.info("Background Transition","Skipped"),super.executeAction(e,n))));return e.getExposedStateForce(this.callee.background).applyTransition(t,()=>{o.resolve(super.executeAction(e,n))}),e.timelines.attachTimeline(o),o}exit(e){e.offSrcManager(this.callee.srcManager).removeScene(this.callee),this.callee.state.backgroundImage.reset()}executeAction(e,t){if(this.type===_.action)return super.executeAction(e,t);if(this.is(it,"scene:init")){let n=new h(r=>r),o=e.timelines.attachTimeline(n);e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:o},()=>{this.exit(e)},[]);let i={type:this.type,node:this.contentNode.getChild()};return it.handleSceneInit(this.callee,i,e,h.forward(n,i))}else if(this.type===_.exit){let n=it.createSceneSnapshot(this.callee,e);return e.actionHistory.push({action:this,stackModel:t.stackModel},o=>{let i=new h(r=>r);e.timelines.attachTimeline(i),it.handleSceneInit(this.callee,{type:this.type,node:this.contentNode.getChild()},e,i),it.restoreSceneSnapshot(o,e)},[n]),e.getStorable().removeNamespace(this.callee.local.getNamespaceName()),this.exit(e),super.executeAction(e,t)}else if(this.type===_.jumpTo){let n=this.contentNode.getContent()[0],o=e.getStory().getScene(n);if(!o)throw this._sceneNotFoundError(this.getSceneName(n));let i=e.getLiveGame().getStackModelForce().serialize();e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{let[c]=e.getLiveGame().constructMaps();e.getLiveGame().getStackModelForce().deserialize(a,c)},[i]);let r=o.getSceneRoot().contentNode;return e.getLiveGame().clearMainStack().getStackModelForce().push({type:this.type,node:r}),null}else if(this.type===_.setBackgroundMusic){let[n,o]=this.contentNode.getContent(),i=this.callee,r=e.getExposedStateForce(i),a=i.state.backgroundMusic;return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{c&&r.setBackgroundMusic(c,0)},[a]),r.setBackgroundMusic(n,o||0),this.callee.state.backgroundMusic=n,super.executeAction(e,t)}else{if(this.type===_.preUnmount)return this.callee.events.emit("event:scene.preUnmount"),super.executeAction(e,t);if(this.type===_.transitionToScene){let[n,o,i]=this.contentNode.getContent();return n._setPrevSrc(V.resolveCurrentSrc(this.callee.background)),o?n._setTargetSrc(V.resolveCurrentSrc(o.background)):i&&n._setTargetSrc(i),this.applyTransition(e,n,t)}}throw new Error("Unknown scene action type: "+this.type)}getFutureActions(e,t={}){if(this.type===_.jumpTo&&t.allowFutureScene!==!1){let o=this.contentNode.getContent()[0],i=e.getScene(o,!0);i.isSceneRootConstructed()||i.constructSceneRoot(e);let r=e.getScene(o,!0).getSceneRoot()?.contentNode;return r?.action?[r.action]:[]}let n=this.contentNode.getChild()?.action;return n?[n]:[]}_sceneNotFoundError(e){return new Q(`Scene with name ${e} not found
|
|
17
17
|
Make sure you have registered the scene using story.register
|
|
18
18
|
Action: (id: ${this.getId()}) ${this.type}
|
|
19
|
-
At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===_.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[o]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${o.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};
|
|
19
|
+
At: ${this.__stack}`)}getSceneName(e){return typeof e=="string"?e:e.config.name}stringify(e,t,n){if(this.type===_.jumpTo){if(t.has(this))return super.stringifyWithContent("Scene","[[recursive]]");t.add(this);let[o]=this.contentNode.getContent();return super.stringifyWithContent("Scene",`jumpTo {${o.stringify(e,t,n)}}`)}return super.stringifyWithName("SceneAction")}};it.ActionTypes=_;var se=it;var Vo=class s{static isHexString(e){return typeof e!="string"?!1:/^#[0-9A-F]{6}$/i.test(e)}static fromHex(e){let t=e.slice(1),n=parseInt(t.slice(0,2),16),o=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16),r=t.length===8?parseInt(t.slice(6,8),16)/255:1;return new s(n,o,i,r)}constructor(e,t,n,o=1){this.r=e,this.g=t,this.b=n,this.a=o}toString(){return`rgba(${this.r}, ${this.g}, ${this.b}, ${this.a})`}toHex(){return"#"+this.r.toString(16)+this.g.toString(16)+this.b.toString(16)}},ze=class ze{static srcToURL(e){return typeof e=="string"?e:e.src}static staticImageDataToSrc(e){return typeof e=="string"?e:e.src}static isStaticImageData(e){return e?.src!==void 0&&typeof e.src=="string"}static isExternalSrc(e){return e.startsWith("http://")||e.startsWith("https://")}static isImageSrc(e){return typeof e=="string"&&!this.isColor(e)||ze.isStaticImageData(e)}static isImageURL(e){return typeof e=="string"&&!this.isColor(e)}static isColor(e){return ze.isHexString(e)||ze.isNamedColor(e)||ze.isRGBAColor(e)}static isNamedColor(e){return Ki(e)}static isRGBAColor(e){return e&&typeof e=="object"&&"r"in e&&"g"in e&&"b"in e}static RGBAColorToHex(e){let t=e.r.toString(16).padStart(2,"0"),n=e.g.toString(16).padStart(2,"0"),o=e.b.toString(16).padStart(2,"0"),i=e.a?Math.round(e.a*255).toString(16).padStart(2,"0"):"";return`#${t}${n}${o}${i}`}static colorToString(e){if(ze.isHexString(e))return e;if(ze.isNamedColor(e))return e;if(ze.isRGBAColor(e))return ze.RGBAColorToHex(e);throw new Error("Unknown color type")}static isHexString(e){return typeof e!="string"?!1:/^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{4}|[0-9A-F]{8})$/i.test(e)}static toBackgroundSrc(e){return typeof e=="string"?e:e.src}static isDataURI(e){return e.startsWith("data:")}static offset(e,t,n={invertX:!1,invertY:!1}){let[o,i]=e,[r,a]=t,c=this.calc(o,r),l=this.calc(i,a),d=n.invertX?{right:c}:{left:c},p=n.invertY?{bottom:l}:{top:l};return{left:"auto",right:"auto",top:"auto",bottom:"auto",...d,...p}}static calc(e,t){let n=typeof e=="string"?e:`${e}px`;if(t===void 0)return`calc(${n} + 0px)`;let o=typeof t=="string"?"+":t<0?"-":"+",i=typeof t=="string"?t:`${Math.abs(t)}px`;return`calc(${n} ${o} ${i})`}static formatLength(e){return typeof e=="number"?`${e}px`:e}static toPixel(e){return typeof e=="number"?e:parseFloat(e)}};ze.RGBColor=Vo;var S=ze,zo=class s extends Error{static isUseError(e){return e instanceof s}constructor(e,t,n="UseError"){super(e),this.props=t,this.name=n}},ve=class s extends zo{static isWarning(e){return e instanceof s}constructor(e,t){super(e,{info:t},"StaticScriptWarning")}},Qn=class{constructor(e){this.scene=e}run(e){let t=new Map,n=new Map,o=[],i=new Set,r=this.scene.getAllChildren(e,this.scene.getSceneRoot());if(!r.length)return null;for(o.push(r[0]);o.length;){let a=o.shift();this.checkAction(e,a,{imageStates:t,scenes:n},i);let c=a.contentNode.getChild();c&&c.action&&o.push(c.action)}return t}checkAction(e,t,{imageStates:n,scenes:o},i){if(t instanceof V)n.has(t.callee)||n.set(t.callee,{isDisposed:!1,usedExternalSrc:!1}),this.checkImage(n.get(t.callee),t);else if(t instanceof se){let r=t.callee;if(o.has(r.config.name)){if(o.get(r.config.name)!==r){let a=`Scene with name: ${r.config.name} is duplicated
|
|
20
20
|
Scene: ${r.config.name}
|
|
21
21
|
|
|
22
|
-
At: ${t.__stack}`;throw new
|
|
22
|
+
At: ${t.__stack}`;throw new ve(a)}}else o.set(r.config.name,r);if(t.type===_.jumpTo){let a=t.contentNode.getContent()[0],c=e.getScene(a,!0);if(i.has(c))return;i.add(c)}}}checkImage(e,t){if(t.type===we.setSrc){let o=t.contentNode.getContent()[0];S.isImageURL(o)&&S.isExternalSrc(o)&&(e.usedExternalSrc=!0)}}},Q=class s extends Error{static toMessage(e,t){let n=[];return n.push(...Array.isArray(e)?e:[e]),t&&n.push(...Array.isArray(t)?t.map(s.getActionTrace):[s.getActionTrace(t)]),n.join("")}static getActionTrace(e){return`
|
|
23
23
|
Using action (id: ${e.getId()})
|
|
24
|
-
at: ${e.__stack}`}constructor(e,t){super(s.toMessage(e,t)),this.name="RuntimeScriptError"}},b=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},ge=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function os(s,e){return H.color(s,e)}function is(s){return H.bold(s)}function rs(s){return H.italic(s)}var
|
|
25
|
-
You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:ue.isLambda(t)?t:new ue(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new
|
|
26
|
-
You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let o={gameState:n};if(t.If.condition?.evaluate(o)?.value)return t.If.action||null;for(let r of t.ElseIf)if(r.condition?.evaluate(o)?.value)return r.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(
|
|
27
|
-
This should not happen, please report this issue to the developers`);return this._element.state}};var Xn=class s extends rn{constructor(t,n,o){super();this.textSize=t;this.duration=n;this.easing=o}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.textSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{fontSize:`${t}px`}}))]}}copy(){return new s(this.textSize,this.duration,this.easing)}};var xe=class xe extends qe{constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,o=xe.DefaultUserConfig.create(n),i=xe.DefaultTextConfig.create(o.get());this.userConfig=o,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(o)}setText(e){let t=this.chain(),n=new ht(t,ht.ActionTypes.setText,new y().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new F({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new
|
|
24
|
+
at: ${e.__stack}`}constructor(e,t){super(s.toMessage(e,t)),this.name="RuntimeScriptError"}},b=class extends Error{constructor(e){super(e),this.name="RuntimeGameError"}},ge=class extends Error{constructor(e){super(e),this.name="RuntimeInternalError"}};function os(s,e){return H.color(s,e)}function is(s){return H.bold(s)}function rs(s){return H.italic(s)}var Xe=class extends M{executeAction(e,t){let n=this.callee.evaluate(this.contentNode.getContent(),{gameState:e});return n?.length?[{type:this.type,node:this.contentNode.getChild()},{type:this.type,node:n[0].contentNode}]:super.executeAction(e,t)}getFutureActions(e,t){return[...this.callee._getFutureActions(),...super.getFutureActions(e,t)]}stringify(e,t,n){let o=this.contentNode.getContent(),i=r=>{let a=r.condition?n?r.condition.toString():"Lambda(unknown)":"null",c=r.action?r.action.map(l=>l.stringify(e,t,n)).join(";"):"null";return`(${a}) {${c}}`};return super.stringifyWithContent("Condition",`if ${i(o.If)} ${o.ElseIf.length>0?`else if ${o.ElseIf.map(i).join(";")} `:""}${o.Else?`else {${i(o.Else)}}`:""}`)}};Xe.ActionTypes=Di;var ue=class s{static isLambda(e){return e instanceof s&&"handler"in e}static from(e){return s.isLambda(e)?e:new s(e)}constructor(e){this.handler=e}evaluate({gameState:e}){return{value:this.handler(this.getCtx({gameState:e}))}}getCtx({gameState:e}){return{gameState:e,game:e.game,liveGame:e.game.getLiveGame(),storable:e.game.getLiveGame().getStorable()}}toString(){return`Lambda(${this.handler.toString()})`}},$o=class s extends j{constructor(){super();this.conditions={If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static getInitialState(){return{If:{condition:null,action:null},ElseIf:[],Else:{action:null}}}static If(t,n){return new s().createIfCondition(t,n)}ElseIf(t,n){if(this.conditions.Else.action)throw new ve(`ELSE condition already set
|
|
25
|
+
You are trying to set an ELSE-IF condition after an ELSE condition`);return this.conditions.ElseIf.push({condition:ue.isLambda(t)?t:new ue(t),action:this.construct(Array.isArray(n)?n:[n])}),this.chain()}Else(t){if(this.conditions.Else.action)throw new ve(`ELSE condition already set
|
|
26
|
+
You are trying to set multiple ELSE conditions for the same condition`);return this.conditions.Else.action=this.construct(Array.isArray(t)?t:[t]),this.chain()}evaluate(t,{gameState:n}){let o={gameState:n};if(t.If.condition?.evaluate(o)?.value)return t.If.action||null;for(let r of t.ElseIf)if(r.condition?.evaluate(o)?.value)return r.action||null;return t.Else.action||null}fromChained(t){return[Reflect.construct(Xe,[this,Xe.ActionTypes.action,new y().setContent(t.conditions)])]}construct(t,n,o){let i=this.narrativeToActions(t);for(let r=0;r<i.length;r++){let a=i[r].contentNode,c=i[r+1]?.contentNode;c&&a.setChild(c),r===i.length-1&&n&&a.setChild(n),r===0&&o&&o.setChild(a)}return i}_getFutureActions(){return de.toActions([this.conditions.If.action?.[0]||[],...this.conditions.ElseIf.flatMap(t=>t.action?.[0]||[]),this.conditions.Else.action?.[0]||[]])}createIfCondition(t,n){this.conditions.If.condition=t instanceof ue?t:new ue(t),this.conditions.If.action=this.construct(n);let o=this.chain(),i=new Xe(o,Xe.ActionTypes.action,new y().setContent(this.conditions));return o.chain(i)}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?gt.say(n).getActions():de.toActions([n]))}};var kt=class extends M{executeAction(e,t){let n=new h().registerSkipController(new L(()=>{a.cancel()})),o=e.timelines.attachTimeline(n),i=this.contentNode.getContent(),r=null,a=e.createMenu(i,l=>{let d=e.getLiveGame().createStackModel([{type:this.type,node:l.action[0]?.contentNode??null}]);n.resolve({type:this.type,node:null,wait:{type:"all",stackModels:[d]}}),r=()=>{d.reset()},e.gameHistory.updateByToken(c,p=>{p&&p.element.type==="menu"&&(p.element.selected=l.evaluated,p.isPending=!1)})}),{id:c}=e.actionHistory.push({action:this,stackModel:t.stackModel,timeline:o},()=>{a.cancel(),r?.()});return e.gameHistory.push({token:c,action:this,element:{type:"menu",text:a.prompt,selected:null},isPending:!0}),[{type:this.type,node:this.contentNode.getChild()},n]}getFutureActions(e,t){let n=this.contentNode.getContent();return[...this.callee._getFutureActions(n.choices),...super.getFutureActions(e,t)]}stringify(e,t,n){let o=this.contentNode.getContent(),i=o.choices.map(r=>`{${r.action.map(c=>c.stringify(e,t,n)).join(";")}}`);return super.stringifyWithContent("Menu",`(${o.prompt}) {[${i.join(",")}]}`)}};kt.ActionTypes=Li;var Pt=class Pt extends j{constructor(t,n={}){super();this.choices=[];this.prompt=te.isSentence(t)?t:t===null?null:new te(t),this.config=D(Pt.defaultConfig,n)}static prompt(t,n={}){return new Pt(t!==void 0?t:null,n)}static choose(t,n){return new Pt(null,{}).choose(t,n)}choose(t,n){let o=this.chain();return te.isSentence(t)&&n?o.choices.push({prompt:te.toSentence(t),action:this.narrativeToActions(n)}):(H.isWord(t)||Array.isArray(t)||typeof t=="string")&&n?o.choices.push({prompt:te.toSentence(t),action:this.narrativeToActions(n)}):typeof t=="object"&&"prompt"in t&&"action"in t?o.choices.push({prompt:te.toSentence(t.prompt),action:this.narrativeToActions(t.action)}):console.warn("No valid choice added to menu, ",{arg0:t,arg1:n}),o}fromChained(t){return[new kt(this.chain(),kt.ActionTypes.action,new y().setContent({prompt:this.prompt,choices:t.constructChoices()}))]}_getFutureActions(t){return t.map(n=>n.action[0]||null).filter(n=>n!==null)}narrativeToActions(t){return this.constructNodes(t.flatMap(n=>typeof n=="string"?gt.say(n).getActions():de.toActions([n])))}constructNodes(t,n,o){for(let i=0;i<t.length;i++){let r=t[i].contentNode,a=t[i+1]?.contentNode;a&&r.setChild(a),i===this.choices.length-1&&n&&r.setChild(n),i===0&&o&&o.setChild(r)}return t}constructChoices(){return this.choices.map(t=>({action:this.constructNodes(t.action),prompt:t.prompt}))}};Pt.defaultConfig={},Pt.targetAction=kt;var Bo=Pt;var Ut=class extends Ht{constructor(){super()}fromChained(e){return e.getActions()}forEachChild(e,t,n,o={}){let i=new Set,r=[];for(Array.isArray(t)?r.push(...t):r.push(t);r.length;){let a=r.shift();if(i.has(a))continue;i.add(a),n(a);let c=a.getFutureActions(e,o).filter(l=>!i.has(l));r.push(...c)}}getAllChildren(e,t,n={}){let o=[];return this.forEachChild(e,t,i=>o.push(i),n),o}getAllChildrenMap(e,t){let n=new Map;return this.forEachChild(e,t,o=>n.set(o.getId(),o)),n}getAllElementMap(e,t,n={}){let o=new Map;return this.forEachChild(e,t,i=>o.set(i.callee.getId(),i.callee),n),o}getAllChildrenElements(e,t,n={}){return Array.from(new Set(this.getAllChildren(e,t,n).map(o=>o.callee)))}toData(){return null}constructNodes(e,t){for(let n=0;n<e.length;n++){let o=e[n];n===0&&t?t.setChild(o.contentNode):n>0&&e[n-1].contentNode?.setChild(o.contentNode)}return e.length?e[0].contentNode:null}};var ht=class extends M{executeAction(e,t){let n={action:this,stackModel:t.stackModel};if(this.type===Ln.setText){let o=this.callee.state.text;return this.callee.state.text=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,i=>{this.callee.state.text=i},[o]),super.executeAction(e,t)}else if(this.type===Ln.setFontSize){let o=this.callee.state.fontSize;return this.callee.state.fontSize=this.contentNode.getContent()[0],e.getExposedStateForce(this.callee).flush(),e.actionHistory.push(n,i=>{this.callee.state.fontSize=i},[o]),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("TextAction")}};ht.ActionTypes=Ln;var rn=class extends Qe{_setElement(e){return this._element=e,this}getTextState(){if(this._element===void 0)throw new b(`Trying to access text state, but element is not set
|
|
27
|
+
This should not happen, please report this issue to the developers`);return this._element.state}};var Xn=class s extends rn{constructor(t,n,o){super();this.textSize=t;this.duration=n;this.easing=o}createTask(){return{animations:[{type:0,start:this.getTextState().fontSize,end:this.textSize,duration:this.duration,ease:this.easing}],resolve:[this.asTarget(t=>({style:{fontSize:`${t}px`}}))]}}copy(){return new s(this.textSize,this.duration,this.easing)}};var xe=class xe extends qe{constructor(e,t={}){super();let n=typeof e=="string"?{...t,text:e}:e,o=xe.DefaultUserConfig.create(n),i=xe.DefaultTextConfig.create(o.get());this.userConfig=o,this.config=i.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(o)}setText(e){let t=this.chain(),n=new ht(t,ht.ActionTypes.setText,new y().setContent([e]));return t.chain(n)}setFontColor(e,t=0,n){return this.transform(new F({fontColor:e},{duration:t,ease:n}))}setFontSize(e,t=0,n){return this.combineActions(new Ve,o=>{if(t){let r=new Xn(e,t,n);o.chain(this._applyTransition(o,r))}let i=new ht(o,ht.ActionTypes.setFontSize,new y().setContent([e]));return o.chain(i)})}useLayer(e){return this.userConfig.get().layer=e,Object.assign(this.config,{layer:e}),this}toData(){return{state:xe.StateSerializer.serialize(this.state),transformState:this.transformState.serialize()}}fromData(e){return this.state=xe.StateSerializer.deserialize(e.state),this.transformState=ie.deserialize(e.transformState),this}_init(e){return new le(this.chain(),ae.init,new y().setContent([e||null,this.config.layer||null]))}reset(){this.state=this.getInitialState(),this.transformState=this.getInitialTransformState(this.userConfig)}getInitialTransformState(e){let[t]=e.extract(xe.DefaultTextTransformState.keys());return new ie(xe.DefaultTextTransformState.create(t.get()).get())}_applyTransition(e,t){return new le(e,ae.applyTransition,new y().setContent([t,n=>n._setElement(this)]))}getInitialState(){return xe.DefaultTextState.create({fontSize:this.userConfig.get().fontSize,text:this.userConfig.get().text}).get()}};xe.DefaultUserConfig=new N({alignX:"center",alignY:"center",className:"",fontSize:16,fontColor:"#000000",text:""}),xe.DefaultTextConfig=new N({alignX:"center",alignY:"center",className:"",layer:void 0}),xe.DefaultTextState=new N({fontSize:16,display:!1,text:""}),xe.DefaultTextTransformState=new N({fontColor:"#000000",...ie.DefaultTransformState.getDefaultConfig()}),xe.StateSerializer=new Se;var Et=xe;var sn=class sn extends M{executeAction(e,t){let n=this;if(n.is(sn,"persistent:set")){let[o,i]=n.contentNode.getContent(),r=e.getStorable().getNamespace(n.callee.getNamespaceName()),a=r.get(o);if(typeof i=="function"){let c=r.get(o);r.set(o,i(c))}else r.set(o,i);return e.actionHistory.push({action:this,stackModel:t.stackModel},c=>{r.set(o,c)},[a]),super.executeAction(e,t)}else if(n.is(sn,"persistent:assign")){let[o]=n.contentNode.getContent(),i=e.getStorable().getNamespace(n.callee.getNamespaceName()),r={};return Object.keys(o).forEach(a=>{r[a]=i.get(a),i.set(a,o[a])}),e.actionHistory.push({action:this,stackModel:t.stackModel},a=>{Object.keys(a).forEach(c=>{i.set(c,a[c])})},[r]),super.executeAction(e,t)}throw this.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("PersistentAction")}};sn.ActionTypes=Xt;var Jn=sn;var rt=class s{static isSerializable(e){return["number","string","boolean"].includes(typeof e)||e instanceof Date||e==null?!0:Array.isArray(e)?e.every(s.isSerializable):typeof e=="object"?Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(s.isSerializable):!1}constructor(e,t,n){this.name=e,this.key=n||e,this.content=D({},t),this.defaultContent=t}set(e,t){return s.isSerializable(t)?(this.content[e]=t,this):(console.warn(`Value "${t}" in key "${String(e)}" is not serializable, and will not be set
|
|
28
28
|
at namespace "${this.name}"`),this.content[e]=t,this)}get(e){return this.content[e]}equals(e,t){return this.content[e]===t}assign(e){return Object.entries(e).forEach(([t,n])=>{this.set(t,n)}),this}reset(){return this.content=D({},this.defaultContent),this}toData(){return this.serialize()}load(e){if(!e){console.warn("No data to load");return}this.content=e}serialize(){let e={};return Object.entries(this.content).forEach(([t,n])=>{e[t]=this.wrap(n)}),e}deserialize(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.content[t]=this.unwrap(n)})}toTypeName(e){return e instanceof Date?"date":"any"}wrap(e){let t={any:o=>({type:"any",data:o}),date:o=>({type:"date",data:o.toString()})},n=this.toTypeName(e);return t[n](e)}unwrap(e){return{any:n=>n.data,date:n=>new Date(n.data)}[e.type](e)}},an=class{constructor(){this.namespaces={}}addNamespace(e){if(!this.namespaces[e.key])return this.namespaces[e.key]=e,this}getNamespace(e){if(!this.namespaces[e])throw new b(`Namespace ${e} is not initialized, did you forget to register it?
|
|
29
|
-
Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]=t,this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.namespaces[t]?this.namespaces[t].load(n):this.namespaces[t]=new
|
|
30
|
-
To prevent unintended behavior and unexpected results, the sound have to be marked as voice. Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof pe}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new Se({backgroundImage:n=>n.toData(),backgroundMusic:n=>n?.toData()||null},{backgroundImage:n=>t.state.backgroundImage.fromData(n),backgroundMusic:n=>t.state.backgroundMusic&&n?t.state.backgroundMusic.fromData(n):null})}get __futureActions__(){return this._futureActions_}get local(){return this.localPersistent}get background(){return this.state.backgroundImage}get backgroundLayer(){return this.config.defaultBackgroundLayer}get displayableLayer(){return this.config.defaultDisplayableLayer}setBackground(t,n){
|
|
29
|
+
Use \`story.registerPersistent\` to register a persistent namespace`);return this.namespaces[e]}setNamespace(e,t){return this.namespaces[e]=t,this}hasNamespace(e){return!!this.namespaces[e]}removeNamespace(e){return delete this.namespaces[e],this}getNamespaces(){return this.namespaces}keys(){return Object.keys(this.namespaces)}values(){return Object.values(this.namespaces)}entries(){return Object.entries(this.namespaces)}toData(){return this.entries().reduce((e,[t,n])=>(e[t]=n.toData(),e),{})}load(e){if(!e){console.warn("No data to load");return}Object.entries(e).forEach(([t,n])=>{this.namespaces[t]?this.namespaces[t].load(n):this.namespaces[t]=new rt(t,n)})}clear(){return this.namespaces={},this}};var Zn=class Zn extends j{constructor(e,t){super(),this.namespace=this.prefix(e),this.defaultContent=t}init(e){e.hasNamespace(this.namespace)||e.addNamespace(new rt(this.namespace,this.defaultContent))}getNamespace(e){return e.getNamespace(this.namespace)}set(e,t){return this.chain(this.createAction(Xt.set,[e,t]))}assign(e){return this.chain(this.createAction(Xt.assign,[e]))}equals(e,t){return new ue(({storable:n})=>n.getNamespace(this.namespace).equals(e,t))}notEquals(e,t){return new ue(({storable:n})=>!n.getNamespace(this.namespace).equals(e,t))}isTrue(e){return new ue(({storable:t})=>t.getNamespace(this.namespace).equals(e,!0))}isFalse(e){return new ue(({storable:t})=>t.getNamespace(this.namespace).equals(e,!1))}isNotNull(e){return new ue(({storable:t})=>{let n=t.getNamespace(this.namespace).get(e);return n!=null})}toWord(e){return new H(({storable:t})=>[String(t.getNamespace(this.namespace).get(e))])}get(e){return this.toWord(e)}conditional(e,t,n){return new H(o=>ue.from(e).evaluate(o).value?t:n)}evaluate(e,t){return new ue(({storable:n})=>t(n.getNamespace(this.namespace).get(e)))}getNamespaceName(){return this.namespace}prefix(e,t=Zn.NamespacePrefix){return t+":"+String(e)}createAction(e,t){return new Jn(this.chain(),e,y.create(t))}};Zn.NamespacePrefix="persistent";var Kt=Zn,_n=class _n extends Kt{constructor(e){super(e,{}),this.namespace=this.prefix(e,_n.LocalNamespacePrefix)}init(e){e.removeNamespace(this.namespace).addNamespace(new rt(this.namespace,this.defaultContent))}};_n.LocalNamespacePrefix="local";var Yn=_n;var Ft=class extends M{executeAction(e,t){if(this.type===At.action)return super.executeAction(e,t);if(this.type===At.setZIndex){let[n]=this.contentNode.getContent(),o=this.callee.state.zIndex;return this.callee.state.zIndex=n,e.actionHistory.push({action:this,stackModel:t.stackModel},i=>{this.callee.state.zIndex=i},[o]),e.stage.update(),super.executeAction(e,t)}throw super.unknownTypeError()}stringify(e,t,n){return super.stringifyWithName("LayerAction")}};Ft.ActionTypes=At;var Ne=class Ne extends qe{constructor(e,t={}){super();let n=Ne.DefaultUserConfig.create(t),o=Ne.DefaultConfig.create({...n.get(),name:e});this.userConfig=n,this.config=o.get(),this.state=this.getInitialState(),this.transformState=this.getInitialTransformState()}include(e){return(Array.isArray(e)?e:[e]).forEach(n=>{n.useLayer(this)}),this}setZIndex(e){return this.chain(new Ft(this.chain(),At.setZIndex,new y().setContent([e])))}toData(){return{state:Ne.StateSerializer.serialize(this.state)}}fromData(e){return this.state=Ne.StateSerializer.deserialize(e.state),this}copy(){return new Ne(this.config.name,this.userConfig.get())}setName(e){return this.config.name=e,this}_init(e){return[new Ft(this.chain(),At.action,new y),new le(this.chain(),ae.init,new y().setContent([e,null,!1]))]}getInitialState(){return Ne.DefaultState.create({zIndex:this.config.zIndex}).get()}getInitialTransformState(){let[e]=this.userConfig.extract(ie.DefaultTransformState.keys());return new ie(ie.DefaultTransformState.create(e.get()).get())}};Ne.DefaultUserConfig=new N({zIndex:0,...ie.DefaultTransformState.getDefaultConfig(),opacity:1}),Ne.DefaultConfig=new N({name:"(anonymous)",zIndex:0}),Ne.StateSerializer=new Se,Ne.DefaultState=new N({zIndex:0});var Wt=Ne;var pe=class pe extends Ut{constructor(t,n){super();this.srcManager=new fe;this.events=new K;this.actions=[];this._futureActions_=[];let o=pe.DefaultSceneConfig.getDefaultConfig().defaultBackgroundLayer.copy().setName("[[Background Layer of "+t+"]]"),i=pe.DefaultSceneConfig.getDefaultConfig().defaultDisplayableLayer.copy().setName("[[Displayable Layer of "+t+"]]"),r=pe.DefaultUserConfig.create(n),a=pe.DefaultSceneConfig.create({...r.get(),name:t,layers:[...r.get().layers,o,i],defaultBackgroundLayer:o,defaultDisplayableLayer:i});this.userConfig=r,this.config=a.get(),this.state=this.getInitialState(),this.localPersistent=new Yn(t)}static validateVoice(t){if(t.config.type!=="voice"&&t.config.type!=="sound")throw new ve(`Voice must be a voice, but got ${t.config.type}.
|
|
30
|
+
To prevent unintended behavior and unexpected results, the sound have to be marked as voice. Please use \`Sound.voice()\` to create the sound.`)}static isScene(t){return t instanceof pe}static getScene(t,n){return typeof n=="string"?t.getScene(n):n}static getStateSerializer(t){return new Se({backgroundImage:n=>n.toData(),backgroundMusic:n=>n?.toData()||null},{backgroundImage:n=>t.state.backgroundImage.fromData(n),backgroundMusic:n=>t.state.backgroundMusic&&n?t.state.backgroundMusic.fromData(n):null})}get __futureActions__(){return this._futureActions_}get local(){return this.localPersistent}get background(){return this.state.backgroundImage}get backgroundLayer(){return this.config.defaultBackgroundLayer}get displayableLayer(){return this.config.defaultDisplayableLayer}setBackground(t,n){return this.chain().chain(Ve.do([this.background.char(t,n)]))}jumpTo(t,n={}){return this.combineActions(new Ve({allowFutureScene:!1}),o=>{let r=D({unloadScene:!0},n instanceof Qe?{transition:n}:n);return o.chain(new se(o,"scene:preUnmount",new y().setContent([]))).chain(this._initScene(t))._transitionToScene(r.transition,t.state.backgroundImage.state.currentSrc),r.unloadScene&&o.chain(this._exit()),o})._jumpTo(t)}setBackgroundMusic(t,n){return this.chain(new se(this.chain(),_.setBackgroundMusic,new y().setContent([t,n])))}action(t){return this.actions=t,this}preloadImage(t){if(!S.isImageSrc(t))throw new Error("Invalid image source: "+t);return(Array.isArray(t)?t:[t]).forEach(o=>{this.srcManager.register({type:"image",src:o})}),this}toData(){return{state:pe.getStateSerializer(this).serialize(this.state)}}fromData(t){return this.state=pe.getStateSerializer(this).deserialize(t.state),this}constructSceneRoot(t){this.sceneRoot=new se(this.chain(),"scene:action",new y);let n=this.actions,i=this.narrativeToActions(typeof n=="function"?n(this):n).map(u=>de.isChained(u)?u.fromChained(u):u).flat(2),r=[],a=[];this.getAllChildrenElements(t,i,{allowFutureScene:!1}).forEach(u=>{de.isChained(u)||(u instanceof I?r.push(u):u instanceof Et&&a.push(u))});let c=[],l=[],d=new Map;r.forEach(u=>{u.config.isWearable?l.push(u):u.config.autoInit&&c.push(u);for(let A of u.config.wearables){if(d.get(A)&&d.get(A)!==u)throw new Error(`Wearable image cannot be used multiple times
|
|
31
31
|
Maybe you bind the same wearable image to multiple parent images
|
|
32
|
-
Parent Conflict (src: `+d.get(
|
|
33
|
-
Current Parent (src: `+u.state.currentSrc+")");d.set(
|
|
34
|
-
To prevent unintended behavior and unexpected results, the sound have to be marked as bgm. Please use \`Sound.bgm()\` to create the sound.`);return pe.DefaultSceneState.create().assign({backgroundImage:this.state?.backgroundImage?this.state.backgroundImage.reset():new I({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),...t.backgroundMusic?{backgroundMusic:this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic}:{}}).get()}_jumpTo(t){return this.chain(new se(this.chain(),"scene:jumpTo",new y().setContent([t])))}_exit(){return new se(this.chain(),"scene:exit",new y().setContent([]))}_transitionToScene(t,n){let o=this.chain();if(t&&n){let i=this.state.backgroundImage.char(n,t);o.chain(i.getActions())}return o}_init(t){return new se(this.chain(),"scene:init",new y().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};pe.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},pe.DefaultUserConfig=new N({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),pe.DefaultSceneConfig=new N({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Wt("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Wt("[[Displayable Layer]]",{zIndex:0})},{voices:t=>{let n=i=>typeof i=="object"&&i!==null,o=i=>typeof i=="function";if(!t)return null;if(n(t)&&Object.values(t).forEach(i=>{
|
|
32
|
+
Parent Conflict (src: `+d.get(A)?.state.currentSrc+`)
|
|
33
|
+
Current Parent (src: `+u.state.currentSrc+")");d.set(A,u)}});let p=[...this._initScene(this),...c.map(u=>u._init(this)),...l.map(u=>{if(!d.has(u))throw new Error("Wearable image must have a parent image");return d.get(u)._initWearable(u)}),...a.map(u=>u._init()),...i],m=super.constructNodes(p),g=new y(this.sceneRoot,void 0,m||void 0).setContent(this);return m?.setParent(g),this.sceneRoot?.setContentNode(g),this._futureActions_=p,this}narrativeToActions(t){return t.flatMap(n=>typeof n=="string"?gt.say(n).getActions():de.toActions([n]))}isSceneRootConstructed(){return!!this.sceneRoot}registerSrc(t,n=new Set){if(!this.sceneRoot)return;let o=new Set,i=new Set,r=[this.sceneRoot],a=new Set;for(;r.length;){let c=r.shift();if(!o.has(c)){if(o.add(c),c instanceof se){let l=c.callee;if(S.isImageSrc(l.state.backgroundImage.state.currentSrc)&&this.srcManager.register({type:"image",src:S.srcToURL(l.state.backgroundImage.state.currentSrc)}),c.type===_.jumpTo){let d=c,p=pe.getScene(t,d.contentNode.getContent()[0]);if(!p)throw c._sceneNotFoundError(c.getSceneName(d.contentNode.getContent()[0]));let m=fe.getPreloadableSrc(t,c);if(m&&this.srcManager.register(m),i.has(d)||n.has(p))continue;i.add(d),a.add(p),n.add(p)}}else if(c instanceof V){let l=fe.getPreloadableSrc(t,c);l&&this.srcManager.register(l)}else if(c instanceof ke)this.srcManager.register(c.callee);else if(c instanceof ee){let d=c.getFutureActions(t,{allowFutureScene:!0});r.push(...d)}else c instanceof le&&this.srcManager.register(c.callee.srcManager.getSrc());r.push(...c.getFutureActions(t,{allowFutureScene:!0}))}}a.forEach(c=>{c.registerSrc(t,n),this.srcManager.registerFuture(c.srcManager)})}assignActionId(t){this.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).forEach((o,i)=>{o.setId(`a-${i}`)})}assignElementId(t){this.getAllChildrenElements(t,this.sceneRoot||[]).forEach((o,i)=>{o.setId(`e-${i}`)})}getVoice(t){if(!t)return null;let n=this.config.voices;if(n){if(typeof n=="function"){let o=n(t);return typeof o=="string"||pe.validateVoice(o),o}return n[t]||null}return null}getSceneRoot(){if(!this.sceneRoot)throw new Error("Scene root is not constructed");return this.sceneRoot}stringify(t,n,o){return super.getAllChildren(t,this.sceneRoot||[],{allowFutureScene:!0}).map(i=>i.stringify(t,n,o)).join(";")}reset(){this.state.backgroundImage.reset(),this.state.backgroundMusic?.reset(),this.state=this.getInitialState()}getInitialState(){let t=this.userConfig.get();if(t.backgroundMusic&&t.backgroundMusic.config.type!=="bgm")throw new ve(`[Scene: ${this.config.name}] Background music must be a bgm, but got ${t.backgroundMusic.config.type}.
|
|
34
|
+
To prevent unintended behavior and unexpected results, the sound have to be marked as bgm. Please use \`Sound.bgm()\` to create the sound.`);return pe.DefaultSceneState.create().assign({backgroundImage:this.state?.backgroundImage?this.state.backgroundImage.reset():new I({src:t.background,opacity:1,autoFit:!0,name:`[[Background Image of ${this.config.name}]]`,layer:this.config.defaultBackgroundLayer})._setIsBackground(!0),...t.backgroundMusic?{backgroundMusic:this.state?.backgroundMusic?this.state.backgroundMusic.reset():t.backgroundMusic}:{}}).get()}_jumpTo(t){return this.chain(new se(this.chain(),"scene:jumpTo",new y().setContent([t])))}_exit(){return new se(this.chain(),"scene:exit",new y().setContent([]))}_transitionToScene(t,n){let o=this.chain();if(t&&n){let i=this.state.backgroundImage.char(n,t);o.chain(i.getActions())}return o}_init(t){return new se(this.chain(),"scene:init",new y().setContent([t]))}_initScene(t){return[t._init(t),...t.config.layers.flatMap(n=>n._init(t)),...t._initBackground(t,t.config.defaultBackgroundLayer)]}_initBackground(t,n){return[t.state.backgroundImage._init(t,n)]}};pe.EventTypes={"event:scene.remove":"event:scene.remove","event:scene.load":"event:scene.load","event:scene.unload":"event:scene.unload","event:scene.mount":"event:scene.mount","event:scene.unmount":"event:scene.unmount","event:scene.preUnmount":"event:scene.preUnmount","event:scene.imageLoaded":"event:scene.imageLoaded"},pe.DefaultUserConfig=new N({backgroundMusic:null,backgroundMusicFade:0,voices:void 0,background:"#fff",layers:[]}),pe.DefaultSceneConfig=new N({name:"",backgroundMusicFade:0,voices:null,layers:[],defaultBackgroundLayer:new Wt("[[Background Layer]]",{zIndex:-1}),defaultDisplayableLayer:new Wt("[[Displayable Layer]]",{zIndex:0})},{voices:t=>{let n=i=>typeof i=="object"&&i!==null,o=i=>typeof i=="function";if(!t)return null;if(n(t)&&Object.values(t).forEach(i=>{Ae.isSound(i)&&pe.validateVoice(i)}),o(t))return t;throw new ve(`Invalid voices config: ${t}`)}}),pe.DefaultSceneState=new N({backgroundImage:new I,backgroundMusic:null});var Pe=pe;var Ot=class extends M{executeAction(e,t){let n=this.contentNode.getContent().execute({gameState:e});return n&&e.actionHistory.push({action:this,stackModel:t.stackModel},()=>{n()},[]),super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ScriptAction")}};Ot.ActionTypes=Ri;var He=class s extends j{static getCtx({gameState:e}){return{gameState:e,game:e.game,liveGame:e.game.getLiveGame(),storable:e.game.getLiveGame().getStorable()}}constructor(e){return super(),this.handler=e,this.chain()}execute({gameState:e}){return this.handler(s.getCtx({gameState:e}))}fromChained(e){return[new Ot(this.chain(),Ot.ActionTypes.action,new y().setContent(e))]}};var st=class st extends Ut{constructor(t,n=st.defaultConfig){super();this.entryScene=null;this.scenes=new Map;this.persistent=[];this.services=new Map;this.name=t,this.config=D(st.defaultConfig,n)}static empty(){return new st("empty").entry(new Pe("empty"))}entry(t){return this.entryScene=t,this}registerPersistent(t){return this.persistent.push(t),this}createPersistent(t,n){let o=new Kt(t,n);return this.registerPersistent(o),o}registerService(t,n){return this.services.set(t,n),this}getService(t){let n=this.services.get(t);if(!n)throw new ve(`Trying to access service ${t} before it's registered, please use "story.registerService" to register the service`);return n}hash(t=!1){return zi(this.stringify(t))}stringify(t=!1){return this.entryScene?.stringify(this,new Set,t)||""}serializeServices(){let t={};return this.services.forEach((n,o)=>{if(!n.serialize||typeof n.serialize!="function")return;let i=n.serialize();if(i!==null){{if(i instanceof Promise)throw new Q(`Service ${o} serialize method should not return a promise`);if(!Ko(i))throw new Q(`Service ${o} serialize method should return a pure object.
|
|
35
35
|
A pure object should:
|
|
36
36
|
1. be an object literal
|
|
37
37
|
2. not have any prototype
|
|
38
38
|
3. no circular reference
|
|
39
39
|
4. sub objects should also be pure objects or serializable data
|
|
40
40
|
Return null if nothing needs to be saved. For more information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description
|
|
41
|
-
Returned value ${i} violates the above rules`)}t[o]=i}}),t}deserializeServices(t){this.services.forEach((n,o)=>{!n.deserialize||typeof n.deserialize!="function"||t[o]&&n.deserialize(t[o])})}getScene(t,n=!1,o){if(Pe.isScene(t))return t;let i=this.scenes.get(t)||null;if(!i&&n)throw Reflect.construct(o||Q,[`Scene with name ${t} not found`]);return i}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this}getAllElementStates(){return this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).map(n=>({id:n.getId(),data:n.toData()})).filter(n=>!!n.data)}constructSceneRoots(t){let n=new Set,o=[],i=0;for(t.constructSceneRoot(this),o.push(t.getSceneRoot());o.length;){if(i++,i>
|
|
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")}};
|
|
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
|
|
44
|
-
${T[
|
|
41
|
+
Returned value ${i} violates the above rules`)}t[o]=i}}),t}deserializeServices(t){this.services.forEach((n,o)=>{!n.deserialize||typeof n.deserialize!="function"||t[o]&&n.deserialize(t[o])})}getScene(t,n=!1,o){if(Pe.isScene(t))return t;let i=this.scenes.get(t)||null;if(!i&&n)throw Reflect.construct(o||Q,[`Scene with name ${t} not found`]);return i}constructStory(){let t=this.entryScene;if(!t)throw new Error("Story must have an entry scene");return this.constructSceneRoots(t),t.registerSrc(this),t.assignActionId(this),t.assignElementId(this),this.runStaticCheck(t),this}getAllElementStates(){return this.getAllChildrenElements(this,this.entryScene?.getSceneRoot()||[]).map(n=>({id:n.getId(),data:n.toData()})).filter(n=>!!n.data)}constructSceneRoots(t){let n=new Set,o=[],i=0;for(t.constructSceneRoot(this),o.push(t.getSceneRoot());o.length;){if(i++,i>st.MAX_DEPTH)throw new Error(`Max depth reached while constructing scene roots (max depth: ${st.MAX_DEPTH})`);let r=o.shift();if(Pe.isScene(r.callee)){if(n.has(r.callee))continue;r.callee.isSceneRootConstructed()||r.callee.constructSceneRoot(this),n.add(r.callee)}let a=r.getFutureActions(this,{allowFutureScene:!0});o.push(...a)}return this}initPersistent(t){return this.persistent.forEach(n=>{n.init(t)}),this}getInversionConfig(){let{origin:t}=this.config;return{invertY:t==="bottom left"||t==="bottom right",invertX:t==="bottom right"||t==="top right"}}runStaticCheck(t){return new Qn(t).run(this)}};st.defaultConfig={origin:"bottom left"},st.MAX_DEPTH=32767;var cn=st;var eo=class extends M{executeAction(e,t){let[n,o]=this.contentNode.getContent(),i=this.callee.triggerAction(He.getCtx({gameState:e}),n,o);return h.isAwaitable(i)?h.forward(i,{type:this.type,node:this.contentNode?.getChild()}):super.executeAction(e,t)}stringify(e,t,n){return super.stringifyWithName("ServiceAction")}};var jo=class extends j{constructor(){super(...arguments);this._handlers={}}on(t,n){return this._registerActionHandler(t,n),this}trigger(t,...n){let o=this.chain();return o.chain(this._createAction(o,t,n))}triggerAction(t,n,o){let i=this._handlers[n];if(!i){t.gameState.logger.warn(`(in User-Defined Service) Trying to trigger action ${n} before it's registered, please use "service.on" to register the action`);return}if(Fi(i)){let r=[],a=new h().registerSkipController(new L(()=>{for(let l of r)l?.()}));return i({...t,onAbort:l=>{r.push(l)}},...o).then(()=>a.resolve()),a}i({...t,onAbort:()=>{}},...o)}_registerActionHandler(t,n){this._handlers[t]=n}_createAction(t,n,o){return new eo(t,"service:action",new y().setContent([n,o]))}},qo=class extends jo{},ln=class extends qo{};var Je=class Je extends M{executeAction(e,t){let n=this,o=this.callee,i={action:n,stackModel:t.stackModel};if(n.is(Je,"video:play"))return this.changeStateAsync(e,r=>r.play(),t);if(n.is(Je,"video:pause"))return this.changeState(e,r=>r.pause(),t);if(n.is(Je,"video:stop"))return this.changeState(e,r=>r.stop(),t);if(n.is(Je,"video:seek"))return this.changeState(e,r=>r.seek(n.contentNode.getContent()[0]),t);if(n.is(Je,"video:show")){let r=o.state.display;return e.isVideoAdded(o)||(e.addVideo(o),e.stage.update()),o.state.display=!0,e.actionHistory.push(i,a=>{o.state.display=a},[r]),this.changeState(e,a=>a.show(),t)}else if(n.is(Je,"video:hide")){let r=o.state.display;return this.changeState(e,a=>{o.state.display=!1,e.actionHistory.push(i,c=>{o.state.display=c},[r]),a.hide(),e.removeVideo(o),e.stage.update()},t)}else if(n.is(Je,"video:resume"))return this.changeState(e,r=>r.resume(),t);throw this.unknownTypeError()}changeStateBase(e,t,n){if(!e.isVideoAdded(this.callee))throw new b(`Video is being used before it is added to the game
|
|
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")}};Je.ActionTypes=Gt;var to=Je;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 ft().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 ft().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 ft().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 ft().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 ft().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
|
+
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 A=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
|
+
${T[A]}
|
|
45
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(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
|
|
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===`
|
|
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 at=class at{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 rt(at.GameSpacesKey.game,at.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
|
+
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(at.EventTypes["event:character.prompt"],e)}onMenuChoose(e){return this.events.on(at.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("Game Actions","Action stack is empty"),this.currentSavedGame?e.events.emit("event:state.end"):this.currentSavedGame=null,null):this.stackModel.rollNext()}setLastDialog(e,t){this.lastDialog={sentence:e,speaker:t}}requestAsyncStackModel(e){this.assertGameState();let t=new 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),[Xe].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")}};at.DefaultNamespaces={game:{}},at.GameSpacesKey={game:"game"},at.EventTypes={"event:character.prompt":"event:character.prompt","event:menu.choose":"event:menu.choose"};var yt=at;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 Ye(){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 ct=class ct{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(ct.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(ct.EventTypes["event:aspectRatio.pause"])}resume(){this.state.paused=!1,this.events.emit(ct.EventTypes["event:aspectRatio.resume"])}onUpdate(e){return this.events.on(ct.EventTypes["event:aspectRatio.update"],e).cancel}requestUpdate(){this.events.emit(ct.EventTypes["event:aspectRatio.requestUpdate"])}onRequestedUpdate(e){return this.events.on(ct.EventTypes["event:aspectRatio.requestUpdate"],e).cancel}triggerUpdate(){this.updater&&this.updater()}};ct.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=ct,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 Ze({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 $e(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(Ze,{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 As}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 vs({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(vs,{...s,as:"img"})}function ks(s){return Ue.createElement(mo,{...s,as:"button"})}function Ps(s){return Ue.createElement(mo,{...s,as:As.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 lt(){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 Be=class Be{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(Be.Events.complete):this.safeEmit(Be.Events.requestComplete)}forceSkip(){this.state==="ended"?this.emitComplete():(this._forceSkipped=!0,this.safeEmit(Be.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(Be.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(Be.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(Be.Events.onFlush),this}onFlush(e){return this.events.on(Be.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(Be.Events.simulateClick)},this.config.gameState.game.config.autoForwardDelay/e.getPreference(q.Preferences.gameSpeed))}};Be.Events={requestComplete:"event:dialog.requestComplete",complete:"event:dialog.complete",forceSkip:"event:dialog.forceSkip",onFlush:"event:dialog.onFlush",simulateClick:"event:dialog.simulateClick"};var De=Be;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
|
-
`: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,
|
|
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,v=new re(f).setGuard(r.guard),G=new Set,he=new Set,et=new Set,Mt=mr(n.config.evaluatedWords),Ke=null,bt=[],Fe=[],mt=()=>{bt.forEach(P=>P()),bt.length=0},tt=()=>{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!==`
|
|
54
54
|
`&&P!==`
|
|
55
|
-
`&&X.tag===P.tag?[...E.slice(0,-1),{...P,text:X.text+P.text,config:P.config}]:[...E,P]})},O=(P=!1)=>{let E=!1;for(;!E;){let{done:X,value:z}=
|
|
56
|
-
`?l(me=>[...me,z]):typeof z=="object"&&"text"in z&&!G.has(z)&&(G.add(z),k(z))}Ke&&!Ke.isSettled()?Ke.abort():(
|
|
57
|
-
`&&G.has(me))continue;G.add(me),k(me);let{gameSpeed:kn,cps:Pn}=i.preference.getPreferences(),Dn=1e3/((typeof me=="object"&&"cps"in me&&me.cps!==void 0?me.cps:Pn)*kn);await Kn(Dn)}}X&&(
|
|
58
|
-
`?Rt.createElement("br",{key:
|
|
59
|
-
This is likely caused by a nested Layout component or using Page inside a Page. `);return s}function ea({children:s,name:e,propagate:t}){let n=w(),[o]=$(),{path:i,router:r,consumedBy:a}=gn(),c=r.joinPath(i,e),l=vo(()=>r.createToken(c+"@layout")),d=r.getCurrentPath(),p=_s(!1),m=u=>{p.current=u,o()},g=r.matchPath(d,c);if(fn(),Co(u=>{let v=u.matchPath(u.getCurrentPath(),c);if(p.current&&!v){if(!s){m(!1);return}u.registerUnmountingPath(l)}v&&u.isPathsUnmounting()&&u.unregisterUnmountingPath(l),v&&!p.current&&!u.isTransitioning()&&m(!0)},[g,s]),Zs(()=>{if(!g)return;let u=r.mount(c);return()=>{u.cancel()}},[c,r,g]),a)throw new b("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return hn.createElement(yn,{path:c},hn.createElement(Ao,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{r.unregisterUnmountingPath(l),m(!1)}},g&&p.current&&s))}function hr({children:s}){return fn(),hn.createElement(yn,{path:Tt.rootPath},hn.createElement(lo,{"data-layout-path":Tt.rootPath,key:Tt.rootPath},s))}var si=ta(null);function ia(){return na(si)}function ra({children:s,name:e}){let[t]=$(),{path:n,router:o,consumedBy:i}=gn(),r=ia(),a=r?.name??e,c=a??n+"@default",l=a?o.joinPath(n,a):n,d=vo(()=>o.createToken(l+"@page")),p=o.getCurrentPath(),m=!a,g=oa(!1),u=f=>{g.current=f,t()},v=m&&o.exactMatch(p,n)||o.exactMatch(p,l);if(i&&i!==c)throw new b("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");fn(),Co(f=>{let A=m&&f.exactMatch(f.getCurrentPath(),n)||f.exactMatch(f.getCurrentPath(),l);if(g.current&&!A){if(!s){u(!1);return}f.registerUnmountingPath(d)}A&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(d),A&&!g.current&&!f.isTransitioning()&&u(!0)},[v,s]),yr(()=>{if(!v)return;let f=m?o.mountDefaultHandler(l):o.mount(l);return o.emitOnPageMount(),()=>{f.cancel()}},[l,v]),yr(()=>()=>{o.unregisterUnmountingPath(d),u(!1)},[]);let T=ri.createElement(yn,{path:n,consumedBy:c},ri.createElement(Ao,{mode:"wait",onExitComplete:()=>{o.unregisterUnmountingPath(d),u(!1)}},v&&g.current&&s));return(f=>r?ri.createElement(si,{value:{name:null}},f):f)(T)}import{useEffect as sa,useState as aa}from"react";function Tn(s){let e=w(),[t,n]=aa(e.keyMap.getKeyBinding(s)),o=i=>{e.keyMap.setKeyBinding(s,i),n(i)};return sa(()=>e.keyMap.onKeyBindingChange(s,n).cancel,[s,e.keyMap,n]),[t,o]}function ca(){return w().getLiveGame()}var Sn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Sn||{});function Sr({state:s}){let e=w(),t=Je(),n=ai(null),o=ai(null),i=ai(!1),[r]=ze(q.Preferences.skipDelay),[a]=ze(q.Preferences.skipInterval),[c]=Tn("skipAction");return ua(()=>{if(!e.getLiveGame().gameState.playerCurrent){s.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){s.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let d=()=>{o.current&&(clearTimeout(o.current),o.current=null),n.current&&(clearInterval(n.current),n.current=null),i.current=!1},p=g=>{if(e.keyMap.match("skipAction",g.key)&&e.preference.getPreference(q.Preferences.skip)&&!i.current){s.logger.verbose("KeyEventAnnouncer","Skipping");let u=()=>{n.current=setInterval(()=>{s.events.emit(U.EventTypes["event:state.player.skip"],!1)},a)};d(),s.events.emit(U.EventTypes["event:state.player.skip"],!1),i.current=!0,r===0?u():o.current=setTimeout(u,r)}},m=g=>{e.keyMap.match("skipAction",g.key)&&d()};if(e.config.useWindowListener){let g=e.getLiveGame().onWindowEvent("keydown",p).cancel,u=e.getLiveGame().onWindowEvent("keyup",m).cancel;return()=>{d(),g(),u()}}else{let g=e.getLiveGame().onPlayerEvent("keydown",p).cancel,u=e.getLiveGame().onPlayerEvent("keyup",m).cancel;return()=>{d(),g(),u()}}},[t,r,a,c]),Tr.createElement(Tr.Fragment,null)}import{useEffect as bn}from"react";function ci({gameState:s}){let e=s.audioManager,[t]=ze("voiceVolume"),[n]=ze("bgmVolume"),[o]=ze("soundVolume"),[i,r]=ze("globalVolume");return bn(()=>{r(e.getGlobalVolume())},[]),bn(()=>{e.setGroupVolume("voice",t)},[t]),bn(()=>{e.setGroupVolume("bgm",n)},[n]),bn(()=>{e.setGroupVolume("sound",o)},[o]),bn(()=>{e.setGlobalVolume(i)},[i]),null}import{useEffect as pa}from"react";function li({ref:s}){let{ratio:e}=Y();return pa(()=>{let t=s.current;if(!t)return;let n=new ResizeObserver(()=>{e.requestUpdate()});return n.observe(t),()=>{n.disconnect()}},[s.current]),null}import{useEffect as wo,useRef as fa}from"react";import ui,{createContext as ma,useContext as da,useState as br}from"react";var Lt=class Lt{constructor(){this.preloaded=[];this.events=new K}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(Lt.EventTypes["event:preloaded.add"],e),this.events.emit(Lt.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(o=>this.getSrc(o));return this.preloaded=this.preloaded.filter(o=>!n.includes(this.getSrc(o))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(Lt.EventTypes["event:preloaded.remove"],e),this.events.emit(Lt.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return fe.getSrc(e)}};Lt.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.unmount":"event:preloaded.unmount"};var Re=Lt;var xo=class s{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear()})}static getImage(e,t,n){return Hi(e,{...n,signal:t})}has(e){return this.src.has(e)}add(e,t){return this.src.set(e,t),this}remove(e){return this.src.delete(e),this}get(e){return this.src.get(e)}clear(){return this.src.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let n=t,o={};this.game.hooks.rawTrigger("preloadImage",()=>[n,(p,m)=>{n=p,o={...o,...m}}]);let i=new AbortController,r=i.signal,a=[],l={promise:s.getImage(n,r,o).then(p=>{this.preloadTasks.delete(t),p&&this.add(t,p)}).catch(p=>{e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),a.forEach(m=>m(p))}),controller:i};this.preloadTasks.set(t,l);let d={abort:()=>{i.abort(),this.preloadTasks.delete(t)},onFinished:p=>(l.promise.then(p),d),onErrored:p=>(a.push(p),d)};return d}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){for(let t of this.src.keys())e.includes(t)||this.src.delete(t);return this}};var pi=ma(null);function vr({children:s}){let e=w(),[t]=br(()=>new Re),[n]=br(()=>new xo(e));return ui.createElement(ui.Fragment,null,ui.createElement(pi,{value:{preloaded:t,cacheManager:n}},s))}function $t(){if(!pi)throw new Error("usePreloaded must be used within a PreloadedProvider");return da(pi)}function Ar({state:s}){let{preloaded:e,cacheManager:t}=$t(),n=w(),o=fa(new Set),[i]=$(),r="Preload",a=s.getLastScene()||s.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function d(){s.logger.debug(r,"Preload unmounted"),e.events.emit(Re.EventTypes["event:preloaded.unmount"])}return wo(()=>s.events.on(U.EventTypes["event:state:flushPreloadedScenes"],()=>{i()}).cancel,[]),wo(()=>{if(typeof fetch>"u")return e.events.emit(Re.EventTypes["event:preloaded.ready"]),s.logger.warn(r,"Fetch is not supported in this environment, skipping preload"),d;if(!n.config.preloadAllImages)return e.events.emit(Re.EventTypes["event:preloaded.ready"]),s.logger.debug(r,"Preload all images is disabled, skipping preload"),d;if(n.config.forceClearCache&&(t.clear(),s.logger.weakWarn(r,"Cache cleared")),!l||!a)return s.logger.weakWarn(r,"Story/Scene not found, skipping preload"),d;let p=performance.now(),m=fe.catSrc([...a.srcManager?.src||[],...a.srcManager?.getFutureSrc()||[]]),g=new Yt(n.config.preloadConcurrency,n.config.preloadDelay),u=[],v=s.logger.group(r,!0),T=[];s.logger.debug(r,"preloading:",m,a);for(let R of m.image){let f=fe.getSrc(R);if(f){if(u.push(f),t.has(f)||t.isPreloading(f)||T.includes(f)){s.logger.debug(r,`Image already loaded (${m.image.indexOf(R)+1}/${m.image.length})`,f),T.push(f);continue}T.push(f),g.addTask(()=>new Promise(A=>{t.preload(s,f).onFinished(()=>{s.logger.debug(r,`Image loaded (${m.image.indexOf(R)+1}/${m.image.length})`,f),A()}).onErrored(()=>{s.logger.weakError(r,`Failed to preload image (${m.image.indexOf(R)+1}/${m.image.length})`,f),A()})}))}}return v.end(),g.start().then(()=>{s.logger.info(r,"Image preload",`loaded ${t.size()} images in ${performance.now()-p}ms`),n.config.waitForPreload&&e.events.emit(Re.EventTypes["event:preloaded.ready"]),t.filter(u)}),n.config.waitForPreload||e.events.emit(Re.EventTypes["event:preloaded.ready"]),e.events.emit(Re.EventTypes["event:preloaded.mount"]),d},[a,l]),wo(()=>{o.current.clear()},[a]),wo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){s.logger.weakWarn(r,"Story not found, skipping preload");return}let p=performance.now(),m=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(f=>fe.getPreloadableSrc(l,f)).filter(function(f){return f!==null});m.filter(function(f){return f?.activeType==="scene"}).forEach(f=>{o.current.has(f)||o.current.add(f)});let u=fe.catSrc([...o.current,...m]),v=new Yt(n.config.preloadConcurrency,n.config.preloadDelay),T=[],R=s.logger.group(r);s.logger.debug(r,"preloading:",u);for(let f of u.image){let A=fe.getSrc(f);if(A){if(T.push(A),t.has(A)||t.isPreloading(A)){s.logger.debug(r,`Image already loaded (${u.image.indexOf(f)+1}/${u.image.length})`,A);continue}v.addTask(()=>new Promise(G=>{t.preload(s,A).onFinished(()=>{s.logger.debug(r,`Image loaded (${u.image.indexOf(f)+1}/${u.image.length})`,A),G()}).onErrored(()=>{s.logger.weakError(r,`Failed to preload image (${u.image.indexOf(f)+1}/${u.image.length})`,A),G()})}))}}R.end(),v.start().then(()=>{s.logger.info(r,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-p}ms`),t.filter(T)})},[c,l]),null}import Ze,{useMemo as ga,useCallback as mi,useRef as ha}from"react";import ya from"clsx";function di({prompt:s,choices:e,afterChoose:t,state:n,words:o}){let i=w(),r=ha([]),a=mi(g=>(r.current.push(g),r.current.indexOf(g)),[]),c=mi(g=>{let u=r.current.indexOf(g);u!==-1&&r.current.splice(u,1)},[]),l=mi(g=>r.current.indexOf(g),[]),d=i.config.menu,p=ga(()=>e.map(g=>({...g,words:g.prompt.evaluate(He.getCtx({gameState:n}))})),[]);function m(g){t(g)}return Ze.createElement(Ze.Fragment,null,Ze.createElement(ei,{value:{evaluated:p,choose:m,gameState:n}},Ze.createElement(ti,{value:{register:a,unregister:c,getIndex:l}},Ze.createElement(Ye,{className:"absolute"},s&&Ze.createElement(mn,{gameState:n,action:{sentence:s,words:o,character:null},useTypeEffect:!1})),Ze.createElement(Dt.Div,{color:"green",border:"dashed",className:ya("absolute"),style:{width:`${i.config.width}px`,height:`${i.config.height}px`}},Ze.createElement(d,{items:p.map((g,u)=>u)})))))}function Cr({items:s}){return Ze.createElement(uo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},s.map(e=>Ze.createElement(ho,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import Ro from"react";import ko from"react";import fi,{useEffect as xr,useLayoutEffect as wr,useRef as kr,useState as gi}from"react";function Bt({element:s,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:o,onTransform:i,onTransition:r,transitionsProps:a=[],propOverwrite:c}){let[l,d]=gi(null),[p,m]=gi(null),g=fi.useRef(null),[u]=gi(()=>new Mn("displayable.refGroup")),v=kr(u.next()),T=kr(et()),f=w().getLiveGame().getGameState(),A=typeof a=="function"?a(l):a,[G]=$([p,l,T]);xr(()=>f.events.depends([f.events.on(U.EventTypes["event:state.player.skip"],pt)]).cancel,[p,l,T]),wr(()=>{if(he(),!l)return;if(T.current.some(([Z])=>!Z.current))throw new b("Displayable: Trying to access transition groups before they are mounted");let{controller:k,task:O}=l;return k.onUpdate(Z=>{T.current.forEach(([Le],Be)=>{let P=O.resolve[Be],E=typeof P=="function"?P:P.resolver;if(!E)throw new b(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${Be}])`);let X=E(...Z),z=D(A[Be]||A[A.length-1]||{},X);Mt(Le,c?c(z):z)})}).cancel},[l]),xr(()=>{if(!g.current)throw new Error(`Scope not ready. Using element: ${s.constructor.name}`)},[]),wr(()=>{let k=e.toStyle(f,o);Object.assign(g.current.style,k),f.logger.debug("Displayable","Initial style applied",g.current,k)},[]);function he(){let k=typeof a=="function"?a(l):a;if(!T.current||!T.current.length)throw new b("Displayable: Transition group refs are not initialized correctly");if(T.current.some(([O])=>!O.current))throw new b("Displayable: Trying to access transition groups before they are mounted");T.current.forEach(([O],x)=>{if(!O.current)throw new b("Displayable: Trying to assign properties to unmounted element");Mt(O,k[x]||k[k.length-1]||{})})}function _e(k){f.logger.debug("Displayable","Transform applied",e.toStyle(f,o),g.current),G(),i?.(k)}function Mt(k,O){if(!k.current)throw new b("Displayable: Trying to assign properties to unmounted element");let x=k.current,Z={},Le={};Object.keys(O).forEach(P=>{let E=P;E==="style"&&O.style?Object.assign(Z,O.style):O[E]!==void 0&&E!=="key"&&(Le[E]=O[E])}),Object.keys(Z).length>0&&Object.assign(x.style,Z);let Be=c?c(Le):Le;for(let[P,E]of Object.entries(Be))x.getAttribute(P)!==E&&x.setAttribute(P,E)}function Ke(k,O){p&&(p.abort(),m(null));let x=k.animate(e,{gameState:f,ref:g,overwrites:o}),Z=new re(x);return f.timelines.attachTimeline(Z),x.onSkipControllerRegister(Le=>{Le.onAbort(()=>{Z.abort(),m(null)})}),m(x),x.then(()=>{m(null),_e(k),O()}),Z}function bt(k,O){l&&l.controller.complete();let x=k.createTask(f),Z=k.requestAnimations(x.animations),Le=new h().registerSkipController(new L(Z.cancel)),Be=new re(Le);Le.skipController.onAbort(()=>{Z.cancel()}),Z.onCanceled(()=>{Be.abort(),d(null),f.logger.debug("Displayable","Transition cancelled",k)}),f.timelines.attachTimeline(Be),d({task:x,controller:Z,transition:k,resolve:O});let P;if(T.current=x.resolve.map(X=>{let z=fi.createRef(),me=typeof X=="function"?void 0:X.key;if(!me)return[z,u.next()];if(me==="target")return P=u.next(),[z,P];if(me==="current")return[z,v.current];throw new b("Displayable: Invalid key type")}),!P)throw new b("Displayable: No target key found");v.current=P;let E=T.current.map(([X])=>{let z=X.current;return z?.waitForLoad?z.waitForLoad():Promise.resolve()});return Promise.all(E).then(()=>{Z.start(),Z.onComplete(()=>{ne(),d(null),r?.(k),O(),Le.resolve()})}),Be}function Fe(k){return f.logger.debug("initDisplayable",s),Ke(F.immediate(e.get()),k)}function pt(){t&&p&&(p.abort(),m(null),f.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),f.logger.debug("transition skipped"))}function et(){return[[fi.createRef(),v.current]]}function ne(){T.current.forEach(([k])=>{k.current=null}),T.current=et()}return{transformRef:g,transitionRefs:T.current,isTransforming:!!p,transitionTask:l,initDisplayable:Fe,applyTransform:Ke,applyTransition:bt,updateStyleSync:he,deps:[p,l,T]}}import{useEffect as Ta}from"react";function St(s,e,t=[]){let o=w().getLiveGame().getGameState();return Ta(()=>{let i=typeof e=="function"?e():e;return o.mountState(s,i).unMount},[...t]),[]}function hi({state:s,text:e}){let{ratio:t}=Y(),[n]=$(),{transformRef:o,transitionRefs:i,initDisplayable:r,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:d,isTransforming:p}=Bt({element:e,state:e.transformState,skipTransform:s.game.config.allowSkipTextTransform,skipTransition:s.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:m=>({width:"fit-content",transform:F.propToCSSTransform(s,m,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return St(e,{initDisplayable:r,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...d]),ko.createElement(Dt.Div,{"data-element-type":"text"},ko.createElement(Dt.mDiv,{tag:"text.container",color:"green",border:"dashed",layout:p,ref:o,className:"absolute"},i.map(([m,g])=>ko.createElement("span",{key:g,ref:m,className:e.config.className},ko.createElement("span",null,e.state.text)))))}import jt,{useRef as Dr,useState as Rr}from"react";import Po,{useEffect as yi,useRef as Eo,forwardRef as Sa}from"react";var Pr=Sa(({onSizeChanged:s,onLoad:e,autoFit:t=!1},n)=>{let o=Eo(null),{ratio:i}=Y(),[r,a]=Po.useState(()=>i.state.width),[c,l]=Po.useState(()=>i.state.height),d=w(),p=Eo(!1),m=Eo(null),g=Eo(null);Po.useImperativeHandle(n,()=>o.current,[]),yi(()=>{o.current&&Object.defineProperties(o.current,{isLoaded:{value:()=>p.current,configurable:!0},waitForLoad:{value:()=>p.current?Promise.resolve():(m.current||(m.current=new Promise(T=>{g.current=T})),m.current),configurable:!0}})},[]),yi(()=>(u(),i.onUpdate(u)),[s]),yi(()=>{let T=new MutationObserver(R=>{R.forEach(f=>{f.type==="attributes"&&f.attributeName==="src"&&o.current&&u()})});return o.current&&T.observe(o.current,{attributes:!0}),()=>{T.disconnect()}},[s]);function u(){if(o.current&&o.current.naturalWidth)if(o.current.naturalWidth*o.current.naturalHeight===1){let T=i.state.width,R=i.state.height,f=`${T} / ${R}`;a(T),l(R),o.current.style.aspectRatio=f,s&&s(T,R)}else{let T=t?d.config.width/o.current.naturalWidth:1,R=o.current.naturalWidth*i.state.scale*T,f=o.current.naturalHeight*i.state.scale*T;a(R),l(f),o.current.style.aspectRatio="auto",s&&s(R,f)}}function v(){u(),p.current=!0,g.current&&(g.current(),g.current=null,m.current=null),e&&e()}return Po.createElement("img",{ref:o,onLoad:v,width:r,height:c,alt:""})});Pr.displayName="AspectScaleImage";var Er=Pr;import Lr from"clsx";import{motion as ba}from"motion/react";function Do({image:s,state:e}){let[t]=Rr(()=>new K),[n,o]=Rr([]),{cacheManager:i}=$t(),r=Dr([]),a=Dr(null),{transformRef:c,transitionRefs:l,isTransforming:d,initDisplayable:p,applyTransition:m,applyTransform:g,updateStyleSync:u,deps:v}=Bt({element:s,state:s.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:f=>{let A=f?f.transition._getCurrentSrc():s.state.currentSrc;return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:S.isColor(A)?S.colorToString(A):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-s.state.darkness})`},src:S.isImageSrc(A)?S.srcToURL(A):I.DefaultImagePlaceholder},{style:{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none",filter:"brightness(1)"}}]},propOverwrite:f=>f.src?(!S.isDataURI(f.src)&&!i.has(f.src)&&!i.isPreloading(f.src)&&!r.current.includes(f.src)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${f.src}".
|
|
55
|
+
`&&X.tag===P.tag?[...E.slice(0,-1),{...P,text:X.text+P.text,config:P.config}]:[...E,P]})},O=(P=!1)=>{let E=!1;for(;!E;){let{done:X,value:z}=tt();if(X){E=!0;break}if(Te.isPause(z)){if(P)continue;E=!0,Fe.push(z);break}else z===`
|
|
56
|
+
`?l(me=>[...me,z]):typeof z=="object"&&"text"in z&&!G.has(z)&&(G.add(z),k(z))}Ke&&!Ke.isSettled()?Ke.abort():(et.forEach(X=>X()),f.resolve())};return r.schedule(async P=>{let E=!1,X=!1;for(;!E;){let{done:z,value:me}=tt();if(z){E=X=!0;break}let wn=new h;if(r.timelines.attachTimeline(wn),wn.registerSkipController(new L(()=>{mt(),E=!0,P.retry()})),wn.onSettled(()=>{mt()}),Ke=wn,Te.isPause(me)){let kn=Te.from(me),Pn=i.preference.getPreference(q.Preferences.gameSpeed);if(kn.config.duration){let En=kn.config.duration/Pn;await Kn(En)}else{let En=i.preference.getPreference(q.Preferences.autoForward),Dn=h.race([h.create(Yr=>{let Zr=ne(_r=>{_r(),Yr.resolve()});bt.push(()=>Zr.cancel())}),...En?[h.delay(i.config.autoForwardDefaultPause/Pn)]:[]]);r.timelines.attachTimeline(Dn),await h.wait(Dn)}}else{if(me!==`
|
|
57
|
+
`&&G.has(me))continue;G.add(me),k(me);let{gameSpeed:kn,cps:Pn}=i.preference.getPreferences(),Dn=1e3/((typeof me=="object"&&"cps"in me&&me.cps!==void 0?me.cps:Pn)*kn);await Kn(Dn)}}X&&(et.forEach(z=>z()),f.resolve())},0),{getToken:()=>f,interact:()=>{let P=!1;he.forEach(E=>E(()=>P=!0)),!P&&O()},update:()=>{Ke&&Ke.abort()},forceSkip:()=>{O(!0)},timeline:v,onComplete:P=>(et.add(P),{cancel:()=>{et.delete(P)}})}}function g(f){let v=mr(f),G=[];for(let he of v)Te.isPause(he)||G.push(he);return G}let u=n.config.action.sentence;if(!u)return null;let A={fontWeight:u.config.bold?i.config.fontWeightBold:i.config.fontWeight,fontSize:u.config.fontSize??i.config.fontSize,color:vt(u.config.color??i.config.defaultTextColor),fontFamily:u.config.fontFamily??i.config.fontFamily,fontStyle:u.config.italic?"italic":void 0},T=f=>({fontWeight:f.config.bold||u.config.bold?i.config.fontWeightBold:i.config.fontWeight,fontSize:f.config.fontSize??u.config.fontSize??i.config.fontSize,color:vt(f.config.color??u.config.color??s??i.config.defaultTextColor),fontFamily:f.config.fontFamily??u.config.fontFamily??i.config.fontFamily,fontStyle:f.config.italic??u.config.italic?"italic":void 0}),R=(f,v)=>f===`
|
|
58
|
+
`?Rt.createElement("br",{key:v}):Rt.createElement(Dt.Span,{tag:`say.word.${v}`,key:v,style:{...T(f),...Fn(i.config.app.debug,{outline:"1px dashed red"})},className:pr("inline-block break-all",f.config.className)},f.config.ruby?Rt.createElement("ruby",{className:"align-bottom inline-block"},Rt.createElement("rt",{className:"block text-center"},f.config.ruby),f.text):f.text);return Rt.createElement("div",{...o,className:pr("whitespace-pre-wrap",e),style:{...t,...A}},c.map(R))}function fr(s){return Rt.createElement(dr,{...s,key:s.dialog?.config.action.id})}function ii(s){let e=lt();return Rt.createElement(dr,{...s,dialog:e,key:e.config.action.id})}var Ns=ii;function ho({className:s,style:e,bindKey:t}){let n=Fs(null),{register:o,unregister:i,getIndex:r}=ar(),[a,c]=Ws(-1),{choose:l,evaluated:d,gameState:p}=sr(),m=a===-1?null:d[a];Ks(()=>{if(!n.current)return;let u=n;o(u);let A=r(u);return c(A),n.current.dataset.index=A.toString(),()=>i(u)},[o,i,r]),Us(()=>{if(!t)return;let u=A=>{A.key.toLowerCase()===t.toLowerCase()&&!A.ctrlKey&&!A.metaKey&&(A.preventDefault(),A.stopPropagation(),g())};return window.addEventListener("keydown",u,!0),()=>{window.removeEventListener("keydown",u,!0)}},[t]);function g(){if(a===-1||!d[a])return;let u=d[a];l({...u,evaluated:H.getText(u.words||[])})}return go.createElement(go.Fragment,null,go.createElement("button",{className:Hs(s),style:e,onClick:g,ref:n},m&&go.createElement(fr,{dialog:new De({useTypeEffect:!1,action:{sentence:m.prompt,words:m.words,character:null},gameState:p,evaluatedWords:m.words})})))}import yo from"react";import{AnimatePresence as Os}from"motion/react";function To({children:s,...e}){let t=Os;return yo.createElement(yo.Fragment,null,yo.createElement("div",{...e},yo.createElement(t,null,s)))}import So from"react";function bo({...s}){let{config:e}=lt(),t=w();return So.createElement(So.Fragment,null,So.createElement("div",{...s},So.createElement("span",{style:{color:vt(e.action.character?.config.color||t.config.defaultNametagColor)}},e.action.character?.state.name)))}import{useEffect as Vs}from"react";function zs(){let s=lt(),[e]=$(s.deps),t=H.getText(s.config.evaluatedWords);return Vs(()=>s.events.on(De.Events.onFlush,()=>{e()}).cancel,[s]),{done:s.isEnded(),text:t,isNarrator:s.config.action.character===null||s.config.action.character.state.name===""}}import ri,{createContext as ta,useContext as na,useEffect as yr,useRef as oa}from"react";import{useState as $s}from"react";function Ao(s){let[e]=$s(s);return e}import{AnimatePresence as Bs}from"motion/react";var vo=Bs;import hn,{createContext as Js,useContext as Ys,useEffect as Zs,useRef as _s}from"react";import{useEffect as dn,useLayoutEffect as js}from"react";function qs(){let s=Ye(),[e]=$();return dn(()=>s.onChange(e).cancel,[]),s.getPathname()}function Qs(){let{router:s,path:e}=gn(),[t]=$();return dn(()=>s.onChange(t).cancel,[]),s.extractParams(s.getCurrentPath(),e)}function Xs(){let s=Ye(),[e]=$();return dn(()=>s.onChange(e).cancel,[]),s.getQueryParams()}function Co(s,e){let t=Ye();js(()=>t.onUpdate(()=>s(t)).cancel,e),dn(()=>{s(t)},[])}function fn(){let s=Ye(),[e]=$();return dn(()=>s.onChange(e).cancel,[]),e}var gr=Js(null);function yn({children:s,path:e,consumedBy:t}){let o={router:Ye(),path:e,consumedBy:t};return hn.createElement(gr,{value:o},s)}function gn(){let s=Ys(gr);if(!s)throw new Error("useLayout must be used within a LayoutRouterProvider");if(s.path===null)throw new b(`Invalid useLayout call: Trying to access layout without a parent.
|
|
59
|
+
This is likely caused by a nested Layout component or using Page inside a Page. `);return s}function ea({children:s,name:e,propagate:t}){let n=w(),[o]=$(),{path:i,router:r,consumedBy:a}=gn(),c=r.joinPath(i,e),l=Ao(()=>r.createToken(c+"@layout")),d=r.getCurrentPath(),p=_s(!1),m=u=>{p.current=u,o()},g=r.matchPath(d,c);if(fn(),Co(u=>{let A=u.matchPath(u.getCurrentPath(),c);if(p.current&&!A){if(!s){m(!1);return}u.registerUnmountingPath(l)}A&&u.isPathsUnmounting()&&u.unregisterUnmountingPath(l),A&&!p.current&&!u.isTransitioning()&&m(!0)},[g,s]),Zs(()=>{if(!g)return;let u=r.mount(c);return()=>{u.cancel()}},[c,r,g]),a)throw new b("[PageRouter] Layout is consumed by a different layout. This is likely caused by a nested layout inside a layout.");return hn.createElement(yn,{path:c},hn.createElement(vo,{mode:"wait",propagate:t??n.config.animationPropagate,onExitComplete:()=>{r.unregisterUnmountingPath(l),m(!1)}},g&&p.current&&s))}function hr({children:s}){return fn(),hn.createElement(yn,{path:Tt.rootPath},hn.createElement(lo,{"data-layout-path":Tt.rootPath,key:Tt.rootPath},s))}var si=ta(null);function ia(){return na(si)}function ra({children:s,name:e}){let[t]=$(),{path:n,router:o,consumedBy:i}=gn(),r=ia(),a=r?.name??e,c=a??n+"@default",l=a?o.joinPath(n,a):n,d=Ao(()=>o.createToken(l+"@page")),p=o.getCurrentPath(),m=!a,g=oa(!1),u=f=>{g.current=f,t()},A=m&&o.exactMatch(p,n)||o.exactMatch(p,l);if(i&&i!==c)throw new b("[PageRouter] Layout Context is consumed by a different page. This is likely caused by a nested page/layout inside a page.");fn(),Co(f=>{let v=m&&f.exactMatch(f.getCurrentPath(),n)||f.exactMatch(f.getCurrentPath(),l);if(g.current&&!v){if(!s){u(!1);return}f.registerUnmountingPath(d)}v&&f.isPathsUnmounting()&&f.unregisterUnmountingPath(d),v&&!g.current&&!f.isTransitioning()&&u(!0)},[A,s]),yr(()=>{if(!A)return;let f=m?o.mountDefaultHandler(l):o.mount(l);return o.emitOnPageMount(),()=>{f.cancel()}},[l,A]),yr(()=>()=>{o.unregisterUnmountingPath(d),u(!1)},[]);let T=ri.createElement(yn,{path:n,consumedBy:c},ri.createElement(vo,{mode:"wait",onExitComplete:()=>{o.unregisterUnmountingPath(d),u(!1)}},A&&g.current&&s));return(f=>r?ri.createElement(si,{value:{name:null}},f):f)(T)}import{useEffect as sa,useState as aa}from"react";function Tn(s){let e=w(),[t,n]=aa(e.keyMap.getKeyBinding(s)),o=i=>{e.keyMap.setKeyBinding(s,i),n(i)};return sa(()=>e.keyMap.onKeyBindingChange(s,n).cancel,[s,e.keyMap,n]),[t,o]}function ca(){return w().getLiveGame()}var Sn=(t=>(t.skipAction="skipAction",t.nextAction="nextAction",t))(Sn||{});function Sr({state:s}){let e=w(),t=Ye(),n=ai(null),o=ai(null),i=ai(!1),[r]=$e(q.Preferences.skipDelay),[a]=$e(q.Preferences.skipInterval),[c]=Tn("skipAction");return ua(()=>{if(!e.getLiveGame().gameState.playerCurrent){s.logger.warn("KeyEventAnnouncer","Failed to listen to playerElement events");return}if(!window){s.logger.warn("KeyEventAnnouncer","Failed to listen to window events");return}let d=()=>{o.current&&(clearTimeout(o.current),o.current=null),n.current&&(clearInterval(n.current),n.current=null),i.current=!1},p=g=>{if(e.keyMap.match("skipAction",g.key)&&e.preference.getPreference(q.Preferences.skip)&&!i.current){s.logger.verbose("KeyEventAnnouncer","Skipping");let u=()=>{n.current=setInterval(()=>{s.events.emit(U.EventTypes["event:state.player.skip"],!1)},a)};d(),s.events.emit(U.EventTypes["event:state.player.skip"],!1),i.current=!0,r===0?u():o.current=setTimeout(u,r)}},m=g=>{e.keyMap.match("skipAction",g.key)&&d()};if(e.config.useWindowListener){let g=e.getLiveGame().onWindowEvent("keydown",p).cancel,u=e.getLiveGame().onWindowEvent("keyup",m).cancel;return()=>{d(),g(),u()}}else{let g=e.getLiveGame().onPlayerEvent("keydown",p).cancel,u=e.getLiveGame().onPlayerEvent("keyup",m).cancel;return()=>{d(),g(),u()}}},[t,r,a,c]),Tr.createElement(Tr.Fragment,null)}import{useEffect as bn}from"react";function ci({gameState:s}){let e=s.audioManager,[t]=$e("voiceVolume"),[n]=$e("bgmVolume"),[o]=$e("soundVolume"),[i,r]=$e("globalVolume");return bn(()=>{r(e.getGlobalVolume())},[]),bn(()=>{e.setGroupVolume("voice",t)},[t]),bn(()=>{e.setGroupVolume("bgm",n)},[n]),bn(()=>{e.setGroupVolume("sound",o)},[o]),bn(()=>{e.setGlobalVolume(i)},[i]),null}import{useEffect as pa}from"react";function li({ref:s}){let{ratio:e}=Y();return pa(()=>{let t=s.current;if(!t)return;let n=new ResizeObserver(()=>{e.requestUpdate()});return n.observe(t),()=>{n.disconnect()}},[s.current]),null}import{useEffect as wo,useRef as fa}from"react";import ui,{createContext as ma,useContext as da,useState as br}from"react";var Lt=class Lt{constructor(){this.preloaded=[];this.events=new K}add(e){let t=this.getSrc(e);return t&&this.has(t)?this:(this.preloaded.push(e),this.events.emit(Lt.EventTypes["event:preloaded.add"],e),this.events.emit(Lt.EventTypes["event:preloaded.change"]),this)}get(e){return this.preloaded.find(t=>this.getSrc(t)===e)}has(e){return Array.isArray(e)?e.every(t=>this.has(t)):this.preloaded.some(t=>this.getSrc(t)===e)}remove(e){if(Array.isArray(e)){let n=e.map(o=>this.getSrc(o));return this.preloaded=this.preloaded.filter(o=>!n.includes(this.getSrc(o))),this}let t=this.getSrc(e);return this.preloaded=this.preloaded.filter(n=>this.getSrc(n)!==t),this.events.emit(Lt.EventTypes["event:preloaded.remove"],e),this.events.emit(Lt.EventTypes["event:preloaded.change"]),this}clear(){return this.preloaded=[],this}getSrc(e){return fe.getSrc(e)}};Lt.EventTypes={"event:preloaded.add":"event:preloaded.add","event:preloaded.remove":"event:preloaded.remove","event:preloaded.change":"event:preloaded.change","event:preloaded.mount":"event:preloaded.mount","event:preloaded.ready":"event:preloaded.ready","event:preloaded.unmount":"event:preloaded.unmount"};var Re=Lt;var xo=class s{constructor(e){this.game=e;this.src=new Map;this.preloadTasks=new Map;this.game.addSideEffect(()=>{this.abortAll(),this.src.clear()})}static getImage(e,t,n){return Hi(e,{...n,signal:t})}has(e){return this.src.has(e)}add(e,t){return this.src.set(e,t),this}remove(e){return this.src.delete(e),this}get(e){return this.src.get(e)}clear(){return this.src.clear(),this}size(){return this.src.size}isPreloading(e){return this.preloadTasks.has(e)}preload(e,t){if(this.src.has(t)||this.preloadTasks.has(t)){let p={abort:()=>{},onFinished:()=>p,onErrored:()=>p};return p}let n=t,o={};this.game.hooks.rawTrigger("preloadImage",()=>[n,(p,m)=>{n=p,o={...o,...m}}]);let i=new AbortController,r=i.signal,a=[],l={promise:s.getImage(n,r,o).then(p=>{this.preloadTasks.delete(t),p&&this.add(t,p)}).catch(p=>{e.logger.error("ImageCacheManager",`Failed to preload image: ${t}`,`Reason: ${p}`),a.forEach(m=>m(p))}),controller:i};this.preloadTasks.set(t,l);let d={abort:()=>{i.abort(),this.preloadTasks.delete(t)},onFinished:p=>(l.promise.then(p),d),onErrored:p=>(a.push(p),d)};return d}abortAll(){this.preloadTasks.forEach(e=>{e.controller.abort()}),this.preloadTasks.clear()}abort(e){let t=this.preloadTasks.get(e);t&&(t.controller.abort(),this.preloadTasks.delete(e))}preloadedSrc(){return Array.from(this.src.values())}filter(e){for(let t of this.src.keys())e.includes(t)||this.src.delete(t);return this}};var pi=ma(null);function Ar({children:s}){let e=w(),[t]=br(()=>new Re),[n]=br(()=>new xo(e));return ui.createElement(ui.Fragment,null,ui.createElement(pi,{value:{preloaded:t,cacheManager:n}},s))}function $t(){if(!pi)throw new Error("usePreloaded must be used within a PreloadedProvider");return da(pi)}function vr({state:s}){let{preloaded:e,cacheManager:t}=$t(),n=w(),o=fa(new Set),[i]=$(),r="Preload",a=s.getLastScene()||s.getPreloadingScene(),c=n.getLiveGame().stackModel?.getTopSync()?.node?.action||null,l=n.getLiveGame().story;function d(){s.logger.debug(r,"Preload unmounted"),e.events.emit(Re.EventTypes["event:preloaded.unmount"])}return wo(()=>s.events.on(U.EventTypes["event:state:flushPreloadedScenes"],()=>{i()}).cancel,[]),wo(()=>{if(typeof fetch>"u")return e.events.emit(Re.EventTypes["event:preloaded.ready"]),s.logger.warn(r,"Fetch is not supported in this environment, skipping preload"),d;if(!n.config.preloadAllImages)return e.events.emit(Re.EventTypes["event:preloaded.ready"]),s.logger.debug(r,"Preload all images is disabled, skipping preload"),d;if(n.config.forceClearCache&&(t.clear(),s.logger.weakWarn(r,"Cache cleared")),!l||!a)return s.logger.weakWarn(r,"Story/Scene not found, skipping preload"),d;let p=performance.now(),m=fe.catSrc([...a.srcManager?.src||[],...a.srcManager?.getFutureSrc()||[]]),g=new Yt(n.config.preloadConcurrency,n.config.preloadDelay),u=[],A=s.logger.group(r,!0),T=[];s.logger.debug(r,"preloading:",m,a);for(let R of m.image){let f=fe.getSrc(R);if(f){if(u.push(f),t.has(f)||t.isPreloading(f)||T.includes(f)){s.logger.debug(r,`Image already loaded (${m.image.indexOf(R)+1}/${m.image.length})`,f),T.push(f);continue}T.push(f),g.addTask(()=>new Promise(v=>{t.preload(s,f).onFinished(()=>{s.logger.debug(r,`Image loaded (${m.image.indexOf(R)+1}/${m.image.length})`,f),v()}).onErrored(()=>{s.logger.weakError(r,`Failed to preload image (${m.image.indexOf(R)+1}/${m.image.length})`,f),v()})}))}}return A.end(),g.start().then(()=>{s.logger.info(r,"Image preload",`loaded ${t.size()} images in ${performance.now()-p}ms`),n.config.waitForPreload&&e.events.emit(Re.EventTypes["event:preloaded.ready"]),t.filter(u)}),n.config.waitForPreload||e.events.emit(Re.EventTypes["event:preloaded.ready"]),e.events.emit(Re.EventTypes["event:preloaded.mount"]),d},[a,l]),wo(()=>{o.current.clear()},[a]),wo(()=>{if(typeof fetch>"u"||n.config.preloadAllImages)return;if(!l){s.logger.weakWarn(r,"Story not found, skipping preload");return}let p=performance.now(),m=n.getLiveGame().getAllPredictableActions(l,c,n.config.maxPreloadActions).map(f=>fe.getPreloadableSrc(l,f)).filter(function(f){return f!==null});m.filter(function(f){return f?.activeType==="scene"}).forEach(f=>{o.current.has(f)||o.current.add(f)});let u=fe.catSrc([...o.current,...m]),A=new Yt(n.config.preloadConcurrency,n.config.preloadDelay),T=[],R=s.logger.group(r);s.logger.debug(r,"preloading:",u);for(let f of u.image){let v=fe.getSrc(f);if(v){if(T.push(v),t.has(v)||t.isPreloading(v)){s.logger.debug(r,`Image already loaded (${u.image.indexOf(f)+1}/${u.image.length})`,v);continue}A.addTask(()=>new Promise(G=>{t.preload(s,v).onFinished(()=>{s.logger.debug(r,`Image loaded (${u.image.indexOf(f)+1}/${u.image.length})`,v),G()}).onErrored(()=>{s.logger.weakError(r,`Failed to preload image (${u.image.indexOf(f)+1}/${u.image.length})`,v),G()})}))}}R.end(),A.start().then(()=>{s.logger.info(r,"Image preload (quick reload)",`loaded ${t.size()} images in ${performance.now()-p}ms`),t.filter(T)})},[c,l]),null}import _e,{useMemo as ga,useCallback as mi,useRef as ha}from"react";import ya from"clsx";function di({prompt:s,choices:e,afterChoose:t,state:n,words:o}){let i=w(),r=ha([]),a=mi(g=>(r.current.push(g),r.current.indexOf(g)),[]),c=mi(g=>{let u=r.current.indexOf(g);u!==-1&&r.current.splice(u,1)},[]),l=mi(g=>r.current.indexOf(g),[]),d=i.config.menu,p=ga(()=>e.map(g=>({...g,words:g.prompt.evaluate(He.getCtx({gameState:n}))})),[]);function m(g){t(g)}return _e.createElement(_e.Fragment,null,_e.createElement(ei,{value:{evaluated:p,choose:m,gameState:n}},_e.createElement(ti,{value:{register:a,unregister:c,getIndex:l}},_e.createElement(Ze,{className:"absolute"},s&&_e.createElement(mn,{gameState:n,action:{sentence:s,words:o,character:null},useTypeEffect:!1})),_e.createElement(Dt.Div,{color:"green",border:"dashed",className:ya("absolute"),style:{width:`${i.config.width}px`,height:`${i.config.height}px`}},_e.createElement(d,{items:p.map((g,u)=>u)})))))}function Cr({items:s}){return _e.createElement(uo,{className:"absolute flex flex-col items-center justify-center min-w-full w-full h-full"},s.map(e=>_e.createElement(ho,{key:e,className:"bg-white text-black p-2 mt-2 w-1/2"})))}import Ro from"react";import ko from"react";import fi,{useEffect as xr,useLayoutEffect as wr,useRef as kr,useState as gi}from"react";function Bt({element:s,state:e,skipTransform:t,skipTransition:n,overwriteDefinition:o,onTransform:i,onTransition:r,transitionsProps:a=[],propOverwrite:c}){let[l,d]=gi(null),[p,m]=gi(null),g=fi.useRef(null),[u]=gi(()=>new Mn("displayable.refGroup")),A=kr(u.next()),T=kr(tt()),f=w().getLiveGame().getGameState(),v=typeof a=="function"?a(l):a,[G]=$([p,l,T]);xr(()=>f.events.depends([f.events.on(U.EventTypes["event:state.player.skip"],mt)]).cancel,[p,l,T]),wr(()=>{if(he(),!l)return;if(T.current.some(([Z])=>!Z.current))throw new b("Displayable: Trying to access transition groups before they are mounted");let{controller:k,task:O}=l;return k.onUpdate(Z=>{T.current.forEach(([Le],je)=>{let P=O.resolve[je],E=typeof P=="function"?P:P.resolver;if(!E)throw new b(`Displayable: Trying to resolve element props but found no resolver. (reading: transitionTask.task.resolve[${je}])`);let X=E(...Z),z=D(v[je]||v[v.length-1]||{},X);Mt(Le,c?c(z):z)})}).cancel},[l]),xr(()=>{if(!g.current)throw new Error(`Scope not ready. Using element: ${s.constructor.name}`)},[]),wr(()=>{let k=e.toStyle(f,o);Object.assign(g.current.style,k),f.logger.debug("Displayable","Initial style applied",g.current,k)},[]);function he(){let k=typeof a=="function"?a(l):a;if(!T.current||!T.current.length)throw new b("Displayable: Transition group refs are not initialized correctly");if(T.current.some(([O])=>!O.current))throw new b("Displayable: Trying to access transition groups before they are mounted");T.current.forEach(([O],x)=>{if(!O.current)throw new b("Displayable: Trying to assign properties to unmounted element");Mt(O,k[x]||k[k.length-1]||{})})}function et(k){f.logger.debug("Displayable","Transform applied",e.toStyle(f,o),g.current),G(),i?.(k)}function Mt(k,O){if(!k.current)throw new b("Displayable: Trying to assign properties to unmounted element");let x=k.current,Z={},Le={};Object.keys(O).forEach(P=>{let E=P;E==="style"&&O.style?Object.assign(Z,O.style):O[E]!==void 0&&E!=="key"&&(Le[E]=O[E])}),Object.keys(Z).length>0&&Object.assign(x.style,Z);let je=c?c(Le):Le;for(let[P,E]of Object.entries(je))x.getAttribute(P)!==E&&x.setAttribute(P,E)}function Ke(k,O){p&&(p.abort(),m(null));let x=k.animate(e,{gameState:f,ref:g,overwrites:o}),Z=new re(x);return f.timelines.attachTimeline(Z),x.onSkipControllerRegister(Le=>{Le.onAbort(()=>{Z.abort(),m(null)})}),m(x),x.then(()=>{m(null),et(k),O()}),Z}function bt(k,O){l&&l.controller.complete();let x=k.createTask(f),Z=k.requestAnimations(x.animations),Le=new h().registerSkipController(new L(Z.cancel)),je=new re(Le);Le.skipController.onAbort(()=>{Z.cancel()}),Z.onCanceled(()=>{je.abort(),d(null),f.logger.debug("Displayable","Transition cancelled",k)}),f.timelines.attachTimeline(je),d({task:x,controller:Z,transition:k,resolve:O});let P;if(T.current=x.resolve.map(X=>{let z=fi.createRef(),me=typeof X=="function"?void 0:X.key;if(!me)return[z,u.next()];if(me==="target")return P=u.next(),[z,P];if(me==="current")return[z,A.current];throw new b("Displayable: Invalid key type")}),!P)throw new b("Displayable: No target key found");A.current=P;let E=T.current.map(([X])=>{let z=X.current;return z?.waitForLoad?z.waitForLoad():Promise.resolve()});return Promise.all(E).then(()=>{Z.start(),Z.onComplete(()=>{ne(),d(null),r?.(k),O(),Le.resolve()})}),je}function Fe(k){return f.logger.debug("initDisplayable",s),Ke(F.immediate(e.get()),k)}function mt(){t&&p&&(p.abort(),m(null),f.logger.debug("transform skipped")),n&&l&&(l.controller.complete(),f.logger.debug("transition skipped"))}function tt(){return[[fi.createRef(),A.current]]}function ne(){T.current.forEach(([k])=>{k.current=null}),T.current=tt()}return{transformRef:g,transitionRefs:T.current,isTransforming:!!p,transitionTask:l,initDisplayable:Fe,applyTransform:Ke,applyTransition:bt,updateStyleSync:he,deps:[p,l,T]}}import{useEffect as Ta}from"react";function St(s,e,t=[]){let o=w().getLiveGame().getGameState();return Ta(()=>{let i=typeof e=="function"?e():e;return o.mountState(s,i).unMount},[...t]),[]}function hi({state:s,text:e}){let{ratio:t}=Y(),[n]=$(),{transformRef:o,transitionRefs:i,initDisplayable:r,applyTransform:a,applyTransition:c,updateStyleSync:l,deps:d,isTransforming:p}=Bt({element:e,state:e.transformState,skipTransform:s.game.config.allowSkipTextTransform,skipTransition:s.game.config.allowSkipTextTransition,overwriteDefinition:{overwrite:m=>({width:"fit-content",transform:F.propToCSSTransform(s,m,{translate:[e.config.alignX==="left"?"0%":e.config.alignX==="right"?"-100%":void 0,e.config.alignY==="top"?"100%":e.config.alignY==="bottom"?"0%":void 0]})})},transitionsProps:[{style:{width:"fit-content",whiteSpace:"nowrap",transform:`scale(${t.state.scale})`,transformOrigin:`${e.config.alignX} ${e.config.alignY}`,fontSize:`${e.state.fontSize}px`}}]});return St(e,{initDisplayable:r,applyTransform:a,applyTransition:c,flush:n,updateStyleSync:l},[...d]),ko.createElement(Dt.Div,{"data-element-type":"text"},ko.createElement(Dt.mDiv,{tag:"text.container",color:"green",border:"dashed",layout:p,ref:o,className:"absolute"},i.map(([m,g])=>ko.createElement("span",{key:g,ref:m,className:e.config.className},ko.createElement("span",null,e.state.text)))))}import jt,{useRef as Dr,useState as Rr}from"react";import Po,{useEffect as yi,useRef as Eo,forwardRef as Sa}from"react";var Pr=Sa(({onSizeChanged:s,onLoad:e,autoFit:t=!1},n)=>{let o=Eo(null),{ratio:i}=Y(),[r,a]=Po.useState(()=>i.state.width),[c,l]=Po.useState(()=>i.state.height),d=w(),p=Eo(!1),m=Eo(null),g=Eo(null);Po.useImperativeHandle(n,()=>o.current,[]),yi(()=>{o.current&&Object.defineProperties(o.current,{isLoaded:{value:()=>p.current,configurable:!0},waitForLoad:{value:()=>p.current?Promise.resolve():(m.current||(m.current=new Promise(T=>{g.current=T})),m.current),configurable:!0}})},[]),yi(()=>(u(),i.onUpdate(u)),[s]),yi(()=>{let T=new MutationObserver(R=>{R.forEach(f=>{f.type==="attributes"&&f.attributeName==="src"&&o.current&&u()})});return o.current&&T.observe(o.current,{attributes:!0}),()=>{T.disconnect()}},[s]);function u(){if(o.current&&o.current.naturalWidth)if(o.current.naturalWidth*o.current.naturalHeight===1){let T=i.state.width,R=i.state.height,f=`${T} / ${R}`;a(T),l(R),o.current.style.aspectRatio=f,s&&s(T,R)}else{let T=t?d.config.width/o.current.naturalWidth:1,R=o.current.naturalWidth*i.state.scale*T,f=o.current.naturalHeight*i.state.scale*T;a(R),l(f),o.current.style.aspectRatio="auto",s&&s(R,f)}}function A(){u(),p.current=!0,g.current&&(g.current(),g.current=null,m.current=null),e&&e()}return Po.createElement("img",{ref:o,onLoad:A,width:r,height:c,alt:""})});Pr.displayName="AspectScaleImage";var Er=Pr;import Lr from"clsx";import{motion as ba}from"motion/react";function Do({image:s,state:e}){let[t]=Rr(()=>new K),[n,o]=Rr([]),{cacheManager:i}=$t(),r=Dr([]),a=Dr(null),{transformRef:c,transitionRefs:l,isTransforming:d,initDisplayable:p,applyTransition:m,applyTransform:g,updateStyleSync:u,deps:A}=Bt({element:s,state:s.transformState,skipTransform:e.game.config.allowSkipImageTransform,skipTransition:e.game.config.allowSkipImageTransition,transitionsProps:f=>{let v=f?f.transition._getCurrentSrc():s.state.currentSrc;return[{style:{willChange:"filter",position:"absolute",transformOrigin:"center",backgroundColor:S.isColor(v)?S.colorToString(v):void 0,transform:"none",top:"auto",left:"auto",right:"auto",bottom:"auto",filter:`brightness(${1-s.state.darkness})`},src:S.isImageSrc(v)?S.srcToURL(v):I.DefaultImagePlaceholder},{style:{willChange:"filter",position:"absolute",transformOrigin:"center",transform:"translate(-50%, -50%)",top:"50%",left:"50%",right:"auto",bottom:"auto",maxWidth:"none",maxHeight:"none",filter:"brightness(1)"}}]},propOverwrite:f=>f.src?(!S.isDataURI(f.src)&&!i.has(f.src)&&!i.isPreloading(f.src)&&!r.current.includes(f.src)&&(e.game.getLiveGame().getGameState()?.logger.warn("Image",`Image not preloaded: "${f.src}".
|
|
60
60
|
This may be caused by complicated image action behavior that cannot be predicted.
|
|
61
|
-
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),r.current.push(f.src)),{...f,src:i.get(f.src)||f.src}):f});St(s,{createWearable:f=>{o(
|
|
62
|
-
at Video.tsx: useEffect`),l=()=>{a||!r||(a=!0,s.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();o()},play:()=>{if(!t.current)throw c();let p=t.current;return p.currentTime=0,new Promise(m=>{s.schedule(({retry:g})=>{if(p.readyState<3){let R=()=>{p.removeEventListener("loadeddata",R),g()};p.addEventListener("loadeddata",R);return}let u=()=>{T(),m()},
|
|
63
|
-
at Say.tsx: onElementClick`);return}let l=p=>{t.keyMap.match("nextAction",p.key)&&n.requestComplete()};window.addEventListener("keyup",l);let d=n.events.on(De.Events.simulateClick,()=>{r.current&&r.current.click()});return()=>{window.removeEventListener("keyup",l),d.cancel()}},[n,a]),qr(()=>{let l=t.preference.onPreferenceChange(q.Preferences.autoForward,d=>{d&&n.isEnded()?n.tryScheduleAutoForward():n.cancelAutoForward()});return()=>{l.cancel()}},[n]),It.createElement("div",{"data-element-type":"dialog",className:"w-full h-full"},It.createElement("div",{className:Ua("absolute bottom-0 w-full h-full",!i&&"invisible pointer-events-auto"),onClick:c,style:{...Fn(t.config.useAspectScale,{maxWidth:t.config.dialogWidth,maxHeight:t.config.dialogHeight,transform:`scale(${o.state.scale})`,transformOrigin:"bottom left",width:t.config.width,height:t.config.height})},ref:r},It.createElement("div",{...e},s)))}function Qr({children:s,...e}){let t=
|
|
61
|
+
To fix this issue, you can manually register the image using scene.preloadImage(YourImageSrc). `),r.current.push(f.src)),{...f,src:i.get(f.src)||f.src}):f});St(s,{createWearable:f=>{o(v=>[...v,f])},disposeWearable:f=>{o(v=>v.filter(G=>G.getId()!==f.getId()))},initDisplayable:p,applyTransform:g,applyTransition:m,events:t,updateStyleSync:u},[...A]);function T(f,v){a.current&&(t.emit("event:image.onLoad"),Object.assign(a.current.style,{width:`${f}px`,height:`${v}px`}))}function R(){t.emit("event:image.onLoad")}return jt.createElement(ba.div,{layout:d,ref:c,className:"absolute w-max h-max","data-element-type":"image"},jt.createElement("div",{className:"relative h-full w-full",ref:a,"data-image-id":s.getId()},l.map(([f,v],G)=>jt.createElement(Er,{key:v,ref:f,autoFit:s.config.autoFit,onSizeChanged:G===0?T:void 0,onLoad:G===0?R:void 0})),jt.createElement("div",{className:Lr("w-full h-full top-0 left-0 absolute")},n.map(f=>jt.createElement("div",{className:Lr("w-full h-full relative"),key:"wearable-"+f.getId()},jt.createElement(Do,{image:f,state:e}))))))}function Ti({state:s,displayable:e}){return Ro.createElement(Ro.Fragment,null,e.map(t=>{if(t instanceof Et)return Ro.createElement(hi,{state:s,text:t,key:"text-"+t.getId()});if(t instanceof I)return Ro.createElement(Do,{state:s,image:t,key:"image-"+t.getId()});throw new Error("Unsupported displayable type: "+(t?.constructor?.name||t))}))}import Lo,{useEffect as Aa}from"react";import{motion as va}from"motion/react";function Ir({state:s,layer:e,children:t}){let{transformRef:n,transitionRefs:o,initDisplayable:i,applyTransition:r,applyTransform:a,updateStyleSync:c,deps:l}=Bt({element:e,state:e.transformState,skipTransform:s.game.config.allowSkipLayersTransform,skipTransition:!1,transitionsProps:[{style:{width:"100%",height:"100%",transformOrigin:"center"}}]});return St(e,{initDisplayable:i,applyTransition:r,applyTransform:a,updateStyleSync:c},[...l]),Aa(()=>(s.logger.debug("Layer","Layer mounted",e.getId()),()=>{s.logger.debug("Layer","Layer unmounted",e.getId())}),[]),Lo.createElement(Lo.Fragment,null,Lo.createElement(va.div,{layout:!0,className:"absolute w-full h-full",ref:n,"data-element-type":"layer","data-layer-id":e.getId(),key:`layer-${e.getId()}`},o.map(([d,p])=>Lo.createElement("div",{className:"relative w-full h-full",ref:d,key:p},t))))}import Ca from"clsx";import{useEffect as Mr,useRef as xa}from"react";import qt from"react";function Si({state:s,className:e,elements:t}){let{scene:n,layers:o,texts:i,menus:r}=t,a=xa(!1);return Mr(()=>n.events.depends([n.events.on(Pe.EventTypes["event:scene.preUnmount"],()=>{if(n.state.backgroundMusic)return s.audioManager.stop(n.state.backgroundMusic).then(()=>{n.state.backgroundMusic=null})})]).cancel,[]),Mr(()=>(n.events.emit(Pe.EventTypes["event:scene.mount"]),s.logger.debug("Scene","Scene mounted",n.getId()),()=>{n.events.emit(Pe.EventTypes["event:scene.unmount"]),s.logger.debug("Scene","Scene unmounted",n.getId())}),[]),St(n,{setBackgroundMusic(c,l){return new Promise(d=>{n.state.backgroundMusic&&async function(){n.state.backgroundMusic&&s.audioManager.isManaged(n.state.backgroundMusic)&&await s.audioManager.stop(n.state.backgroundMusic,l),c?(await s.audioManager.play(c,{end:c.state.volume,duration:l}),n.state.backgroundMusic=c):n.state.backgroundMusic=null,d()}()})}}),qt.createElement("div",{className:Ca(e,"w-full h-full absolute")},[...o.entries()].sort(([c],[l])=>c.state.zIndex-l.state.zIndex).map(([c,l])=>qt.createElement(Ir,{state:s,layer:c,key:c.getId()},qt.createElement(Ti,{state:s,displayable:l}))),i.map(({action:c,onClick:l})=>qt.createElement(mn,{gameState:s,key:"say-"+c.id,action:c,onFinished:d=>{d!==void 0&&(a.current=d),l(),s.stage.next()},useTypeEffect:!a.current})),r.map(({action:c,onClick:l},d)=>qt.createElement("div",{key:"menu-"+d,"data-element-type":"menu"},qt.createElement(di,{state:s,prompt:c.prompt,choices:c.choices,afterChoose:p=>{a.current=!1,l(p),s.stage.next()},words:c.words}))))}import wa from"react";import{useEffect as bi,useRef as ka}from"react";import{useCallback as Gr}from"react";function Nr(s){let e=Gr(()=>{if(!s.current)return;let n=s.current;n.style.opacity="1",n.style.pointerEvents="auto",n.style.visibility="visible"},[s]),t=Gr(()=>{if(!s.current)return;let n=s.current;n.style.opacity="0",n.style.pointerEvents="none",n.style.visibility="hidden"},[s]);return{show:e,hide:t}}function Ai({gameState:s,video:e}){let t=ka(null),{show:n,hide:o}=Nr(t);bi(()=>s.events.depends([s.events.on(U.EventTypes["event:state.player.skip"],()=>{s.game.config.allowSkipVideo&&(i(),s.logger.log("NarraLeaf-React: Video","Skipped"))})]).cancel,[]),bi(()=>{o(),e.state.display&&n()},[]),bi(()=>{if(!t.current)return;let r=t.current,a=!1,c=()=>new b(`Failed to add event listener, ref is not available
|
|
62
|
+
at Video.tsx: useEffect`),l=()=>{a||!r||(a=!0,s.mountState(e,{show:()=>{if(!t.current)throw c();n()},hide:()=>{if(!t.current)throw c();o()},play:()=>{if(!t.current)throw c();let p=t.current;return p.currentTime=0,new Promise(m=>{s.schedule(({retry:g})=>{if(p.readyState<3){let R=()=>{p.removeEventListener("loadeddata",R),g()};p.addEventListener("loadeddata",R);return}let u=()=>{T(),m()},A=()=>{T(),m()},T=()=>{p.removeEventListener("ended",u),p.removeEventListener("stopped",A)};p.addEventListener("ended",u),p.addEventListener("stopped",A),d.push(T),p.play().catch(R=>{s.logger.error("Failed to play video: "+R),T(),m()})},10)})},pause:()=>{if(!t.current)throw c();t.current.pause()},resume:()=>{if(!t.current)throw c();return t.current.play()},stop:()=>{if(!t.current)throw c();t.current.pause(),t.current.dispatchEvent(new Event("stopped"))},seek:p=>{if(!t.current)throw c();t.current.currentTime=p}}))},d=[];return r.addEventListener("canplay",l),()=>{a=!1,r.removeEventListener("canplay",l),d.forEach(p=>p()),r.currentTime>0&&r.pause(),s.isStateMounted(e)&&s.unMountState(e)}},[s,e]);function i(){t.current&&(t.current.pause(),t.current.currentTime=0,t.current.dispatchEvent(new Event("stopped")))}return wa.createElement("video",{ref:t,src:e.config.src,preload:"auto",muted:e.config.muted,playsInline:!0,width:"100%",height:"100%",onContextMenu:r=>r.preventDefault()})}import Pa from"clsx";import Hr,{useEffect as Ur,useState as Ea}from"react";function vi({children:s,className:e,gameState:t}){let[n,o]=Ea({}),{ratio:i}=Y(),r=w(),[a]=$(),c=r.config.minWidth,l=r.config.minHeight;return Ur(()=>{t.logger.debug("AspectRatio","mount, using interval",r.config.ratioUpdateInterval);let d=()=>{if(i.isLocked()){t.logger.weakWarn("Ratio is locked, skipping update");return}let u=document.getElementById(r.config.contentContainerId);if(u){let A=u.clientWidth,T=u.clientHeight,R=r.config.aspectRatio,f,v;A/T>R?(f=T*R,v=T):(f=A,v=A/R),f<c&&(f=c),v<l&&(v=l),o({width:`${f}px`,height:`${v}px`,margin:"auto",position:"absolute",top:"0",bottom:"0",left:"0",right:"0",display:"flex",alignItems:"center",justifyContent:"center"});let G=f/r.config.width;i.update(f,v,G),i.updateMin(c,l),a()}};i.setUpdate(d);let m=Gi(()=>{d()},r.config.ratioUpdateInterval);m(),window.addEventListener("resize",m);let g=i.onRequestedUpdate(m);return()=>{window.removeEventListener("resize",m),g()}},[i,r.config.ratioUpdateInterval]),Ur(()=>t.events.on(U.EventTypes["event:state.player.requestFlush"],a).cancel,[t]),Hr.createElement("div",{id:r.config.contentContainerId,style:{position:"relative",width:"100%",height:"100%",overflow:"hidden"}},Hr.createElement("div",{className:Pa(e),style:n},s))}import Kr,{useEffect as Da,useRef as Ra,useState as Fr}from"react";function Ci({src:s,width:e,height:t}){let[n,o]=Fr({x:0,y:0}),[i,r]=Fr(!1),a=Ra(null),{ratio:c}=Y();return Da(()=>{let l=d=>{if(a.current){let p=a.current.getBoundingClientRect(),m=d.clientX-p.left,g=d.clientY-p.top;o({x:m,y:g}),i||r(!0)}};return window.addEventListener("mousemove",l),()=>{window.removeEventListener("mousemove",l)}},[i]),Kr.createElement(Ze,{ref:a,className:"overflow-hidden absolute"},Kr.createElement("img",{src:s,style:{position:"absolute",left:n.x,top:n.y,width:e,height:t,pointerEvents:"none",zIndex:1001,display:i?"block":"none",cursor:"none",transform:`scale(${c.state.scale})`},alt:""}))}import Wr from"react";import ut from"react";function xi({error:s,errorInfo:e}){return w().config.app.debug?ut.createElement("div",{className:"text-left"},ut.createElement("h1",null,"NarraLeaf-React cannot initialize the player correctly. (development mode)"),ut.createElement("p",{className:"text-red-700"},"Message: ",s.message),ut.createElement("pre",null,"Error Stack: ",s?.stack),ut.createElement("pre",null,"Component Stack: ",e?.componentStack),ut.createElement("pre",null,"Digest: ",e?.digest)):ut.createElement("div",{className:"bg-white w-full h-full"},ut.createElement("h1",null,"NarraLeaf-React crashed due to an unknown error."),ut.createElement("p",null,"Please contact the game developer for further assistance."))}var Io=class extends Wr.Component{constructor(){super(...arguments);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t,errorInfo:null}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n}),this.props.onError?.(t,n),console.error(t,n)}render(){return this.state.hasError?Wr.createElement(xi,{error:this.state.error,errorInfo:this.state.errorInfo}):this.props.children}};import zr from"clsx";import B,{useEffect as vn,useReducer as Ga,useState as Cn}from"react";import{flushSync as $r}from"react-dom";import{useRef as La}from"react";import{useEffect as Ia}from"react";function Or({gameState:s}){let e=La(null);return Ia(()=>(e.current=requestAnimationFrame(()=>{setTimeout(()=>{s.events.emit(U.EventTypes["event:state.onRender"])},0)}),()=>{e.current!==null&&cancelAnimationFrame(e.current)}),[s.deps]),null}import An,{useEffect as Ma}from"react";function wi({gameState:s}){let[e]=$(),{ratio:t}=Y(),n=s.notificationMgr;Ma(()=>n.onFlush(()=>{e()}).cancel,[]);let o=s.game.config.notification;return An.createElement("div",{style:{transform:`scale(${t.state.scale})`,transformOrigin:"left top"},className:"absolute top-0 left-0 w-full h-full pointer-events-none","data-element-type":"notification"},An.createElement(o,{notifications:n.toArray()}))}function Vr({notifications:s}){return An.createElement(To,{className:"absolute top-0 left-0 w-full h-full"},s.map(({id:e,message:t})=>An.createElement("div",{key:e,className:"absolute top-0 left-0 w-[100px] h-[80px]"},An.createElement("span",{className:"text-white text-2xl font-bold"},t))))}function Br({story:s=cn.empty(),width:e,height:t,className:n,onReady:o,onEnd:i,onError:r,children:a,active:c=!0}){let[l,d]=Ga(ne=>ne+1,0),[p,m]=Cn(0),g=w(),[u]=Cn(()=>new U(g,{update:d,forceUpdate:()=>{u.logger.weakWarn("Player","force update"),$r(()=>{d()})},forceRemount:()=>{u.logger.weakWarn("Player","force remount"),$r(()=>{m(ne=>ne+1),d()})},next:Fe})),A=B.createRef(),T=B.createRef(),[R,f]=Cn(!1),v=B.useRef(!1),G=B.useRef(null),he=B.useRef(null),{preloaded:et}=$t(),[Mt,Ke]=Cn(!1),[bt]=Cn(new Map);function Fe(){let ne=()=>{bt.forEach(x=>x.cancel())};if(u.rollLock.isLocked())return;ne();let k=!1,O=0;for(;!k;){if(O++>g.config.maxStackModelLoop)throw new b("Max stack model loop reached");let x=g.getLiveGame().next();if(!x){if(g.getLiveGame().stackModel&&!g.getLiveGame().stackModel.isEmpty())continue;break}if(h.isAwaitable(x)){if(G.current===x)break;G.current=x,x.onSettled(()=>{G.current===x&&(G.current=null),Fe()}),k=!0;break}if(x instanceof Nt){if(he.current===x)break;he.current=x,x.nextUnlock().then(()=>{he.current===x&&(he.current=null),Fe()}),k=!0;break}if(Ee.isCalledActionResult(x)&&x.wait&&Ee.isStackModelsAwaiting(x.wait.type,x.wait.stackModels)){if(G.current===x)break;G.current=x,x.wait&&Ee.executeStackModelGroup(x.wait.type,x.wait.stackModels).then(()=>{G.current===x&&(G.current=null),Fe()}),k=!0;break}u.handle(x)}u.stage.update()}vn(()=>(g.getLiveGame().setGameState(u),s&&!g.getLiveGame().isPlaying()&&g.getLiveGame().loadStory(s),u.playerCurrent=A.current,u.mainContentNode=T.current,()=>{g.getLiveGame().setGameState(void 0),u.playerCurrent=null}),[g,s]),vn(()=>Ie(()=>{f(!0);let ne=u.getLastScene(),k=[];ne?k.push(ne.events.once("event:scene.mount",()=>{u.stage.next()}).cancel):u.stage.next();let O=u.events.on(U.EventTypes["event:state.end"],()=>{i&&i({game:g,gameState:u,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable()})});return u.stage.update(),()=>{ne&&k.forEach(x=>x()),O.cancel()}}),[]),vn(()=>Ie(()=>{R&&o&&!v.current&&(v.current=!0,u.stage.forceUpdate(),g.hooks.trigger("init",[]),o({game:g,gameState:u,liveGame:g.getLiveGame(),storable:g.getLiveGame().getStorable()}))}),[R]),vn(()=>et.events.depends([et.events.on(Re.EventTypes["event:preloaded.ready"],()=>{Ke(!0),u.stage.update(),s&&Fe()})]).cancel,[]),vn(()=>{u.flushDep=l},[l]);let mt=e||g.config.width,tt=t||g.config.height;return B.createElement(Io,{onError:r},B.createElement("div",{style:{width:typeof mt=="number"?`${mt}px`:mt,height:typeof tt=="number"?`${tt}px`:tt},className:zr(n,"__narraleaf_content-player"),ref:A,tabIndex:0},B.createElement(vi,{className:zr("flex-grow overflow-auto"),gameState:u},B.createElement(li,{ref:A}),B.createElement(ci,{gameState:u}),B.createElement(Or,{gameState:u}),B.createElement(Ze,{className:"absolute",ref:T,style:{cursor:u.game.config.cursor?"none":"auto",overflow:u.game.config.showOverflow?"visible":"hidden"}},g.config.cursor&&B.createElement(Ci,{src:g.config.cursor,width:g.config.cursorWidth,height:g.config.cursorHeight}),B.createElement(Na,{show:Mt&&c,key:p},B.createElement(Sr,{state:u}),u.getSceneElements().map(ne=>B.createElement(Si,{key:"scene-"+ne.scene.getId(),state:u,elements:ne})),u.getVideos().map((ne,k)=>B.createElement("div",{className:"w-full h-full absolute",key:"video-"+k,"data-element-type":"video"},B.createElement(Ai,{gameState:u,video:ne})))),B.createElement(vr,{state:u}),B.createElement(hr,null,a),B.createElement(wi,{gameState:u})))))}function Na({children:s,show:e}){return B.createElement(B.Fragment,null,e?s:null)}import"client-only";import Qt from"react";function jr({children:s,game:e}){return Qt.createElement(Qt.Fragment,null,Qt.createElement(tr,null,Qt.createElement(Yi,{game:e},Qt.createElement(Ar,null,Qt.createElement(er,null,s)))))}var Ha=(i=>(i.image="narraleaf:image",i.text="narraleaf:text",i.layer="narraleaf:layer",i.scene="narraleaf:scene",i.video="narraleaf:video",i))(Ha||{});import Ua from"clsx";import It,{useEffect as qr,useRef as Ka}from"react";function Fa({children:s,...e}){let t=w(),n=lt(),{ratio:o}=Y(),[i]=$e(q.Preferences.showDialog),r=Ka(null),[a]=Tn("nextAction");function c(){n.requestComplete()}return qr(()=>{if(!window){console.warn(`Failed to add event listener, window is not available
|
|
63
|
+
at Say.tsx: onElementClick`);return}let l=p=>{t.keyMap.match("nextAction",p.key)&&n.requestComplete()};window.addEventListener("keyup",l);let d=n.events.on(De.Events.simulateClick,()=>{r.current&&r.current.click()});return()=>{window.removeEventListener("keyup",l),d.cancel()}},[n,a]),qr(()=>{let l=t.preference.onPreferenceChange(q.Preferences.autoForward,d=>{d&&n.isEnded()?n.tryScheduleAutoForward():n.cancelAutoForward()});return()=>{l.cancel()}},[n]),It.createElement("div",{"data-element-type":"dialog",className:"w-full h-full"},It.createElement("div",{className:Ua("absolute bottom-0 w-full h-full",!i&&"invisible pointer-events-auto"),onClick:c,style:{...Fn(t.config.useAspectScale,{maxWidth:t.config.dialogWidth,maxHeight:t.config.dialogHeight,transform:`scale(${o.state.scale})`,transformOrigin:"bottom left",width:t.config.width,height:t.config.height})},ref:r},It.createElement("div",{...e},s)))}function Qr({children:s,...e}){let t=lt();return!t.config.action.sentence||!t.config.action.words?null:It.createElement(Fa,{...e},s)}var la=Qr;function Xr(){return It.createElement(Qr,null,It.createElement(bo,null),It.createElement(ii,null))}var Mo={say:Xr,menu:Cr,notification:Vr};var Go=class{constructor(e){this.game=e;this.plugins=[];this.registerAll()}use(e){return this.plugins.push(e),this}register(e){e.register(this.game)}registerAll(){this.plugins.forEach(e=>e.register(this.game))}unregisterAll(){this.plugins.forEach(e=>e.unregister(this.game))}has(e){return this.plugins.some(t=>t.name===e.name)}};var xn=class{constructor(e={}){this.keyMap=e;this.events=new K}setKeyBinding(e,t){this.keyMap[e]=t,this.events.emit("event:keyMap.change",e,t)}getKeyBinding(e){return this.keyMap[e]??null}addKeyBinding(e,t){if(t===null)return;let n=this.getKeyBinding(e)??[],o=i=>Array.isArray(i)?i:[i];Array.isArray(n)?this.setKeyBinding(e,[...n,...o(t)]):this.setKeyBinding(e,[n,...o(t)])}getKeyBindings(){return this.keyMap}onKeyBindingChange(e,t){return this.events.on("event:keyMap.change",(n,o)=>{n===e&&t(o)})}importKeyBindings(e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setKeyBinding(t,e[t])}exportKeyBindings(){return this.keyMap}match(e,t){let n=this.getKeyBinding(e);return n===null?!1:Array.isArray(n)?n.includes(t)||n.some(o=>o.toLowerCase()===t.toLowerCase()):n===t||n.toLowerCase()===t.toLowerCase()}};var Jr=(e=>(e.game="game",e))(Jr||{}),pt=class pt{constructor(e){this.hooks=new Nn;this.liveGame=null;this.sideEffect=[];this.freezeFields=[];this.preference=new pn(pt.DefaultPreference);this.keyMap=new xn({skipAction:["Control"],nextAction:[" "]});this.config=D(pt.DefaultConfig,e),this.plugins=new Go(this),this.router=new Tt(this)}configure(e){let[t,n]=Vi(e,this.freezeFields);return n.length>0&&console.warn(`NarraLeaf-React [Game] The following fields are not allowed to be configured: ${n.join(", ")}`),this.config=D(this.config,t),this.getLiveGame().getGameState()?.events.emit(U.EventTypes["event:state.player.requestFlush"]),this}configureAndFreeze(e){return this.configure(e),this.freeze(Object.keys(e)),this}freeze(e){return this.freezeFields.push(...e),this}use(e){return this.plugins.has(e)||this.plugins.use(e).register(e),this}getLiveGame(){if(!this.liveGame){let e=this.createLiveGame();return this.liveGame=e,e}return this.liveGame}dispose(){this.plugins.unregisterAll(),this.liveGame?.dispose(),this.sideEffect.forEach(e=>e())}addSideEffect(e){this.sideEffect.push(e)}createLiveGame(){return new yt(this)}};pt.defaultSettings={volume:1},pt.DefaultPreference={autoForward:!1,skip:!0,showDialog:!0,gameSpeed:1,cps:10,voiceVolume:1,bgmVolume:1,soundVolume:1,globalVolume:1,skipDelay:500,skipInterval:100},pt.Preferences={autoForward:"autoForward",skip:"skip",showDialog:"showDialog",gameSpeed:"gameSpeed",cps:"cps",voiceVolume:"voiceVolume",bgmVolume:"bgmVolume",soundVolume:"soundVolume",globalVolume:"globalVolume",skipDelay:"skipDelay",skipInterval:"skipInterval"},pt.DefaultConfig={app:{debug:!1,logger:{log:!1,info:!1,warn:!0,error:!0,debug:!1,trace:!1,verbose:!1},inspector:!1,guard:{invalidExposedStateUnmounting:!0,unexpectedTimelineStatusChange:!0}},contentContainerId:"__narraleaf_content",aspectRatio:16/9,minWidth:800,minHeight:450,width:1920,height:1080,useWindowListener:!0,ratioUpdateInterval:50,preloadDelay:100,preloadConcurrency:5,waitForPreload:!0,preloadAllImages:!0,forceClearCache:!1,maxPreloadActions:10,cursor:null,cursorHeight:30,cursorWidth:30,showOverflow:!1,maxRouterHistory:10,screenshotQuality:1,useAspectScale:!0,autoForwardDelay:3*1e3,autoForwardDefaultPause:1e3,allowSkipImageTransform:!0,allowSkipImageTransition:!0,allowSkipBackgroundTransform:!0,allowSkipBackgroundTransition:!1,allowSkipTextTransform:!0,allowSkipTextTransition:!0,allowSkipLayersTransform:!0,allowSkipVideo:!1,animationPropagate:!1,dialogWidth:1920,dialogHeight:1080*.2,defaultTextColor:"#000",defaultNametagColor:"#000",notification:Mo.notification,menu:Mo.menu,dialog:Mo.say,onError:e=>{console.error(e)},fontSize:16,fontWeight:400,fontWeightBold:700,fontFamily:"sans-serif",stage:null,defaultMenuChoiceColor:"#000",maxStackModelLoop:1e3,maxActionHistory:100},pt.GameSettingsNamespace=Jr;var q=pt;var ki=class s extends ot{constructor(t,n){super();this.duration=t;this.easing=n}createTask(){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(t=>({style:{opacity:1-t}})),this.asTarget(t=>({style:{opacity:t}}))]}}copy(){return new s(this.duration,this.easing)}};var Pi=class s extends ot{constructor(t,n=[0,0],o){super();this.duration=t;this.startPos=n;this.easing=o}createTask(t){return{animations:[{type:0,start:0,end:1,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[0],end:0,duration:this.duration,ease:this.easing},{type:0,start:this.startPos[1],end:0,duration:this.duration,ease:this.easing}],resolve:[this.asPrev(()=>({})),this.asTarget((n,o,i)=>({style:{opacity:n,...S.offset(["50%","50%"],[o,i],t.getStory().getInversionConfig()),transform:"translate(-50%, 50%)"}}))]}}copy(){return new s(this.duration,this.startPos,this.easing)}};var Ei=class extends ln{constructor(){super();this.unlocked={};this.setupActions()}serialize(){return{unlocked:this.unlocked}}deserialize(t){this.unlocked=t.unlocked}add(t,n){return this.trigger("add",t,n)}has(t){return new ue(()=>this.unlocked[t]!==void 0)}remove(t){return this.trigger("remove",t)}clear(){return this.trigger("clear")}$remove(t){delete this.unlocked[t]}$clear(){this.unlocked={}}$get(t){return this.unlocked[t]}$set(t,n){this.unlocked[t]=n}$getAll(){return this.unlocked}$has(t){return this.unlocked[t]!==void 0}setupActions(){this.on("add",(t,n,o)=>{let i={gameState:t.gameState,game:t.game,liveGame:t.liveGame,storable:t.storable},r=typeof o=="function"?o(i):o;this.unlocked[n]=r}),this.on("remove",(t,n)=>{delete this.unlocked[n]}),this.on("clear",t=>{this.$clear()})}};if(typeof document<"u"){let s=document.createElement("style");s.textContent=`/*! tailwindcss v4.1.8 | MIT License | https://tailwindcss.com */
|
|
64
64
|
@layer properties{@supports ((-webkit-hyphens:none) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial}}}.invisible{visibility:hidden}.visible{visibility:visible}.absolute{position:absolute}.relative{position:relative}.static{position:static}.z-20{z-index:20}.container{width:100%}.block{display:block}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline-block{display:inline-block}.h-\\[80px\\]{height:80px}.h-full{height:100%}.h-max{height:-moz-max-content;height:max-content}.w-1\\/2{width:50%}.w-\\[100px\\]{width:100px}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-full{min-width:100%}.flex-grow{flex-grow:1}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.resize{resize:both}.flex-col{flex-direction:column}.items-center{align-items:center}.justify-center{justify-content:center}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.text-center{text-align:center}.text-left{text-align:left}.align-bottom{vertical-align:bottom}.break-all{word-break:break-all}.whitespace-pre-wrap{white-space:pre-wrap}.italic{font-style:italic}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.invert{--tw-invert:invert(100%);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,ease);transition-duration:var(--tw-duration,0s)}.__narraleaf_content-player *{-webkit-user-select:none;-moz-user-select:none;user-select:none}.__narraleaf_content-player img{pointer-events:none;-webkit-user-drag:none;-webkit-user-select:none}.__narraleaf_content-player .pointer-disabled{pointer-events:none}.__narraleaf_content-player .pointer-disabled>:not(.pointer-disabled){pointer-events:auto}.__narraleaf_content-player img:before,.__narraleaf_content-player img:after{content:none!important;border:none!important}.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.bg-cover{background-size:cover}.bg-center{background-position:50%}.pointer-events-auto-rest *{pointer-events:auto}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}\r
|
|
65
|
-
`,document.head.appendChild(s)}export{Ct as Align,jn as Character,Ge as CommonPosition,_t as CommonPositionType,$o as Condition,
|
|
65
|
+
`,document.head.appendChild(s)}export{Ct as Align,jn as Character,Ge as CommonPosition,_t as CommonPositionType,$o as Condition,Ve as Control,be as Coord2D,la as Dialog,ki as Dissolve,Ha as ExposedStateType,Pi as FadeIn,Ei as Gallery,q as Game,uo as GameMenu,jr as GameProviders,U as GameState,I as Image,ot as ImageTransition,Ze as Isolated,ho as Item,Sn as KeyBindingType,xn as KeyMap,ue as Lambda,Wt as Layer,ea as Layout,yn as LayoutRouterProvider,yt as LiveGame,Bo as Menu,rt as Namespace,bo as Nametag,To as Notifications,ra as Page,si as PageInjectContext,Te as Pause,Kt as Persistent,Br as Player,pn as Preference,_i as RootPath,Pe as Scene,He as Script,te as Sentence,ln as Service,Ae as Sound,bs as Stage,an as Storable,cn as Story,Et as Text,rn as TextTransition,Ns as Texts,F as Transform,Qe as Transition,Qo as Video,H as Word,is as b,os as c,rs as i,zs as useDialog,w as useGame,Tn as useKeyBinding,ca as useLiveGame,Qs as useParams,qs as usePathname,$e as usePreference,Xs as useQueryParams,Ye as useRouter};
|