@rive-app/canvas-lite 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/rive.js ADDED
@@ -0,0 +1,2374 @@
1
+ (function webpackUniversalModuleDefinition(root, factory) {
2
+ if(typeof exports === 'object' && typeof module === 'object')
3
+ module.exports = factory();
4
+ else if(typeof define === 'function' && define.amd)
5
+ define([], factory);
6
+ else if(typeof exports === 'object')
7
+ exports["rive"] = factory();
8
+ else
9
+ root["rive"] = factory();
10
+ })(this, () => {
11
+ return /******/ (() => { // webpackBootstrap
12
+ /******/ "use strict";
13
+ /******/ var __webpack_modules__ = ([
14
+ /* 0 */,
15
+ /* 1 */
16
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
17
+
18
+ __webpack_require__.r(__webpack_exports__);
19
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
20
+ /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
21
+ /* harmony export */ });
22
+
23
+ var Rive = (() => {
24
+ var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
25
+
26
+ return (
27
+ function(moduleArg = {}) {
28
+
29
+ var h=moduleArg,ba,ca;h.ready=new Promise((b,a)=>{ba=b;ca=a});
30
+ function da(){function b(m){const l=d;c=a=0;d=new Map;l.forEach(p=>{try{p(m)}catch(k){console.error(k)}});this.fb();e&&e.Db()}let a=0,c=0,d=new Map,e=null,f=null;this.requestAnimationFrame=function(m){a||(a=requestAnimationFrame(b.bind(this)));const l=++c;d.set(l,m);return l};this.cancelAnimationFrame=function(m){d.delete(m);a&&0==d.size&&(cancelAnimationFrame(a),a=0)};this.Bb=function(m){f&&(document.body.remove(f),f=null);m||(f=document.createElement("div"),f.style.backgroundColor="black",f.style.position=
31
+ "fixed",f.style.right=0,f.style.top=0,f.style.color="white",f.style.padding="4px",f.innerHTML="RIVE FPS",m=function(l){f.innerHTML="RIVE FPS "+l.toFixed(1)},document.body.appendChild(f));e=new function(){let l=0,p=0;this.Db=function(){var k=performance.now();p?(++l,k-=p,1E3<k&&(m(1E3*l/k),l=p=0)):(p=k,l=0)}}};this.yb=function(){f&&(document.body.remove(f),f=null);e=null};this.fb=function(){}}
32
+ function ea(b){console.assert(!0);const a=new Map;let c=-Infinity;this.push=function(d){d=d+((1<<b)-1)>>b;a.has(d)&&clearTimeout(a.get(d));a.set(d,setTimeout(function(){a.delete(d);0==a.length?c=-Infinity:d==c&&(c=Math.max(...a.keys()),console.assert(c<d))},1E3));c=Math.max(d,c);return c<<b}}
33
+ const ha="createConicGradient createImageData createLinearGradient createPattern createRadialGradient getContextAttributes getImageData getLineDash getTransform isContextLost isPointInPath isPointInStroke measureText".split(" "),ka=new function(){function b(){if(!a){var t=document.createElement("canvas"),g={alpha:1,depth:0,stencil:0,antialias:0,premultipliedAlpha:1,preserveDrawingBuffer:0,preferLowPowerToHighPerformance:0,failIfMajorPerformanceCaveat:0,enableExtensionsByDefault:1,explicitSwapControl:1,
34
+ renderViaOffscreenBackBuffer:1};let n=t.getContext("webgl2",g);if(n)c=2;else if(n=t.getContext("webgl",g))c=1;else return console.log("No WebGL support. Image mesh will not be drawn."),!1;d=Math.min(n.getParameter(n.MAX_RENDERBUFFER_SIZE),n.getParameter(n.MAX_TEXTURE_SIZE));function w(H,x,A){x=n.createShader(x);n.shaderSource(x,A);n.compileShader(x);A=n.getShaderInfoLog(x);if(0<A.length)throw A;n.attachShader(H,x)}t=n.createProgram();w(t,n.VERTEX_SHADER,"attribute vec2 vertex;\n attribute vec2 uv;\n uniform vec4 mat;\n uniform vec2 translate;\n varying vec2 st;\n void main() {\n st = uv;\n gl_Position = vec4(mat2(mat) * vertex + translate, 0, 1);\n }");
35
+ w(t,n.FRAGMENT_SHADER,"precision highp float;\n uniform sampler2D image;\n varying vec2 st;\n void main() {\n gl_FragColor = texture2D(image, st);\n }");n.bindAttribLocation(t,0,"vertex");n.bindAttribLocation(t,1,"uv");n.linkProgram(t);g=n.getProgramInfoLog(t);if(0<g.trim().length)throw g;e=n.getUniformLocation(t,"mat");f=n.getUniformLocation(t,"translate");n.useProgram(t);n.bindBuffer(n.ARRAY_BUFFER,n.createBuffer());
36
+ n.enableVertexAttribArray(0);n.enableVertexAttribArray(1);n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,n.createBuffer());n.uniform1i(n.getUniformLocation(t,"image"),0);n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0);a=n}return!0}let a=null,c=0,d=0,e=null,f=null,m=0,l=0;this.Mb=function(){b();return d};this.vb=function(t){if(!b())return null;const g=a.createTexture();a.bindTexture(a.TEXTURE_2D,g);a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,t);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE);
37
+ a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR);2==c?(a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR_MIPMAP_LINEAR),a.generateMipmap(a.TEXTURE_2D)):a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR);return g};const p=new ea(8),k=new ea(8),r=new ea(10),u=new ea(10);this.Ab=function(t,g,n,w,H){if(b()){var x=p.push(t),A=k.push(g);if(a.canvas.width!=x||a.canvas.height!=A)a.canvas.width=x,a.canvas.height=A;
38
+ a.viewport(0,A-g,t,g);a.disable(a.SCISSOR_TEST);a.clearColor(0,0,0,0);a.clear(a.COLOR_BUFFER_BIT);a.enable(a.SCISSOR_TEST);n.sort((B,fa)=>fa.jb-B.jb);x=r.push(w);m!=x&&(a.bufferData(a.ARRAY_BUFFER,8*x,a.DYNAMIC_DRAW),m=x);x=0;for(var J of n)a.bufferSubData(a.ARRAY_BUFFER,x,J.Ra),x+=4*J.Ra.length;console.assert(x==4*w);for(var Q of n)a.bufferSubData(a.ARRAY_BUFFER,x,Q.mb),x+=4*Q.mb.length;console.assert(x==8*w);x=u.push(H);l!=x&&(a.bufferData(a.ELEMENT_ARRAY_BUFFER,2*x,a.DYNAMIC_DRAW),l=x);J=0;for(var aa of n)a.bufferSubData(a.ELEMENT_ARRAY_BUFFER,
39
+ J,aa.indices),J+=2*aa.indices.length;console.assert(J==2*H);aa=0;Q=!0;x=J=0;for(const B of n){B.image.Ma!=aa&&(a.bindTexture(a.TEXTURE_2D,B.image.rb||null),aa=B.image.Ma);B.Pb?(a.scissor(B.Va,A-B.Wa-B.cb,B.$b,B.cb),Q=!0):Q&&(a.scissor(0,A-g,t,g),Q=!1);n=2/t;const fa=-2/g;a.uniform4f(e,B.xa[0]*n*B.Ga,B.xa[1]*fa*B.Ha,B.xa[2]*n*B.Ga,B.xa[3]*fa*B.Ha);a.uniform2f(f,B.xa[4]*n*B.Ga+n*(B.Va-B.Nb*B.Ga)-1,B.xa[5]*fa*B.Ha+fa*(B.Wa-B.Ob*B.Ha)+1);a.vertexAttribPointer(0,2,a.FLOAT,!1,0,x);a.vertexAttribPointer(1,
40
+ 2,a.FLOAT,!1,0,x+4*w);a.drawElements(a.TRIANGLES,B.indices.length,a.UNSIGNED_SHORT,J);x+=4*B.Ra.length;J+=2*B.indices.length}console.assert(x==4*w);console.assert(J==2*H)}};this.canvas=function(){return b()&&a.canvas}},la=h.onRuntimeInitialized;
41
+ h.onRuntimeInitialized=function(){function b(q){switch(q){case k.srcOver:return"source-over";case k.screen:return"screen";case k.overlay:return"overlay";case k.darken:return"darken";case k.lighten:return"lighten";case k.colorDodge:return"color-dodge";case k.colorBurn:return"color-burn";case k.hardLight:return"hard-light";case k.softLight:return"soft-light";case k.difference:return"difference";case k.exclusion:return"exclusion";case k.multiply:return"multiply";case k.hue:return"hue";case k.saturation:return"saturation";
42
+ case k.color:return"color";case k.luminosity:return"luminosity"}}function a(q){return"rgba("+((16711680&q)>>>16)+","+((65280&q)>>>8)+","+((255&q)>>>0)+","+((4278190080&q)>>>24)/255+")"}function c(){0<J.length&&(ka.Ab(A.drawWidth(),A.drawHeight(),J,Q,aa),J=[],aa=Q=0,A.reset(512,512));for(const q of x){for(const v of q.ja)v();q.ja=[]}x.clear()}la&&la();var d=h.RenderPaintStyle;const e=h.RenderPath,f=h.RenderPaint,m=h.Renderer,l=h.StrokeCap,p=h.StrokeJoin,k=h.BlendMode,r=d.fill,u=d.stroke,t=h.FillRule.evenOdd;
43
+ let g=1;var n=h.RenderImage.extend("CanvasRenderImage",{__construct:function({Aa:q,Fa:v}={}){this.__parent.__construct.call(this);this.Ma=g;g=g+1&2147483647||1;this.Aa=q;this.Fa=v},decode:function(q){var v=this;v.Fa&&v.Fa(v);var C=new Image;C.src=URL.createObjectURL(new Blob([q],{type:"image/png"}));C.onload=function(){v.ob=C;v.rb=ka.vb(C);v.size(C.width,C.height);v.Aa&&v.Aa(v)}}}),w=e.extend("CanvasRenderPath",{__construct:function(){this.__parent.__construct.call(this);this.pa=new Path2D},rewind:function(){this.pa=
44
+ new Path2D},addPath:function(q,v,C,D,z,E,F){var G=this.pa,T=G.addPath;q=q.pa;const K=new DOMMatrix;K.a=v;K.b=C;K.c=D;K.d=z;K.e=E;K.f=F;T.call(G,q,K)},fillRule:function(q){this.Ta=q},moveTo:function(q,v){this.pa.moveTo(q,v)},lineTo:function(q,v){this.pa.lineTo(q,v)},cubicTo:function(q,v,C,D,z,E){this.pa.bezierCurveTo(q,v,C,D,z,E)},close:function(){this.pa.closePath()}}),H=f.extend("CanvasRenderPaint",{color:function(q){this.Ua=a(q)},thickness:function(q){this.sb=q},join:function(q){switch(q){case p.miter:this.La=
45
+ "miter";break;case p.round:this.La="round";break;case p.bevel:this.La="bevel"}},cap:function(q){switch(q){case l.butt:this.Ka="butt";break;case l.round:this.Ka="round";break;case l.square:this.Ka="square"}},style:function(q){this.qb=q},blendMode:function(q){this.nb=b(q)},clearGradient:function(){this.za=null},linearGradient:function(q,v,C,D){this.za={kb:q,lb:v,Za:C,$a:D,Pa:[]}},radialGradient:function(q,v,C,D){this.za={kb:q,lb:v,Za:C,$a:D,Pa:[],Kb:!0}},addStop:function(q,v){this.za.Pa.push({color:q,
46
+ stop:v})},completeGradient:function(){},draw:function(q,v,C){let D=this.qb;var z=this.Ua,E=this.za;q.globalCompositeOperation=this.nb;if(null!=E){z=E.kb;var F=E.lb;const T=E.Za;var G=E.$a;const K=E.Pa;E.Kb?(E=T-z,G-=F,z=q.createRadialGradient(z,F,0,z,F,Math.sqrt(E*E+G*G))):z=q.createLinearGradient(z,F,T,G);for(let W=0,N=K.length;W<N;W++)F=K[W],z.addColorStop(F.stop,a(F.color));this.Ua=z;this.za=null}switch(D){case u:q.strokeStyle=z;q.lineWidth=this.sb;q.lineCap=this.Ka;q.lineJoin=this.La;q.stroke(v);
47
+ break;case r:q.fillStyle=z,q.fill(v,C)}}});const x=new Set;let A=null,J=[],Q=0,aa=0;var B=h.CanvasRenderer=m.extend("Renderer",{__construct:function(q){this.__parent.__construct.call(this);this.oa=[1,0,0,1,0,0];this.ha=q.getContext("2d");this.Sa=q;this.ja=[]},save:function(){this.oa.push(...this.oa.slice(this.oa.length-6));this.ja.push(this.ha.save.bind(this.ha))},restore:function(){const q=this.oa.length-6;if(6>q)throw"restore() called without matching save().";this.oa.splice(q);this.ja.push(this.ha.restore.bind(this.ha))},
48
+ transform:function(q,v,C,D,z,E){const F=this.oa,G=F.length-6;F.splice(G,6,F[G]*q+F[G+2]*v,F[G+1]*q+F[G+3]*v,F[G]*C+F[G+2]*D,F[G+1]*C+F[G+3]*D,F[G]*z+F[G+2]*E+F[G+4],F[G+1]*z+F[G+3]*E+F[G+5]);this.ja.push(this.ha.transform.bind(this.ha,q,v,C,D,z,E))},rotate:function(q){const v=Math.sin(q);q=Math.cos(q);this.transform(q,v,-v,q,0,0)},_drawPath:function(q,v){this.ja.push(v.draw.bind(v,this.ha,q.pa,q.Ta===t?"evenodd":"nonzero"))},_drawRiveImage:function(q,v,C){var D=q.ob;if(D){var z=this.ha,E=b(v);this.ja.push(function(){z.globalCompositeOperation=
49
+ E;z.globalAlpha=C;z.drawImage(D,0,0);z.globalAlpha=1})}},_getMatrix:function(q){const v=this.oa,C=v.length-6;for(let D=0;6>D;++D)q[D]=v[C+D]},_drawImageMesh:function(q,v,C,D,z,E,F,G,T,K){var W=this.ha.canvas.width,N=this.ha.canvas.height;const sb=T-F,tb=K-G;F=Math.max(F,0);G=Math.max(G,0);T=Math.min(T,W);K=Math.min(K,N);const ua=T-F,va=K-G;console.assert(ua<=Math.min(sb,W));console.assert(va<=Math.min(tb,N));if(!(0>=ua||0>=va)){T=ua<sb||va<tb;W=K=1;var ia=Math.ceil(ua*K),ja=Math.ceil(va*W);N=ka.Mb();
50
+ ia>N&&(K*=N/ia,ia=N);ja>N&&(W*=N/ja,ja=N);A||(A=new h.DynamicRectanizer(N),A.reset(512,512));N=A.addRect(ia,ja);0>N&&(c(),x.add(this),N=A.addRect(ia,ja),console.assert(0<=N));var ub=N&65535,vb=N>>16;J.push({xa:this.oa.slice(this.oa.length-6),image:q,Va:ub,Wa:vb,Nb:F,Ob:G,$b:ia,cb:ja,Ga:K,Ha:W,Ra:new Float32Array(D),mb:new Float32Array(z),indices:new Uint16Array(E),Pb:T,jb:q.Ma<<1|(T?1:0)});Q+=D.length;aa+=E.length;var oa=this.ha,kc=b(v);this.ja.push(function(){oa.save();oa.resetTransform();oa.globalCompositeOperation=
51
+ kc;oa.globalAlpha=C;oa.drawImage(ka.canvas(),ub,vb,ia,ja,F,G,ua,va);oa.restore()})}},_clipPath:function(q){this.ja.push(this.ha.clip.bind(this.ha,q.pa,q.Ta===t?"evenodd":"nonzero"))},clear:function(){x.add(this);this.ja.push(this.ha.clearRect.bind(this.ha,0,0,this.Sa.width,this.Sa.height))},flush:function(){},translate:function(q,v){this.transform(1,0,0,1,q,v)}});h.makeRenderer=function(q){const v=new B(q),C=v.ha;return new Proxy(v,{get(D,z){if("function"===typeof D[z])return function(...E){return D[z].apply(D,
52
+ E)};if("function"===typeof C[z]){if(-1<ha.indexOf(z))throw Error("RiveException: Method call to '"+z+"()' is not allowed, as the renderer cannot immediately pass through the return values of any canvas 2d context methods.");return function(...E){v.ja.push(C[z].bind(C,...E))}}return D[z]},set(D,z,E){if(z in C)return C[z]=E,!0}})};h.decodeImage=function(q,v){(new n({Aa:v})).decode(q)};h.renderFactory={makeRenderPaint:function(){return new H},makeRenderPath:function(){return new w},makeRenderImage:function(){let q=
53
+ Za;return new n({Fa:()=>{q.total++},Aa:()=>{q.loaded++;if(q.loaded===q.total){const v=q.ready;v&&(v(),q.ready=null)}}})}};let fa=h.load,Za=null;h.load=function(q,v,C=!0){const D=new h.FallbackFileAssetLoader;void 0!==v&&D.addLoader(v);C&&(v=new h.CDNFileAssetLoader,D.addLoader(v));return new Promise(function(z){let E=null;Za={total:0,loaded:0,ready:function(){z(E)}};E=fa(q,D);0==Za.total&&z(E)})};d=new da;h.requestAnimationFrame=d.requestAnimationFrame.bind(d);h.cancelAnimationFrame=d.cancelAnimationFrame.bind(d);
54
+ h.enableFPSCounter=d.Bb.bind(d);h.disableFPSCounter=d.yb;d.fb=c;h.cleanup=function(){A&&A.delete()}};const ma=h.onRuntimeInitialized;
55
+ h.onRuntimeInitialized=function(){ma&&ma();let b=h.decodeFont;h.decodeFont=function(c,d){c=b(c);d(c)};const a=h.FileAssetLoader;h.ptrToAsset=c=>{let d=h.ptrToFileAsset(c);return d.isImage?h.ptrToImageAsset(c):d.isFont?h.ptrToFontAsset(c):d};h.CustomFileAssetLoader=a.extend("CustomFileAssetLoader",{__construct:function({loadContents:c}){this.__parent.__construct.call(this);this.pb=c},loadContents:function(c,d){c=h.ptrToAsset(c);return this.pb(c,d)}});h.CDNFileAssetLoader=a.extend("CDNFileAssetLoader",
56
+ {__construct:function(){this.__parent.__construct.call(this)},loadContents:function(c){let d=h.ptrToAsset(c);c=d.cdnUuid;if(""===c)return!1;(function(e,f){var m=new XMLHttpRequest;m.responseType="arraybuffer";m.onreadystatechange=function(){4==m.readyState&&200==m.status&&f(m)};m.open("GET",e,!0);m.send(null)})(d.cdnBaseUrl+"/"+c,e=>{d.decode(new Uint8Array(e.response))});return!0}});h.FallbackFileAssetLoader=a.extend("FallbackFileAssetLoader",{__construct:function(){this.__parent.__construct.call(this);
57
+ this.eb=[]},addLoader:function(c){this.eb.push(c)},loadContents:function(c,d){for(let e of this.eb)if(e.loadContents(c,d))return!0;return!1}})};var na=Object.assign({},h),pa="./this.program",qa="object"==typeof window,ra="function"==typeof importScripts,y="",sa,ta;
58
+ if(qa||ra)ra?y=self.location.href:"undefined"!=typeof document&&document.currentScript&&(y=document.currentScript.src),_scriptDir&&(y=_scriptDir),0!==y.indexOf("blob:")?y=y.substr(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1):y="",ra&&(ta=b=>{var a=new XMLHttpRequest;a.open("GET",b,!1);a.responseType="arraybuffer";a.send(null);return new Uint8Array(a.response)}),sa=(b,a,c)=>{var d=new XMLHttpRequest;d.open("GET",b,!0);d.responseType="arraybuffer";d.onload=()=>{200==d.status||0==d.status&&d.response?
59
+ a(d.response):c()};d.onerror=c;d.send(null)};var wa=h.print||console.log.bind(console),xa=h.printErr||console.error.bind(console);Object.assign(h,na);na=null;h.thisProgram&&(pa=h.thisProgram);var ya;h.wasmBinary&&(ya=h.wasmBinary);var noExitRuntime=h.noExitRuntime||!0;"object"!=typeof WebAssembly&&za("no native wasm support detected");var Aa,I,Ba=!1,Ca,L,Da,Ea,M,O,Fa,Ga;
60
+ function Ha(){var b=Aa.buffer;h.HEAP8=Ca=new Int8Array(b);h.HEAP16=Da=new Int16Array(b);h.HEAP32=M=new Int32Array(b);h.HEAPU8=L=new Uint8Array(b);h.HEAPU16=Ea=new Uint16Array(b);h.HEAPU32=O=new Uint32Array(b);h.HEAPF32=Fa=new Float32Array(b);h.HEAPF64=Ga=new Float64Array(b)}var Ia,Ja=[],Ka=[],La=[];function Ma(){var b=h.preRun.shift();Ja.unshift(b)}var Na=0,Oa=null,Pa=null;
61
+ function za(b){if(h.onAbort)h.onAbort(b);b="Aborted("+b+")";xa(b);Ba=!0;b=new WebAssembly.RuntimeError(b+". Build with -sASSERTIONS for more info.");ca(b);throw b;}function Qa(b){return b.startsWith("data:application/octet-stream;base64,")}var Ra;Ra="canvas_advanced.wasm";if(!Qa(Ra)){var Sa=Ra;Ra=h.locateFile?h.locateFile(Sa,y):y+Sa}function Ta(b){if(b==Ra&&ya)return new Uint8Array(ya);if(ta)return ta(b);throw"both async and sync fetching of the wasm failed";}
62
+ function Ua(b){if(!ya&&(qa||ra)){if("function"==typeof fetch&&!b.startsWith("file://"))return fetch(b,{credentials:"same-origin"}).then(a=>{if(!a.ok)throw"failed to load wasm binary file at '"+b+"'";return a.arrayBuffer()}).catch(()=>Ta(b));if(sa)return new Promise((a,c)=>{sa(b,d=>a(new Uint8Array(d)),c)})}return Promise.resolve().then(()=>Ta(b))}function Va(b,a,c){return Ua(b).then(d=>WebAssembly.instantiate(d,a)).then(d=>d).then(c,d=>{xa("failed to asynchronously prepare wasm: "+d);za(d)})}
63
+ function Wa(b,a){var c=Ra;return ya||"function"!=typeof WebAssembly.instantiateStreaming||Qa(c)||c.startsWith("file://")||"function"!=typeof fetch?Va(c,b,a):fetch(c,{credentials:"same-origin"}).then(d=>WebAssembly.instantiateStreaming(d,b).then(a,function(e){xa("wasm streaming compile failed: "+e);xa("falling back to ArrayBuffer instantiation");return Va(c,b,a)}))}var Xa=b=>{for(;0<b.length;)b.shift()(h)};
64
+ function Ya(b){if(void 0===b)return"_unknown";b=b.replace(/[^a-zA-Z0-9_]/g,"$");var a=b.charCodeAt(0);return 48<=a&&57>=a?`_${b}`:b}function $a(b,a){b=Ya(b);return{[b]:function(){return a.apply(this,arguments)}}[b]}function ab(){this.qa=[void 0];this.bb=[]}var P=new ab,bb=void 0;function R(b){throw new bb(b);}
65
+ var S=b=>{b||R("Cannot use deleted val. handle = "+b);return P.get(b).value},U=b=>{switch(b){case void 0:return 1;case null:return 2;case !0:return 3;case !1:return 4;default:return P.tb({ib:1,value:b})}};
66
+ function cb(b){var a=Error,c=$a(b,function(d){this.name=b;this.message=d;d=Error(d).stack;void 0!==d&&(this.stack=this.toString()+"\n"+d.replace(/^Error(:[^\n]*)?\n/,""))});c.prototype=Object.create(a.prototype);c.prototype.constructor=c;c.prototype.toString=function(){return void 0===this.message?this.name:`${this.name}: ${this.message}`};return c}var db=void 0,eb=void 0;function V(b){for(var a="";L[b];)a+=eb[L[b++]];return a}var fb=[];
67
+ function gb(){for(;fb.length;){var b=fb.pop();b.ba.wa=!1;b["delete"]()}}var hb=void 0,ib={};function jb(b,a){for(void 0===a&&R("ptr should not be undefined");b.fa;)a=b.Ba(a),b=b.fa;return a}var kb={};function lb(b){b=mb(b);var a=V(b);nb(b);return a}function ob(b,a){var c=kb[b];void 0===c&&R(a+" has unknown type "+lb(b));return c}function pb(){}var qb=!1;function rb(b){--b.count.value;0===b.count.value&&(b.ia?b.la.ra(b.ia):b.ea.ca.ra(b.da))}
68
+ function wb(b,a,c){if(a===c)return b;if(void 0===c.fa)return null;b=wb(b,a,c.fa);return null===b?null:c.zb(b)}var xb={};function yb(b,a){a=jb(b,a);return ib[a]}var zb=void 0;function Ab(b){throw new zb(b);}function Bb(b,a){a.ea&&a.da||Ab("makeClassHandle requires ptr and ptrType");!!a.la!==!!a.ia&&Ab("Both smartPtrType and smartPtr must be specified");a.count={value:1};return Cb(Object.create(b,{ba:{value:a}}))}
69
+ function Cb(b){if("undefined"===typeof FinalizationRegistry)return Cb=a=>a,b;qb=new FinalizationRegistry(a=>{rb(a.ba)});Cb=a=>{var c=a.ba;c.ia&&qb.register(a,{ba:c},a);return a};pb=a=>{qb.unregister(a)};return Cb(b)}var Db={};function Eb(b){for(;b.length;){var a=b.pop();b.pop()(a)}}function Fb(b){return this.fromWireType(M[b>>2])}var Gb={},Hb={};
70
+ function X(b,a,c){function d(l){l=c(l);l.length!==b.length&&Ab("Mismatched type converter count");for(var p=0;p<b.length;++p)Y(b[p],l[p])}b.forEach(function(l){Hb[l]=a});var e=Array(a.length),f=[],m=0;a.forEach((l,p)=>{kb.hasOwnProperty(l)?e[p]=kb[l]:(f.push(l),Gb.hasOwnProperty(l)||(Gb[l]=[]),Gb[l].push(()=>{e[p]=kb[l];++m;m===f.length&&d(e)}))});0===f.length&&d(e)}
71
+ function Ib(b){switch(b){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${b}`);}}function Jb(b,a,c={}){var d=a.name;b||R(`type "${d}" must have a positive integer typeid pointer`);if(kb.hasOwnProperty(b)){if(c.Jb)return;R(`Cannot register type '${d}' twice`)}kb[b]=a;delete Hb[b];Gb.hasOwnProperty(b)&&(a=Gb[b],delete Gb[b],a.forEach(e=>e()))}
72
+ function Y(b,a,c={}){if(!("argPackAdvance"in a))throw new TypeError("registerType registeredInstance requires argPackAdvance");Jb(b,a,c)}function Kb(b){R(b.ba.ea.ca.name+" instance already deleted")}function Lb(){}
73
+ function Mb(b,a,c){if(void 0===b[a].ga){var d=b[a];b[a]=function(){b[a].ga.hasOwnProperty(arguments.length)||R(`Function '${c}' called with an invalid number of arguments (${arguments.length}) - expects one of (${b[a].ga})!`);return b[a].ga[arguments.length].apply(this,arguments)};b[a].ga=[];b[a].ga[d.va]=d}}
74
+ function Nb(b,a,c){h.hasOwnProperty(b)?((void 0===c||void 0!==h[b].ga&&void 0!==h[b].ga[c])&&R(`Cannot register public name '${b}' twice`),Mb(h,b,b),h.hasOwnProperty(c)&&R(`Cannot register multiple overloads of a function with the same number of arguments (${c})!`),h[b].ga[c]=a):(h[b]=a,void 0!==c&&(h[b].ac=c))}function Ob(b,a,c,d,e,f,m,l){this.name=b;this.constructor=a;this.ma=c;this.ra=d;this.fa=e;this.Eb=f;this.Ba=m;this.zb=l;this.gb=[]}
75
+ function Pb(b,a,c){for(;a!==c;)a.Ba||R(`Expected null or instance of ${c.name}, got an instance of ${a.name}`),b=a.Ba(b),a=a.fa;return b}function Qb(b,a){if(null===a)return this.Na&&R(`null is not a valid ${this.name}`),0;a.ba||R(`Cannot pass "${Rb(a)}" as a ${this.name}`);a.ba.da||R(`Cannot pass deleted object as a pointer of type ${this.name}`);return Pb(a.ba.da,a.ba.ea.ca,this.ca)}
76
+ function Sb(b,a){if(null===a){this.Na&&R(`null is not a valid ${this.name}`);if(this.Ea){var c=this.Oa();null!==b&&b.push(this.ra,c);return c}return 0}a.ba||R(`Cannot pass "${Rb(a)}" as a ${this.name}`);a.ba.da||R(`Cannot pass deleted object as a pointer of type ${this.name}`);!this.Da&&a.ba.ea.Da&&R(`Cannot convert argument of type ${a.ba.la?a.ba.la.name:a.ba.ea.name} to parameter type ${this.name}`);c=Pb(a.ba.da,a.ba.ea.ca,this.ca);if(this.Ea)switch(void 0===a.ba.ia&&R("Passing raw pointer to smart pointer is illegal"),
77
+ this.Vb){case 0:a.ba.la===this?c=a.ba.ia:R(`Cannot convert argument of type ${a.ba.la?a.ba.la.name:a.ba.ea.name} to parameter type ${this.name}`);break;case 1:c=a.ba.ia;break;case 2:if(a.ba.la===this)c=a.ba.ia;else{var d=a.clone();c=this.Rb(c,U(function(){d["delete"]()}));null!==b&&b.push(this.ra,c)}break;default:R("Unsupporting sharing policy")}return c}
78
+ function Tb(b,a){if(null===a)return this.Na&&R(`null is not a valid ${this.name}`),0;a.ba||R(`Cannot pass "${Rb(a)}" as a ${this.name}`);a.ba.da||R(`Cannot pass deleted object as a pointer of type ${this.name}`);a.ba.ea.Da&&R(`Cannot convert argument of type ${a.ba.ea.name} to parameter type ${this.name}`);return Pb(a.ba.da,a.ba.ea.ca,this.ca)}
79
+ function Ub(b,a,c,d){this.name=b;this.ca=a;this.Na=c;this.Da=d;this.Ea=!1;this.ra=this.Rb=this.Oa=this.hb=this.Vb=this.Qb=void 0;void 0!==a.fa?this.toWireType=Sb:(this.toWireType=d?Qb:Tb,this.ka=null)}function Vb(b,a,c){h.hasOwnProperty(b)||Ab("Replacing nonexistant public symbol");void 0!==h[b].ga&&void 0!==c?h[b].ga[c]=a:(h[b]=a,h[b].va=c)}
80
+ var Wb=(b,a)=>{var c=[];return function(){c.length=0;Object.assign(c,arguments);if(b.includes("j")){var d=h["dynCall_"+b];d=c&&c.length?d.apply(null,[a].concat(c)):d.call(null,a)}else d=Ia.get(a).apply(null,c);return d}};function Z(b,a){b=V(b);var c=b.includes("j")?Wb(b,a):Ia.get(a);"function"!=typeof c&&R(`unknown function pointer with signature ${b}: ${a}`);return c}var Xb=void 0;
81
+ function Yb(b,a){function c(f){e[f]||kb[f]||(Hb[f]?Hb[f].forEach(c):(d.push(f),e[f]=!0))}var d=[],e={};a.forEach(c);throw new Xb(`${b}: `+d.map(lb).join([", "]));}
82
+ function Zb(b,a,c,d,e){var f=a.length;2>f&&R("argTypes array size mismatch! Must at least get return value and 'this' types!");var m=null!==a[1]&&null!==c,l=!1;for(c=1;c<a.length;++c)if(null!==a[c]&&void 0===a[c].ka){l=!0;break}var p="void"!==a[0].name,k=f-2,r=Array(k),u=[],t=[];return function(){arguments.length!==k&&R(`function ${b} called with ${arguments.length} arguments, expected ${k} args!`);t.length=0;u.length=m?2:1;u[0]=e;if(m){var g=a[1].toWireType(t,this);u[1]=g}for(var n=0;n<k;++n)r[n]=
83
+ a[n+2].toWireType(t,arguments[n]),u.push(r[n]);n=d.apply(null,u);if(l)Eb(t);else for(var w=m?1:2;w<a.length;w++){var H=1===w?g:r[w-2];null!==a[w].ka&&a[w].ka(H)}g=p?a[0].fromWireType(n):void 0;return g}}function $b(b,a){for(var c=[],d=0;d<b;d++)c.push(O[a+4*d>>2]);return c}
84
+ function ac(b,a,c){b instanceof Object||R(`${c} with invalid "this": ${b}`);b instanceof a.ca.constructor||R(`${c} incompatible with "this" of type ${b.constructor.name}`);b.ba.da||R(`cannot call emscripten binding method ${c} on deleted object`);return Pb(b.ba.da,b.ba.ea.ca,a.ca)}function bc(b){b>=P.Xa&&0===--P.get(b).ib&&P.wb(b)}
85
+ function cc(b,a,c){switch(a){case 0:return function(d){return this.fromWireType((c?Ca:L)[d])};case 1:return function(d){return this.fromWireType((c?Da:Ea)[d>>1])};case 2:return function(d){return this.fromWireType((c?M:O)[d>>2])};default:throw new TypeError("Unknown integer type: "+b);}}function Rb(b){if(null===b)return"null";var a=typeof b;return"object"===a||"array"===a||"function"===a?b.toString():""+b}
86
+ function dc(b,a){switch(a){case 2:return function(c){return this.fromWireType(Fa[c>>2])};case 3:return function(c){return this.fromWireType(Ga[c>>3])};default:throw new TypeError("Unknown float type: "+b);}}
87
+ function ec(b,a,c){switch(a){case 0:return c?function(d){return Ca[d]}:function(d){return L[d]};case 1:return c?function(d){return Da[d>>1]}:function(d){return Ea[d>>1]};case 2:return c?function(d){return M[d>>2]}:function(d){return O[d>>2]};default:throw new TypeError("Unknown integer type: "+b);}}
88
+ var fc=(b,a,c,d)=>{if(0<d){d=c+d-1;for(var e=0;e<b.length;++e){var f=b.charCodeAt(e);if(55296<=f&&57343>=f){var m=b.charCodeAt(++e);f=65536+((f&1023)<<10)|m&1023}if(127>=f){if(c>=d)break;a[c++]=f}else{if(2047>=f){if(c+1>=d)break;a[c++]=192|f>>6}else{if(65535>=f){if(c+2>=d)break;a[c++]=224|f>>12}else{if(c+3>=d)break;a[c++]=240|f>>18;a[c++]=128|f>>12&63}a[c++]=128|f>>6&63}a[c++]=128|f&63}}a[c]=0}},gc=b=>{for(var a=0,c=0;c<b.length;++c){var d=b.charCodeAt(c);127>=d?a++:2047>=d?a+=2:55296<=d&&57343>=
89
+ d?(a+=4,++c):a+=3}return a},hc="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,ic=(b,a,c)=>{var d=a+c;for(c=a;b[c]&&!(c>=d);)++c;if(16<c-a&&b.buffer&&hc)return hc.decode(b.subarray(a,c));for(d="";a<c;){var e=b[a++];if(e&128){var f=b[a++]&63;if(192==(e&224))d+=String.fromCharCode((e&31)<<6|f);else{var m=b[a++]&63;e=224==(e&240)?(e&15)<<12|f<<6|m:(e&7)<<18|f<<12|m<<6|b[a++]&63;65536>e?d+=String.fromCharCode(e):(e-=65536,d+=String.fromCharCode(55296|e>>10,56320|e&1023))}}else d+=String.fromCharCode(e)}return d},
90
+ jc="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,lc=(b,a)=>{var c=b>>1;for(var d=c+a/2;!(c>=d)&&Ea[c];)++c;c<<=1;if(32<c-b&&jc)return jc.decode(L.subarray(b,c));c="";for(d=0;!(d>=a/2);++d){var e=Da[b+2*d>>1];if(0==e)break;c+=String.fromCharCode(e)}return c},mc=(b,a,c)=>{void 0===c&&(c=2147483647);if(2>c)return 0;c-=2;var d=a;c=c<2*b.length?c/2:b.length;for(var e=0;e<c;++e)Da[a>>1]=b.charCodeAt(e),a+=2;Da[a>>1]=0;return a-d},nc=b=>2*b.length,oc=(b,a)=>{for(var c=0,d="";!(c>=a/
91
+ 4);){var e=M[b+4*c>>2];if(0==e)break;++c;65536<=e?(e-=65536,d+=String.fromCharCode(55296|e>>10,56320|e&1023)):d+=String.fromCharCode(e)}return d},pc=(b,a,c)=>{void 0===c&&(c=2147483647);if(4>c)return 0;var d=a;c=d+c-4;for(var e=0;e<b.length;++e){var f=b.charCodeAt(e);if(55296<=f&&57343>=f){var m=b.charCodeAt(++e);f=65536+((f&1023)<<10)|m&1023}M[a>>2]=f;a+=4;if(a+4>c)break}M[a>>2]=0;return a-d},qc=b=>{for(var a=0,c=0;c<b.length;++c){var d=b.charCodeAt(c);55296<=d&&57343>=d&&++c;a+=4}return a},rc={};
92
+ function sc(b){var a=rc[b];return void 0===a?V(b):a}var tc=[];function uc(b){var a=tc.length;tc.push(b);return a}function vc(b,a){for(var c=Array(b),d=0;d<b;++d)c[d]=ob(O[a+4*d>>2],"parameter "+d);return c}
93
+ var wc=[],xc={},zc=()=>{if(!yc){var b={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:pa||"./this.program"},a;for(a in xc)void 0===xc[a]?delete b[a]:b[a]=xc[a];var c=[];for(a in b)c.push(`${a}=${b[a]}`);yc=c}return yc},yc,Ac=[null,[],[]],Bc=b=>0===b%4&&(0!==b%100||0===b%400),Cc=[31,29,31,30,31,30,31,31,30,31,30,31],Dc=[31,28,31,30,31,30,31,31,30,31,30,31];
94
+ function Ec(b){var a=Array(gc(b)+1);fc(b,a,0,a.length);return a}
95
+ var Fc=(b,a,c,d)=>{function e(g,n,w){for(g="number"==typeof g?g.toString():g||"";g.length<n;)g=w[0]+g;return g}function f(g,n){return e(g,n,"0")}function m(g,n){function w(x){return 0>x?-1:0<x?1:0}var H;0===(H=w(g.getFullYear()-n.getFullYear()))&&0===(H=w(g.getMonth()-n.getMonth()))&&(H=w(g.getDate()-n.getDate()));return H}function l(g){switch(g.getDay()){case 0:return new Date(g.getFullYear()-1,11,29);case 1:return g;case 2:return new Date(g.getFullYear(),0,3);case 3:return new Date(g.getFullYear(),
96
+ 0,2);case 4:return new Date(g.getFullYear(),0,1);case 5:return new Date(g.getFullYear()-1,11,31);case 6:return new Date(g.getFullYear()-1,11,30)}}function p(g){var n=g.ta;for(g=new Date((new Date(g.ua+1900,0,1)).getTime());0<n;){var w=g.getMonth(),H=(Bc(g.getFullYear())?Cc:Dc)[w];if(n>H-g.getDate())n-=H-g.getDate()+1,g.setDate(1),11>w?g.setMonth(w+1):(g.setMonth(0),g.setFullYear(g.getFullYear()+1));else{g.setDate(g.getDate()+n);break}}w=new Date(g.getFullYear()+1,0,4);n=l(new Date(g.getFullYear(),
97
+ 0,4));w=l(w);return 0>=m(n,g)?0>=m(w,g)?g.getFullYear()+1:g.getFullYear():g.getFullYear()-1}var k=M[d+40>>2];d={Yb:M[d>>2],Xb:M[d+4>>2],Ia:M[d+8>>2],Qa:M[d+12>>2],Ja:M[d+16>>2],ua:M[d+20>>2],na:M[d+24>>2],ta:M[d+28>>2],bc:M[d+32>>2],Wb:M[d+36>>2],Zb:k?k?ic(L,k):"":""};c=c?ic(L,c):"";k={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y",
98
+ "%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var r in k)c=c.replace(new RegExp(r,"g"),k[r]);var u="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),t="January February March April May June July August September October November December".split(" ");k={"%a":g=>u[g.na].substring(0,3),"%A":g=>u[g.na],"%b":g=>t[g.Ja].substring(0,3),"%B":g=>t[g.Ja],"%C":g=>f((g.ua+1900)/
99
+ 100|0,2),"%d":g=>f(g.Qa,2),"%e":g=>e(g.Qa,2," "),"%g":g=>p(g).toString().substring(2),"%G":g=>p(g),"%H":g=>f(g.Ia,2),"%I":g=>{g=g.Ia;0==g?g=12:12<g&&(g-=12);return f(g,2)},"%j":g=>{for(var n=0,w=0;w<=g.Ja-1;n+=(Bc(g.ua+1900)?Cc:Dc)[w++]);return f(g.Qa+n,3)},"%m":g=>f(g.Ja+1,2),"%M":g=>f(g.Xb,2),"%n":()=>"\n","%p":g=>0<=g.Ia&&12>g.Ia?"AM":"PM","%S":g=>f(g.Yb,2),"%t":()=>"\t","%u":g=>g.na||7,"%U":g=>f(Math.floor((g.ta+7-g.na)/7),2),"%V":g=>{var n=Math.floor((g.ta+7-(g.na+6)%7)/7);2>=(g.na+371-g.ta-
100
+ 2)%7&&n++;if(n)53==n&&(w=(g.na+371-g.ta)%7,4==w||3==w&&Bc(g.ua)||(n=1));else{n=52;var w=(g.na+7-g.ta-1)%7;(4==w||5==w&&Bc(g.ua%400-1))&&n++}return f(n,2)},"%w":g=>g.na,"%W":g=>f(Math.floor((g.ta+7-(g.na+6)%7)/7),2),"%y":g=>(g.ua+1900).toString().substring(2),"%Y":g=>g.ua+1900,"%z":g=>{g=g.Wb;var n=0<=g;g=Math.abs(g)/60;return(n?"+":"-")+String("0000"+(g/60*100+g%60)).slice(-4)},"%Z":g=>g.Zb,"%%":()=>"%"};c=c.replace(/%%/g,"\x00\x00");for(r in k)c.includes(r)&&(c=c.replace(new RegExp(r,"g"),k[r](d)));
101
+ c=c.replace(/\0\0/g,"%");r=Ec(c);if(r.length>a)return 0;Ca.set(r,b);return r.length-1};Object.assign(ab.prototype,{get(b){return this.qa[b]},has(b){return void 0!==this.qa[b]},tb(b){var a=this.bb.pop()||this.qa.length;this.qa[a]=b;return a},wb(b){this.qa[b]=void 0;this.bb.push(b)}});bb=h.BindingError=class extends Error{constructor(b){super(b);this.name="BindingError"}};P.qa.push({value:void 0},{value:null},{value:!0},{value:!1});P.Xa=P.qa.length;
102
+ h.count_emval_handles=function(){for(var b=0,a=P.Xa;a<P.qa.length;++a)void 0!==P.qa[a]&&++b;return b};db=h.PureVirtualError=cb("PureVirtualError");for(var Gc=Array(256),Hc=0;256>Hc;++Hc)Gc[Hc]=String.fromCharCode(Hc);eb=Gc;h.getInheritedInstanceCount=function(){return Object.keys(ib).length};h.getLiveInheritedInstances=function(){var b=[],a;for(a in ib)ib.hasOwnProperty(a)&&b.push(ib[a]);return b};h.flushPendingDeletes=gb;h.setDelayFunction=function(b){hb=b;fb.length&&hb&&hb(gb)};
103
+ zb=h.InternalError=class extends Error{constructor(b){super(b);this.name="InternalError"}};Lb.prototype.isAliasOf=function(b){if(!(this instanceof Lb&&b instanceof Lb))return!1;var a=this.ba.ea.ca,c=this.ba.da,d=b.ba.ea.ca;for(b=b.ba.da;a.fa;)c=a.Ba(c),a=a.fa;for(;d.fa;)b=d.Ba(b),d=d.fa;return a===d&&c===b};
104
+ Lb.prototype.clone=function(){this.ba.da||Kb(this);if(this.ba.ya)return this.ba.count.value+=1,this;var b=Cb,a=Object,c=a.create,d=Object.getPrototypeOf(this),e=this.ba;b=b(c.call(a,d,{ba:{value:{count:e.count,wa:e.wa,ya:e.ya,da:e.da,ea:e.ea,ia:e.ia,la:e.la}}}));b.ba.count.value+=1;b.ba.wa=!1;return b};Lb.prototype["delete"]=function(){this.ba.da||Kb(this);this.ba.wa&&!this.ba.ya&&R("Object already scheduled for deletion");pb(this);rb(this.ba);this.ba.ya||(this.ba.ia=void 0,this.ba.da=void 0)};
105
+ Lb.prototype.isDeleted=function(){return!this.ba.da};Lb.prototype.deleteLater=function(){this.ba.da||Kb(this);this.ba.wa&&!this.ba.ya&&R("Object already scheduled for deletion");fb.push(this);1===fb.length&&hb&&hb(gb);this.ba.wa=!0;return this};Ub.prototype.Fb=function(b){this.hb&&(b=this.hb(b));return b};Ub.prototype.Ya=function(b){this.ra&&this.ra(b)};Ub.prototype.argPackAdvance=8;Ub.prototype.readValueFromPointer=Fb;Ub.prototype.deleteObject=function(b){if(null!==b)b["delete"]()};
106
+ Ub.prototype.fromWireType=function(b){function a(){return this.Ea?Bb(this.ca.ma,{ea:this.Qb,da:c,la:this,ia:b}):Bb(this.ca.ma,{ea:this,da:b})}var c=this.Fb(b);if(!c)return this.Ya(b),null;var d=yb(this.ca,c);if(void 0!==d){if(0===d.ba.count.value)return d.ba.da=c,d.ba.ia=b,d.clone();d=d.clone();this.Ya(b);return d}d=this.ca.Eb(c);d=xb[d];if(!d)return a.call(this);d=this.Da?d.ub:d.pointerType;var e=wb(c,this.ca,d.ca);return null===e?a.call(this):this.Ea?Bb(d.ca.ma,{ea:d,da:e,la:this,ia:b}):Bb(d.ca.ma,
107
+ {ea:d,da:e})};Xb=h.UnboundTypeError=cb("UnboundTypeError");
108
+ var Jc={N:function(b,a,c){b=V(b);a=ob(a,"wrapper");c=S(c);var d=[].slice,e=a.ca,f=e.ma,m=e.fa.ma,l=e.fa.constructor;b=$a(b,function(){e.fa.gb.forEach(function(k){if(this[k]===m[k])throw new db(`Pure virtual function ${k} must be implemented in JavaScript`);}.bind(this));Object.defineProperty(this,"__parent",{value:f});this.__construct.apply(this,d.call(arguments))});f.__construct=function(){this===f&&R("Pass correct 'this' to __construct");var k=l.implement.apply(void 0,[this].concat(d.call(arguments)));
109
+ pb(k);var r=k.ba;k.notifyOnDestruction();r.ya=!0;Object.defineProperties(this,{ba:{value:r}});Cb(this);k=r.da;k=jb(e,k);ib.hasOwnProperty(k)?R(`Tried to register registered instance: ${k}`):ib[k]=this};f.__destruct=function(){this===f&&R("Pass correct 'this' to __destruct");pb(this);var k=this.ba.da;k=jb(e,k);ib.hasOwnProperty(k)?delete ib[k]:R(`Tried to unregister unregistered instance: ${k}`)};b.prototype=Object.create(f);for(var p in c)b.prototype[p]=c[p];return U(b)},O:function(b){var a=Db[b];
110
+ delete Db[b];var c=a.Oa,d=a.ra,e=a.ab,f=e.map(m=>m.Ib).concat(e.map(m=>m.Tb));X([b],f,m=>{var l={};e.forEach((p,k)=>{var r=m[k],u=p.Gb,t=p.Hb,g=m[k+e.length],n=p.Sb,w=p.Ub;l[p.Cb]={read:H=>r.fromWireType(u(t,H)),write:(H,x)=>{var A=[];n(w,H,g.toWireType(A,x));Eb(A)}}});return[{name:a.name,fromWireType:function(p){var k={},r;for(r in l)k[r]=l[r].read(p);d(p);return k},toWireType:function(p,k){for(var r in l)if(!(r in k))throw new TypeError(`Missing field: "${r}"`);var u=c();for(r in l)l[r].write(u,
111
+ k[r]);null!==p&&p.push(d,u);return u},argPackAdvance:8,readValueFromPointer:Fb,ka:d}]})},C:function(){},K:function(b,a,c,d,e){var f=Ib(c);a=V(a);Y(b,{name:a,fromWireType:function(m){return!!m},toWireType:function(m,l){return l?d:e},argPackAdvance:8,readValueFromPointer:function(m){if(1===c)var l=Ca;else if(2===c)l=Da;else if(4===c)l=M;else throw new TypeError("Unknown boolean type size: "+a);return this.fromWireType(l[m>>f])},ka:null})},f:function(b,a,c,d,e,f,m,l,p,k,r,u,t){r=V(r);f=Z(e,f);l&&(l=
112
+ Z(m,l));k&&(k=Z(p,k));t=Z(u,t);var g=Ya(r);Nb(g,function(){Yb(`Cannot construct ${r} due to unbound types`,[d])});X([b,a,c],d?[d]:[],function(n){n=n[0];if(d){var w=n.ca;var H=w.ma}else H=Lb.prototype;n=$a(g,function(){if(Object.getPrototypeOf(this)!==x)throw new bb("Use 'new' to construct "+r);if(void 0===A.sa)throw new bb(r+" has no accessible constructor");var Q=A.sa[arguments.length];if(void 0===Q)throw new bb(`Tried to invoke ctor of ${r} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(A.sa).toString()}) parameters instead!`);
113
+ return Q.apply(this,arguments)});var x=Object.create(H,{constructor:{value:n}});n.prototype=x;var A=new Ob(r,n,x,t,w,f,l,k);A.fa&&(void 0===A.fa.Ca&&(A.fa.Ca=[]),A.fa.Ca.push(A));w=new Ub(r,A,!0,!1);H=new Ub(r+"*",A,!1,!1);var J=new Ub(r+" const*",A,!1,!0);xb[b]={pointerType:H,ub:J};Vb(g,n);return[w,H,J]})},j:function(b,a,c,d,e,f,m){var l=$b(c,d);a=V(a);f=Z(e,f);X([],[b],function(p){function k(){Yb(`Cannot call ${r} due to unbound types`,l)}p=p[0];var r=`${p.name}.${a}`;a.startsWith("@@")&&(a=Symbol[a.substring(2)]);
114
+ var u=p.ca.constructor;void 0===u[a]?(k.va=c-1,u[a]=k):(Mb(u,a,r),u[a].ga[c-1]=k);X([],l,function(t){t=Zb(r,[t[0],null].concat(t.slice(1)),null,f,m);void 0===u[a].ga?(t.va=c-1,u[a]=t):u[a].ga[c-1]=t;if(p.ca.Ca)for(const g of p.ca.Ca)g.constructor.hasOwnProperty(a)||(g.constructor[a]=t);return[]});return[]})},x:function(b,a,c,d,e,f,m,l){a=V(a);f=Z(e,f);X([],[b],function(p){p=p[0];var k=`${p.name}.${a}`,r={get(){Yb(`Cannot access ${k} due to unbound types`,[c])},enumerable:!0,configurable:!0};r.set=
115
+ l?()=>{Yb(`Cannot access ${k} due to unbound types`,[c])}:()=>{R(`${k} is a read-only property`)};Object.defineProperty(p.ca.constructor,a,r);X([],[c],function(u){u=u[0];var t={get(){return u.fromWireType(f(d))},enumerable:!0};l&&(l=Z(m,l),t.set=g=>{var n=[];l(d,u.toWireType(n,g));Eb(n)});Object.defineProperty(p.ca.constructor,a,t);return[]});return[]})},s:function(b,a,c,d,e,f){var m=$b(a,c);e=Z(d,e);X([],[b],function(l){l=l[0];var p=`constructor ${l.name}`;void 0===l.ca.sa&&(l.ca.sa=[]);if(void 0!==
116
+ l.ca.sa[a-1])throw new bb(`Cannot register multiple constructors with identical number of parameters (${a-1}) for class '${l.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);l.ca.sa[a-1]=()=>{Yb(`Cannot construct ${l.name} due to unbound types`,m)};X([],m,function(k){k.splice(1,0,null);l.ca.sa[a-1]=Zb(p,k,null,e,f);return[]});return[]})},a:function(b,a,c,d,e,f,m,l){var p=$b(c,d);a=V(a);f=Z(e,f);X([],[b],function(k){function r(){Yb(`Cannot call ${u} due to unbound types`,
117
+ p)}k=k[0];var u=`${k.name}.${a}`;a.startsWith("@@")&&(a=Symbol[a.substring(2)]);l&&k.ca.gb.push(a);var t=k.ca.ma,g=t[a];void 0===g||void 0===g.ga&&g.className!==k.name&&g.va===c-2?(r.va=c-2,r.className=k.name,t[a]=r):(Mb(t,a,u),t[a].ga[c-2]=r);X([],p,function(n){n=Zb(u,n,k,f,m);void 0===t[a].ga?(n.va=c-2,t[a]=n):t[a].ga[c-2]=n;return[]});return[]})},e:function(b,a,c,d,e,f,m,l,p,k){a=V(a);e=Z(d,e);X([],[b],function(r){r=r[0];var u=`${r.name}.${a}`,t={get(){Yb(`Cannot access ${u} due to unbound types`,
118
+ [c,m])},enumerable:!0,configurable:!0};t.set=p?()=>{Yb(`Cannot access ${u} due to unbound types`,[c,m])}:()=>{R(u+" is a read-only property")};Object.defineProperty(r.ca.ma,a,t);X([],p?[c,m]:[c],function(g){var n=g[0],w={get(){var x=ac(this,r,u+" getter");return n.fromWireType(e(f,x))},enumerable:!0};if(p){p=Z(l,p);var H=g[1];w.set=function(x){var A=ac(this,r,u+" setter"),J=[];p(k,A,H.toWireType(J,x));Eb(J)}}Object.defineProperty(r.ca.ma,a,w);return[]});return[]})},J:function(b,a){a=V(a);Y(b,{name:a,
119
+ fromWireType:function(c){var d=S(c);bc(c);return d},toWireType:function(c,d){return U(d)},argPackAdvance:8,readValueFromPointer:Fb,ka:null})},p:function(b,a,c,d){function e(){}c=Ib(c);a=V(a);e.values={};Y(b,{name:a,constructor:e,fromWireType:function(f){return this.constructor.values[f]},toWireType:function(f,m){return m.value},argPackAdvance:8,readValueFromPointer:cc(a,c,d),ka:null});Nb(a,e)},d:function(b,a,c){var d=ob(b,"enum");a=V(a);b=d.constructor;d=Object.create(d.constructor.prototype,{value:{value:c},
120
+ constructor:{value:$a(`${d.name}_${a}`,function(){})}});b.values[c]=d;b[a]=d},y:function(b,a,c){c=Ib(c);a=V(a);Y(b,{name:a,fromWireType:function(d){return d},toWireType:function(d,e){return e},argPackAdvance:8,readValueFromPointer:dc(a,c),ka:null})},m:function(b,a,c,d,e,f){var m=$b(a,c);b=V(b);e=Z(d,e);Nb(b,function(){Yb(`Cannot call ${b} due to unbound types`,m)},a-1);X([],m,function(l){Vb(b,Zb(b,[l[0],null].concat(l.slice(1)),null,e,f),a-1);return[]})},l:function(b,a,c,d,e){a=V(a);-1===e&&(e=4294967295);
121
+ e=Ib(c);var f=l=>l;if(0===d){var m=32-8*c;f=l=>l<<m>>>m}c=a.includes("unsigned")?function(l,p){return p>>>0}:function(l,p){return p};Y(b,{name:a,fromWireType:f,toWireType:c,argPackAdvance:8,readValueFromPointer:ec(a,e,0!==d),ka:null})},g:function(b,a,c){function d(f){f>>=2;var m=O;return new e(m.buffer,m[f+1],m[f])}var e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][a];c=V(c);Y(b,{name:c,fromWireType:d,argPackAdvance:8,readValueFromPointer:d},{Jb:!0})},
122
+ z:function(b,a){a=V(a);var c="std::string"===a;Y(b,{name:a,fromWireType:function(d){var e=O[d>>2],f=d+4;if(c)for(var m=f,l=0;l<=e;++l){var p=f+l;if(l==e||0==L[p]){m=m?ic(L,m,p-m):"";if(void 0===k)var k=m;else k+=String.fromCharCode(0),k+=m;m=p+1}}else{k=Array(e);for(l=0;l<e;++l)k[l]=String.fromCharCode(L[f+l]);k=k.join("")}nb(d);return k},toWireType:function(d,e){e instanceof ArrayBuffer&&(e=new Uint8Array(e));var f="string"==typeof e;f||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof
123
+ Int8Array||R("Cannot pass non-string to std::string");var m=c&&f?gc(e):e.length;var l=Ic(4+m+1),p=l+4;O[l>>2]=m;if(c&&f)fc(e,L,p,m+1);else if(f)for(f=0;f<m;++f){var k=e.charCodeAt(f);255<k&&(nb(p),R("String has UTF-16 code units that do not fit in 8 bits"));L[p+f]=k}else for(f=0;f<m;++f)L[p+f]=e[f];null!==d&&d.push(nb,l);return l},argPackAdvance:8,readValueFromPointer:Fb,ka:function(d){nb(d)}})},u:function(b,a,c){c=V(c);if(2===a){var d=lc;var e=mc;var f=nc;var m=()=>Ea;var l=1}else 4===a&&(d=oc,e=
124
+ pc,f=qc,m=()=>O,l=2);Y(b,{name:c,fromWireType:function(p){for(var k=O[p>>2],r=m(),u,t=p+4,g=0;g<=k;++g){var n=p+4+g*a;if(g==k||0==r[n>>l])t=d(t,n-t),void 0===u?u=t:(u+=String.fromCharCode(0),u+=t),t=n+a}nb(p);return u},toWireType:function(p,k){"string"!=typeof k&&R(`Cannot pass non-string to C++ string type ${c}`);var r=f(k),u=Ic(4+r+a);O[u>>2]=r>>l;e(k,u+4,r+a);null!==p&&p.push(nb,u);return u},argPackAdvance:8,readValueFromPointer:Fb,ka:function(p){nb(p)}})},Q:function(b,a,c,d,e,f){Db[b]={name:V(a),
125
+ Oa:Z(c,d),ra:Z(e,f),ab:[]}},P:function(b,a,c,d,e,f,m,l,p,k){Db[b].ab.push({Cb:V(a),Ib:c,Gb:Z(d,e),Hb:f,Tb:m,Sb:Z(l,p),Ub:k})},L:function(b,a){a=V(a);Y(b,{Lb:!0,name:a,argPackAdvance:0,fromWireType:function(){},toWireType:function(){}})},v:function(b,a,c){b=S(b);a=ob(a,"emval::as");var d=[],e=U(d);O[c>>2]=e;return a.toWireType(d,b)},w:function(b,a,c,d,e){b=tc[b];a=S(a);c=sc(c);var f=[];O[d>>2]=U(f);return b(a,c,f,e)},i:function(b,a,c,d){b=tc[b];a=S(a);c=sc(c);b(a,c,null,d)},c:bc,h:function(b,a){var c=
126
+ vc(b,a),d=c[0];a=d.name+"_$"+c.slice(1).map(function(m){return m.name}).join("_")+"$";var e=wc[a];if(void 0!==e)return e;var f=Array(b-1);e=uc((m,l,p,k)=>{for(var r=0,u=0;u<b-1;++u)f[u]=c[u+1].readValueFromPointer(k+r),r+=c[u+1].argPackAdvance;m=m[l].apply(m,f);for(u=0;u<b-1;++u)c[u+1].xb&&c[u+1].xb(f[u]);if(!d.Lb)return d.toWireType(p,m)});return wc[a]=e},t:function(b){b=sc(b);return U(h[b])},M:function(b,a){b=S(b);a=S(a);return U(b[a])},n:function(b){4<b&&(P.get(b).ib+=1)},o:function(b){return U(sc(b))},
127
+ A:function(){return U({})},q:function(b){var a=S(b);Eb(a);bc(b)},k:function(b,a,c){b=S(b);a=S(a);c=S(c);b[a]=c},r:function(b,a){b=ob(b,"_emval_take_value");b=b.readValueFromPointer(a);return U(b)},b:()=>{za("")},E:b=>{var a=L.length;b>>>=0;if(2147483648<b)return!1;for(var c=1;4>=c;c*=2){var d=a*(1+.2/c);d=Math.min(d,b+100663296);var e=Math;d=Math.max(b,d);a:{e=e.min.call(e,2147483648,d+(65536-d%65536)%65536)-Aa.buffer.byteLength+65535>>>16;try{Aa.grow(e);Ha();var f=1;break a}catch(m){}f=void 0}if(f)return!0}return!1},
128
+ F:(b,a)=>{var c=0;zc().forEach(function(d,e){var f=a+c;e=O[b+4*e>>2]=f;for(f=0;f<d.length;++f)Ca[e++>>0]=d.charCodeAt(f);Ca[e>>0]=0;c+=d.length+1});return 0},G:(b,a)=>{var c=zc();O[b>>2]=c.length;var d=0;c.forEach(function(e){d+=e.length+1});O[a>>2]=d;return 0},H:()=>52,B:function(){return 70},I:(b,a,c,d)=>{for(var e=0,f=0;f<c;f++){var m=O[a>>2],l=O[a+4>>2];a+=8;for(var p=0;p<l;p++){var k=L[m+p],r=Ac[b];0===k||10===k?((1===b?wa:xa)(ic(r,0)),r.length=0):r.push(k)}e+=l}O[d>>2]=e;return 0},D:(b,a,c,
129
+ d)=>Fc(b,a,c,d)};(function(){function b(c){I=c=c.exports;Aa=I.R;Ha();Ia=I.X;Ka.unshift(I.S);Na--;h.monitorRunDependencies&&h.monitorRunDependencies(Na);if(0==Na&&(null!==Oa&&(clearInterval(Oa),Oa=null),Pa)){var d=Pa;Pa=null;d()}return c}var a={a:Jc};Na++;h.monitorRunDependencies&&h.monitorRunDependencies(Na);if(h.instantiateWasm)try{return h.instantiateWasm(a,b)}catch(c){xa("Module.instantiateWasm callback failed with error: "+c),ca(c)}Wa(a,function(c){b(c.instance)}).catch(ca);return{}})();
130
+ var nb=b=>(nb=I.T)(b),Ic=b=>(Ic=I.U)(b),mb=b=>(mb=I.V)(b);h.__embind_initialize_bindings=()=>(h.__embind_initialize_bindings=I.W)();h.dynCall_jiji=(b,a,c,d,e)=>(h.dynCall_jiji=I.Y)(b,a,c,d,e);h.dynCall_viijii=(b,a,c,d,e,f,m)=>(h.dynCall_viijii=I.Z)(b,a,c,d,e,f,m);h.dynCall_iiiiij=(b,a,c,d,e,f,m)=>(h.dynCall_iiiiij=I._)(b,a,c,d,e,f,m);h.dynCall_iiiiijj=(b,a,c,d,e,f,m,l,p)=>(h.dynCall_iiiiijj=I.$)(b,a,c,d,e,f,m,l,p);
131
+ h.dynCall_iiiiiijj=(b,a,c,d,e,f,m,l,p,k)=>(h.dynCall_iiiiiijj=I.aa)(b,a,c,d,e,f,m,l,p,k);var Kc;Pa=function Lc(){Kc||Mc();Kc||(Pa=Lc)};
132
+ function Mc(){function b(){if(!Kc&&(Kc=!0,h.calledRun=!0,!Ba)){Xa(Ka);ba(h);if(h.onRuntimeInitialized)h.onRuntimeInitialized();if(h.postRun)for("function"==typeof h.postRun&&(h.postRun=[h.postRun]);h.postRun.length;){var a=h.postRun.shift();La.unshift(a)}Xa(La)}}if(!(0<Na)){if(h.preRun)for("function"==typeof h.preRun&&(h.preRun=[h.preRun]);h.preRun.length;)Ma();Xa(Ja);0<Na||(h.setStatus?(h.setStatus("Running..."),setTimeout(function(){setTimeout(function(){h.setStatus("")},1);b()},1)):b())}}
133
+ if(h.preInit)for("function"==typeof h.preInit&&(h.preInit=[h.preInit]);0<h.preInit.length;)h.preInit.pop()();Mc();
134
+
135
+
136
+ return moduleArg.ready
137
+ }
138
+
139
+ );
140
+ })();
141
+ /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Rive);
142
+
143
+ /***/ }),
144
+ /* 2 */
145
+ /***/ ((module) => {
146
+
147
+ module.exports = JSON.parse('{"name":"@rive-app/canvas-lite","version":"0.1.1","description":"A lite version of Rive\'s canvas based web api.","main":"rive.js","homepage":"https://rive.app","repository":{"type":"git","url":"https://github.com/rive-app/rive-wasm/tree/master/js"},"keywords":["rive","animation"],"author":"Rive","contributors":["Luigi Rosso <luigi@rive.app> (https://rive.app)","Maxwell Talbot <max@rive.app> (https://rive.app)","Arthur Vivian <arthur@rive.app> (https://rive.app)","Umberto Sonnino <umberto@rive.app> (https://rive.app)","Matthew Sullivan <matt.j.sullivan@gmail.com> (mailto:matt.j.sullivan@gmail.com)"],"license":"MIT","files":["rive.js","rive.js.map","rive.wasm","rive.d.ts","rive_advanced.mjs.d.ts"],"typings":"rive.d.ts","dependencies":{},"browser":{"fs":false,"path":false}}');
148
+
149
+ /***/ }),
150
+ /* 3 */
151
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
152
+
153
+ __webpack_require__.r(__webpack_exports__);
154
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
155
+ /* harmony export */ BLANK_URL: () => (/* reexport safe */ _sanitizeUrl__WEBPACK_IMPORTED_MODULE_1__.BLANK_URL),
156
+ /* harmony export */ registerTouchInteractions: () => (/* reexport safe */ _registerTouchInteractions__WEBPACK_IMPORTED_MODULE_0__.registerTouchInteractions),
157
+ /* harmony export */ sanitizeUrl: () => (/* reexport safe */ _sanitizeUrl__WEBPACK_IMPORTED_MODULE_1__.sanitizeUrl)
158
+ /* harmony export */ });
159
+ /* harmony import */ var _registerTouchInteractions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);
160
+ /* harmony import */ var _sanitizeUrl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
161
+
162
+
163
+
164
+
165
+ /***/ }),
166
+ /* 4 */
167
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
168
+
169
+ __webpack_require__.r(__webpack_exports__);
170
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
171
+ /* harmony export */ registerTouchInteractions: () => (/* binding */ registerTouchInteractions)
172
+ /* harmony export */ });
173
+ var _this = undefined;
174
+ /**
175
+ * Returns the clientX and clientY properties from touch or mouse events. Also
176
+ * calls preventDefault() on the event if it is a touchstart or touchmove to prevent
177
+ * scrolling the page on mobile devices
178
+ * @param event - Either a TouchEvent or a MouseEvent
179
+ * @returns - Coordinates of the clientX and clientY properties from the touch/mouse event
180
+ */
181
+ var getClientCoordinates = function (event) {
182
+ var _a, _b;
183
+ if (["touchstart", "touchmove"].indexOf(event.type) > -1 &&
184
+ ((_a = event.touches) === null || _a === void 0 ? void 0 : _a.length)) {
185
+ event.preventDefault();
186
+ return {
187
+ clientX: event.touches[0].clientX,
188
+ clientY: event.touches[0].clientY,
189
+ };
190
+ }
191
+ else if (event.type === "touchend" &&
192
+ ((_b = event.changedTouches) === null || _b === void 0 ? void 0 : _b.length)) {
193
+ return {
194
+ clientX: event.changedTouches[0].clientX,
195
+ clientY: event.changedTouches[0].clientY,
196
+ };
197
+ }
198
+ else {
199
+ return {
200
+ clientX: event.clientX,
201
+ clientY: event.clientY,
202
+ };
203
+ }
204
+ };
205
+ /**
206
+ * Registers mouse move/up/down callback handlers on the canvas to send meaningful coordinates to
207
+ * the state machine pointer move/up/down functions based on cursor interaction
208
+ */
209
+ var registerTouchInteractions = function (_a) {
210
+ var canvas = _a.canvas, artboard = _a.artboard, _b = _a.stateMachines, stateMachines = _b === void 0 ? [] : _b, renderer = _a.renderer, rive = _a.rive, fit = _a.fit, alignment = _a.alignment;
211
+ if (!canvas ||
212
+ !stateMachines.length ||
213
+ !renderer ||
214
+ !rive ||
215
+ !artboard ||
216
+ typeof window === "undefined") {
217
+ return null;
218
+ }
219
+ var processEventCallback = function (event) {
220
+ var boundingRect = event.currentTarget.getBoundingClientRect();
221
+ var _a = getClientCoordinates(event), clientX = _a.clientX, clientY = _a.clientY;
222
+ if (!clientX && !clientY) {
223
+ return;
224
+ }
225
+ var canvasX = clientX - boundingRect.left;
226
+ var canvasY = clientY - boundingRect.top;
227
+ var forwardMatrix = rive.computeAlignment(fit, alignment, {
228
+ minX: 0,
229
+ minY: 0,
230
+ maxX: boundingRect.width,
231
+ maxY: boundingRect.height,
232
+ }, artboard.bounds);
233
+ var invertedMatrix = new rive.Mat2D();
234
+ forwardMatrix.invert(invertedMatrix);
235
+ var canvasCoordinatesVector = new rive.Vec2D(canvasX, canvasY);
236
+ var transformedVector = rive.mapXY(invertedMatrix, canvasCoordinatesVector);
237
+ var transformedX = transformedVector.x();
238
+ var transformedY = transformedVector.y();
239
+ transformedVector.delete();
240
+ invertedMatrix.delete();
241
+ canvasCoordinatesVector.delete();
242
+ forwardMatrix.delete();
243
+ switch (event.type) {
244
+ // Pointer moving/hovering on the canvas
245
+ case "touchmove":
246
+ case "mouseover":
247
+ case "mouseout":
248
+ case "mousemove": {
249
+ for (var _i = 0, stateMachines_1 = stateMachines; _i < stateMachines_1.length; _i++) {
250
+ var stateMachine = stateMachines_1[_i];
251
+ stateMachine.pointerMove(transformedX, transformedY);
252
+ }
253
+ break;
254
+ }
255
+ // Pointer click initiated but not released yet on the canvas
256
+ case "touchstart":
257
+ case "mousedown": {
258
+ for (var _b = 0, stateMachines_2 = stateMachines; _b < stateMachines_2.length; _b++) {
259
+ var stateMachine = stateMachines_2[_b];
260
+ stateMachine.pointerDown(transformedX, transformedY);
261
+ }
262
+ break;
263
+ }
264
+ // Pointer click released on the canvas
265
+ case "touchend":
266
+ case "mouseup": {
267
+ for (var _c = 0, stateMachines_3 = stateMachines; _c < stateMachines_3.length; _c++) {
268
+ var stateMachine = stateMachines_3[_c];
269
+ stateMachine.pointerUp(transformedX, transformedY);
270
+ }
271
+ break;
272
+ }
273
+ default:
274
+ }
275
+ };
276
+ var callback = processEventCallback.bind(_this);
277
+ canvas.addEventListener("mouseover", callback);
278
+ canvas.addEventListener("mouseout", callback);
279
+ canvas.addEventListener("mousemove", callback);
280
+ canvas.addEventListener("mousedown", callback);
281
+ canvas.addEventListener("mouseup", callback);
282
+ canvas.addEventListener("touchmove", callback);
283
+ canvas.addEventListener("touchstart", callback);
284
+ canvas.addEventListener("touchend", callback);
285
+ return function () {
286
+ canvas.removeEventListener("mouseover", callback);
287
+ canvas.removeEventListener("mouseout", callback);
288
+ canvas.removeEventListener("mousemove", callback);
289
+ canvas.removeEventListener("mousedown", callback);
290
+ canvas.removeEventListener("mouseup", callback);
291
+ canvas.removeEventListener("touchmove", callback);
292
+ canvas.removeEventListener("touchstart", callback);
293
+ canvas.removeEventListener("touchend", callback);
294
+ };
295
+ };
296
+
297
+
298
+ /***/ }),
299
+ /* 5 */
300
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
301
+
302
+ __webpack_require__.r(__webpack_exports__);
303
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
304
+ /* harmony export */ BLANK_URL: () => (/* binding */ BLANK_URL),
305
+ /* harmony export */ sanitizeUrl: () => (/* binding */ sanitizeUrl)
306
+ /* harmony export */ });
307
+ // Reference: https://github.com/braintree/sanitize-url/tree/main
308
+ var invalidProtocolRegex = /^([^\w]*)(javascript|data|vbscript)/im;
309
+ var htmlEntitiesRegex = /&#(\w+)(^\w|;)?/g;
310
+ var htmlCtrlEntityRegex = /&(newline|tab);/gi;
311
+ var ctrlCharactersRegex = /[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim;
312
+ var urlSchemeRegex = /^.+(:|&colon;)/gim;
313
+ var relativeFirstCharacters = [".", "/"];
314
+ var BLANK_URL = "about:blank";
315
+ function isRelativeUrlWithoutProtocol(url) {
316
+ return relativeFirstCharacters.indexOf(url[0]) > -1;
317
+ }
318
+ // adapted from https://stackoverflow.com/a/29824550/2601552
319
+ function decodeHtmlCharacters(str) {
320
+ var removedNullByte = str.replace(ctrlCharactersRegex, "");
321
+ return removedNullByte.replace(htmlEntitiesRegex, function (match, dec) {
322
+ return String.fromCharCode(dec);
323
+ });
324
+ }
325
+ function sanitizeUrl(url) {
326
+ if (!url) {
327
+ return BLANK_URL;
328
+ }
329
+ var sanitizedUrl = decodeHtmlCharacters(url)
330
+ .replace(htmlCtrlEntityRegex, "")
331
+ .replace(ctrlCharactersRegex, "")
332
+ .trim();
333
+ if (!sanitizedUrl) {
334
+ return BLANK_URL;
335
+ }
336
+ if (isRelativeUrlWithoutProtocol(sanitizedUrl)) {
337
+ return sanitizedUrl;
338
+ }
339
+ var urlSchemeParseResults = sanitizedUrl.match(urlSchemeRegex);
340
+ if (!urlSchemeParseResults) {
341
+ return sanitizedUrl;
342
+ }
343
+ var urlScheme = urlSchemeParseResults[0];
344
+ if (invalidProtocolRegex.test(urlScheme)) {
345
+ return BLANK_URL;
346
+ }
347
+ return sanitizedUrl;
348
+ }
349
+
350
+
351
+ /***/ })
352
+ /******/ ]);
353
+ /************************************************************************/
354
+ /******/ // The module cache
355
+ /******/ var __webpack_module_cache__ = {};
356
+ /******/
357
+ /******/ // The require function
358
+ /******/ function __webpack_require__(moduleId) {
359
+ /******/ // Check if module is in cache
360
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
361
+ /******/ if (cachedModule !== undefined) {
362
+ /******/ return cachedModule.exports;
363
+ /******/ }
364
+ /******/ // Create a new module (and put it into the cache)
365
+ /******/ var module = __webpack_module_cache__[moduleId] = {
366
+ /******/ // no module.id needed
367
+ /******/ // no module.loaded needed
368
+ /******/ exports: {}
369
+ /******/ };
370
+ /******/
371
+ /******/ // Execute the module function
372
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
373
+ /******/
374
+ /******/ // Return the exports of the module
375
+ /******/ return module.exports;
376
+ /******/ }
377
+ /******/
378
+ /************************************************************************/
379
+ /******/ /* webpack/runtime/define property getters */
380
+ /******/ (() => {
381
+ /******/ // define getter functions for harmony exports
382
+ /******/ __webpack_require__.d = (exports, definition) => {
383
+ /******/ for(var key in definition) {
384
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
385
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
386
+ /******/ }
387
+ /******/ }
388
+ /******/ };
389
+ /******/ })();
390
+ /******/
391
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
392
+ /******/ (() => {
393
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
394
+ /******/ })();
395
+ /******/
396
+ /******/ /* webpack/runtime/make namespace object */
397
+ /******/ (() => {
398
+ /******/ // define __esModule on exports
399
+ /******/ __webpack_require__.r = (exports) => {
400
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
401
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
402
+ /******/ }
403
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
404
+ /******/ };
405
+ /******/ })();
406
+ /******/
407
+ /************************************************************************/
408
+ var __webpack_exports__ = {};
409
+ // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
410
+ (() => {
411
+ __webpack_require__.r(__webpack_exports__);
412
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
413
+ /* harmony export */ Alignment: () => (/* binding */ Alignment),
414
+ /* harmony export */ EventType: () => (/* binding */ EventType),
415
+ /* harmony export */ Fit: () => (/* binding */ Fit),
416
+ /* harmony export */ Layout: () => (/* binding */ Layout),
417
+ /* harmony export */ LoopType: () => (/* binding */ LoopType),
418
+ /* harmony export */ Rive: () => (/* binding */ Rive),
419
+ /* harmony export */ RiveEventType: () => (/* binding */ RiveEventType),
420
+ /* harmony export */ RuntimeLoader: () => (/* binding */ RuntimeLoader),
421
+ /* harmony export */ StateMachineInput: () => (/* binding */ StateMachineInput),
422
+ /* harmony export */ StateMachineInputType: () => (/* binding */ StateMachineInputType),
423
+ /* harmony export */ Testing: () => (/* binding */ Testing),
424
+ /* harmony export */ decodeFont: () => (/* binding */ decodeFont),
425
+ /* harmony export */ decodeImage: () => (/* binding */ decodeImage)
426
+ /* harmony export */ });
427
+ /* harmony import */ var _rive_advanced_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
428
+ /* harmony import */ var package_json__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
429
+ /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3);
430
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
431
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
432
+ return new (P || (P = Promise))(function (resolve, reject) {
433
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
434
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
435
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
436
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
437
+ });
438
+ };
439
+ var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
440
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
441
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
442
+ function verb(n) { return function (v) { return step([n, v]); }; }
443
+ function step(op) {
444
+ if (f) throw new TypeError("Generator is already executing.");
445
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
446
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
447
+ if (y = 0, t) op = [op[0] & 2, t.value];
448
+ switch (op[0]) {
449
+ case 0: case 1: t = op; break;
450
+ case 4: _.label++; return { value: op[1], done: false };
451
+ case 5: _.label++; y = op[1]; op = [0]; continue;
452
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
453
+ default:
454
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
455
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
456
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
457
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
458
+ if (t[2]) _.ops.pop();
459
+ _.trys.pop(); continue;
460
+ }
461
+ op = body.call(thisArg, _);
462
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
463
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
464
+ }
465
+ };
466
+
467
+
468
+
469
+ // #region layout
470
+ // Fit options for the canvas
471
+ var Fit;
472
+ (function (Fit) {
473
+ Fit["Cover"] = "cover";
474
+ Fit["Contain"] = "contain";
475
+ Fit["Fill"] = "fill";
476
+ Fit["FitWidth"] = "fitWidth";
477
+ Fit["FitHeight"] = "fitHeight";
478
+ Fit["None"] = "none";
479
+ Fit["ScaleDown"] = "scaleDown";
480
+ })(Fit || (Fit = {}));
481
+ // Alignment options for the canvas
482
+ var Alignment;
483
+ (function (Alignment) {
484
+ Alignment["Center"] = "center";
485
+ Alignment["TopLeft"] = "topLeft";
486
+ Alignment["TopCenter"] = "topCenter";
487
+ Alignment["TopRight"] = "topRight";
488
+ Alignment["CenterLeft"] = "centerLeft";
489
+ Alignment["CenterRight"] = "centerRight";
490
+ Alignment["BottomLeft"] = "bottomLeft";
491
+ Alignment["BottomCenter"] = "bottomCenter";
492
+ Alignment["BottomRight"] = "bottomRight";
493
+ })(Alignment || (Alignment = {}));
494
+ // Alignment options for Rive animations in a HTML canvas
495
+ var Layout = /** @class */ (function () {
496
+ function Layout(params) {
497
+ var _a, _b, _c, _d, _e, _f;
498
+ this.fit = (_a = params === null || params === void 0 ? void 0 : params.fit) !== null && _a !== void 0 ? _a : Fit.Contain;
499
+ this.alignment = (_b = params === null || params === void 0 ? void 0 : params.alignment) !== null && _b !== void 0 ? _b : Alignment.Center;
500
+ this.minX = (_c = params === null || params === void 0 ? void 0 : params.minX) !== null && _c !== void 0 ? _c : 0;
501
+ this.minY = (_d = params === null || params === void 0 ? void 0 : params.minY) !== null && _d !== void 0 ? _d : 0;
502
+ this.maxX = (_e = params === null || params === void 0 ? void 0 : params.maxX) !== null && _e !== void 0 ? _e : 0;
503
+ this.maxY = (_f = params === null || params === void 0 ? void 0 : params.maxY) !== null && _f !== void 0 ? _f : 0;
504
+ }
505
+ // Alternative constructor to build a Layout from an interface/object
506
+ Layout.new = function (_a) {
507
+ var fit = _a.fit, alignment = _a.alignment, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY;
508
+ console.warn("This function is deprecated: please use `new Layout({})` instead");
509
+ return new Layout({ fit: fit, alignment: alignment, minX: minX, minY: minY, maxX: maxX, maxY: maxY });
510
+ };
511
+ /**
512
+ * Makes a copy of the layout, replacing any specified parameters
513
+ */
514
+ Layout.prototype.copyWith = function (_a) {
515
+ var fit = _a.fit, alignment = _a.alignment, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY;
516
+ return new Layout({
517
+ fit: fit !== null && fit !== void 0 ? fit : this.fit,
518
+ alignment: alignment !== null && alignment !== void 0 ? alignment : this.alignment,
519
+ minX: minX !== null && minX !== void 0 ? minX : this.minX,
520
+ minY: minY !== null && minY !== void 0 ? minY : this.minY,
521
+ maxX: maxX !== null && maxX !== void 0 ? maxX : this.maxX,
522
+ maxY: maxY !== null && maxY !== void 0 ? maxY : this.maxY,
523
+ });
524
+ };
525
+ // Returns fit for the Wasm runtime format
526
+ Layout.prototype.runtimeFit = function (rive) {
527
+ if (this.cachedRuntimeFit)
528
+ return this.cachedRuntimeFit;
529
+ var fit;
530
+ if (this.fit === Fit.Cover)
531
+ fit = rive.Fit.cover;
532
+ else if (this.fit === Fit.Contain)
533
+ fit = rive.Fit.contain;
534
+ else if (this.fit === Fit.Fill)
535
+ fit = rive.Fit.fill;
536
+ else if (this.fit === Fit.FitWidth)
537
+ fit = rive.Fit.fitWidth;
538
+ else if (this.fit === Fit.FitHeight)
539
+ fit = rive.Fit.fitHeight;
540
+ else if (this.fit === Fit.ScaleDown)
541
+ fit = rive.Fit.scaleDown;
542
+ else
543
+ fit = rive.Fit.none;
544
+ this.cachedRuntimeFit = fit;
545
+ return fit;
546
+ };
547
+ // Returns alignment for the Wasm runtime format
548
+ Layout.prototype.runtimeAlignment = function (rive) {
549
+ if (this.cachedRuntimeAlignment)
550
+ return this.cachedRuntimeAlignment;
551
+ var alignment;
552
+ if (this.alignment === Alignment.TopLeft)
553
+ alignment = rive.Alignment.topLeft;
554
+ else if (this.alignment === Alignment.TopCenter)
555
+ alignment = rive.Alignment.topCenter;
556
+ else if (this.alignment === Alignment.TopRight)
557
+ alignment = rive.Alignment.topRight;
558
+ else if (this.alignment === Alignment.CenterLeft)
559
+ alignment = rive.Alignment.centerLeft;
560
+ else if (this.alignment === Alignment.CenterRight)
561
+ alignment = rive.Alignment.centerRight;
562
+ else if (this.alignment === Alignment.BottomLeft)
563
+ alignment = rive.Alignment.bottomLeft;
564
+ else if (this.alignment === Alignment.BottomCenter)
565
+ alignment = rive.Alignment.bottomCenter;
566
+ else if (this.alignment === Alignment.BottomRight)
567
+ alignment = rive.Alignment.bottomRight;
568
+ else
569
+ alignment = rive.Alignment.center;
570
+ this.cachedRuntimeAlignment = alignment;
571
+ return alignment;
572
+ };
573
+ return Layout;
574
+ }());
575
+
576
+ // Runtime singleton; use getInstance to provide a callback that returns the
577
+ // Rive runtime
578
+ var RuntimeLoader = /** @class */ (function () {
579
+ // Class is never instantiated
580
+ function RuntimeLoader() {
581
+ }
582
+ // Loads the runtime
583
+ RuntimeLoader.loadRuntime = function () {
584
+ _rive_advanced_mjs__WEBPACK_IMPORTED_MODULE_0__["default"]({
585
+ // Loads Wasm bundle
586
+ locateFile: function () { return RuntimeLoader.wasmURL; },
587
+ })
588
+ .then(function (rive) {
589
+ var _a;
590
+ RuntimeLoader.runtime = rive;
591
+ // Fire all the callbacks
592
+ while (RuntimeLoader.callBackQueue.length > 0) {
593
+ (_a = RuntimeLoader.callBackQueue.shift()) === null || _a === void 0 ? void 0 : _a(RuntimeLoader.runtime);
594
+ }
595
+ })
596
+ .catch(function () {
597
+ // In case unpkg fails or goes down, we should try to load from jsdelivr
598
+ var backupJsdelivrUrl = "https://cdn.jsdelivr.net/npm/".concat(package_json__WEBPACK_IMPORTED_MODULE_1__.name, "@").concat(package_json__WEBPACK_IMPORTED_MODULE_1__.version, "/rive.wasm");
599
+ if (RuntimeLoader.wasmURL.toLowerCase() !== backupJsdelivrUrl) {
600
+ console.warn("Failed to load WASM from ".concat(RuntimeLoader.wasmURL, ", trying jsdelivr as a backup"));
601
+ RuntimeLoader.setWasmUrl(backupJsdelivrUrl);
602
+ RuntimeLoader.loadRuntime();
603
+ }
604
+ else {
605
+ console.error("Could not load Rive WASM file from unpkg or jsdelivr, network connection may be down, or \
606
+ you may need to call set a new WASM source via RuntimeLoader.setWasmUrl() and call \
607
+ RuntimeLoader.loadRuntime() again");
608
+ }
609
+ });
610
+ };
611
+ // Provides a runtime instance via a callback
612
+ RuntimeLoader.getInstance = function (callback) {
613
+ // If it's not loading, start loading runtime
614
+ if (!RuntimeLoader.isLoading) {
615
+ RuntimeLoader.isLoading = true;
616
+ RuntimeLoader.loadRuntime();
617
+ }
618
+ if (!RuntimeLoader.runtime) {
619
+ RuntimeLoader.callBackQueue.push(callback);
620
+ }
621
+ else {
622
+ callback(RuntimeLoader.runtime);
623
+ }
624
+ };
625
+ // Provides a runtime instance via a promise
626
+ RuntimeLoader.awaitInstance = function () {
627
+ return new Promise(function (resolve) {
628
+ return RuntimeLoader.getInstance(function (rive) { return resolve(rive); });
629
+ });
630
+ };
631
+ // Manually sets the wasm url
632
+ RuntimeLoader.setWasmUrl = function (url) {
633
+ RuntimeLoader.wasmURL = url;
634
+ };
635
+ // Flag to indicate that loading has started/completed
636
+ RuntimeLoader.isLoading = false;
637
+ // List of callbacks for the runtime that come in while loading
638
+ RuntimeLoader.callBackQueue = [];
639
+ // Path to the Wasm file; default path works for testing only;
640
+ // if embedded wasm is used then this is never used.
641
+ RuntimeLoader.wasmURL = "https://unpkg.com/".concat(package_json__WEBPACK_IMPORTED_MODULE_1__.name, "@").concat(package_json__WEBPACK_IMPORTED_MODULE_1__.version, "/rive.wasm");
642
+ return RuntimeLoader;
643
+ }());
644
+
645
+ // #endregion
646
+ // #region animations
647
+ // Wraps animations and instances from the runtime and keeps track of playback
648
+ // state
649
+ var Animation = /** @class */ (function () {
650
+ /**
651
+ * Constructs a new animation
652
+ * @constructor
653
+ * @param {any} animation: runtime animation object
654
+ * @param {any} instance: runtime animation instance object
655
+ */
656
+ function Animation(animation, artboard, runtime, playing) {
657
+ this.animation = animation;
658
+ this.artboard = artboard;
659
+ this.playing = playing;
660
+ this.loopCount = 0;
661
+ // Time to which the animation should move to on the next render
662
+ this.scrubTo = null;
663
+ this.instance = new runtime.LinearAnimationInstance(animation, artboard);
664
+ }
665
+ Object.defineProperty(Animation.prototype, "name", {
666
+ // Returns the animation's name
667
+ get: function () {
668
+ return this.animation.name;
669
+ },
670
+ enumerable: false,
671
+ configurable: true
672
+ });
673
+ Object.defineProperty(Animation.prototype, "time", {
674
+ // Returns the animation's current time
675
+ get: function () {
676
+ return this.instance.time;
677
+ },
678
+ // Sets the animation's current time
679
+ set: function (value) {
680
+ this.instance.time = value;
681
+ },
682
+ enumerable: false,
683
+ configurable: true
684
+ });
685
+ Object.defineProperty(Animation.prototype, "loopValue", {
686
+ // Returns the animation's loop type
687
+ get: function () {
688
+ return this.animation.loopValue;
689
+ },
690
+ enumerable: false,
691
+ configurable: true
692
+ });
693
+ /**
694
+ * Advances the animation by the give time. If the animation needs scrubbing,
695
+ * time is ignored and the stored scrub value is used.
696
+ * @param time the time to advance the animation by if no scrubbing required
697
+ */
698
+ Animation.prototype.advance = function (time) {
699
+ if (this.scrubTo === null) {
700
+ this.instance.advance(time);
701
+ }
702
+ else {
703
+ this.instance.time = 0;
704
+ this.instance.advance(this.scrubTo);
705
+ this.scrubTo = null;
706
+ }
707
+ };
708
+ /**
709
+ * Apply interpolated keyframe values to the artboard. This should be called after calling
710
+ * .advance() on an animation instance so that new values are applied to properties.
711
+ *
712
+ * Note: This does not advance the artboard, which updates all objects on the artboard
713
+ * @param mix - Mix value for the animation from 0 to 1
714
+ */
715
+ Animation.prototype.apply = function (mix) {
716
+ this.instance.apply(mix);
717
+ };
718
+ Object.defineProperty(Animation.prototype, "needsScrub", {
719
+ get: function () {
720
+ return this.scrubTo !== null;
721
+ },
722
+ enumerable: false,
723
+ configurable: true
724
+ });
725
+ /**
726
+ * Deletes the backing Wasm animation instance; once this is called, this
727
+ * animation is no more.
728
+ */
729
+ Animation.prototype.cleanup = function () {
730
+ this.instance.delete();
731
+ };
732
+ return Animation;
733
+ }());
734
+ // #endregion
735
+ // #region state machines
736
+ var StateMachineInputType;
737
+ (function (StateMachineInputType) {
738
+ StateMachineInputType[StateMachineInputType["Number"] = 56] = "Number";
739
+ StateMachineInputType[StateMachineInputType["Trigger"] = 58] = "Trigger";
740
+ StateMachineInputType[StateMachineInputType["Boolean"] = 59] = "Boolean";
741
+ })(StateMachineInputType || (StateMachineInputType = {}));
742
+ /**
743
+ * An input for a state machine
744
+ */
745
+ var StateMachineInput = /** @class */ (function () {
746
+ function StateMachineInput(type, runtimeInput) {
747
+ this.type = type;
748
+ this.runtimeInput = runtimeInput;
749
+ }
750
+ Object.defineProperty(StateMachineInput.prototype, "name", {
751
+ /**
752
+ * Returns the name of the input
753
+ */
754
+ get: function () {
755
+ return this.runtimeInput.name;
756
+ },
757
+ enumerable: false,
758
+ configurable: true
759
+ });
760
+ Object.defineProperty(StateMachineInput.prototype, "value", {
761
+ /**
762
+ * Returns the current value of the input
763
+ */
764
+ get: function () {
765
+ return this.runtimeInput.value;
766
+ },
767
+ /**
768
+ * Sets the value of the input
769
+ */
770
+ set: function (value) {
771
+ this.runtimeInput.value = value;
772
+ },
773
+ enumerable: false,
774
+ configurable: true
775
+ });
776
+ /**
777
+ * Fires a trigger; does nothing on Number or Boolean input types
778
+ */
779
+ StateMachineInput.prototype.fire = function () {
780
+ if (this.type === StateMachineInputType.Trigger) {
781
+ this.runtimeInput.fire();
782
+ }
783
+ };
784
+ return StateMachineInput;
785
+ }());
786
+
787
+ var RiveEventType;
788
+ (function (RiveEventType) {
789
+ RiveEventType[RiveEventType["General"] = 128] = "General";
790
+ RiveEventType[RiveEventType["OpenUrl"] = 131] = "OpenUrl";
791
+ })(RiveEventType || (RiveEventType = {}));
792
+ var StateMachine = /** @class */ (function () {
793
+ /**
794
+ * @constructor
795
+ * @param stateMachine runtime state machine object
796
+ * @param instance runtime state machine instance object
797
+ */
798
+ function StateMachine(stateMachine, runtime, playing, artboard) {
799
+ this.stateMachine = stateMachine;
800
+ this.playing = playing;
801
+ this.artboard = artboard;
802
+ /**
803
+ * Caches the inputs from the runtime
804
+ */
805
+ this.inputs = [];
806
+ this.instance = new runtime.StateMachineInstance(stateMachine, artboard);
807
+ this.initInputs(runtime);
808
+ }
809
+ Object.defineProperty(StateMachine.prototype, "name", {
810
+ get: function () {
811
+ return this.stateMachine.name;
812
+ },
813
+ enumerable: false,
814
+ configurable: true
815
+ });
816
+ Object.defineProperty(StateMachine.prototype, "statesChanged", {
817
+ /**
818
+ * Returns a list of state names that have changed on this frame
819
+ */
820
+ get: function () {
821
+ var names = [];
822
+ for (var i = 0; i < this.instance.stateChangedCount(); i++) {
823
+ names.push(this.instance.stateChangedNameByIndex(i));
824
+ }
825
+ return names;
826
+ },
827
+ enumerable: false,
828
+ configurable: true
829
+ });
830
+ /**
831
+ * Advances the state machine instance by a given time.
832
+ * @param time - the time to advance the animation by in seconds
833
+ */
834
+ StateMachine.prototype.advance = function (time) {
835
+ this.instance.advance(time);
836
+ };
837
+ /**
838
+ * Returns the number of events reported from the last advance call
839
+ * @returns Number of events reported
840
+ */
841
+ StateMachine.prototype.reportedEventCount = function () {
842
+ return this.instance.reportedEventCount();
843
+ };
844
+ /**
845
+ * Returns a RiveEvent object emitted from the last advance call at the given index
846
+ * of a list of potentially multiple events. If an event at the index is not found,
847
+ * undefined is returned.
848
+ * @param i index of the event reported in a list of potentially multiple events
849
+ * @returns RiveEvent or extended RiveEvent object returned, or undefined
850
+ */
851
+ StateMachine.prototype.reportedEventAt = function (i) {
852
+ return this.instance.reportedEventAt(i);
853
+ };
854
+ /**
855
+ * Fetches references to the state machine's inputs and caches them
856
+ * @param runtime an instance of the runtime; needed for the SMIInput types
857
+ */
858
+ StateMachine.prototype.initInputs = function (runtime) {
859
+ // Fetch the inputs from the runtime if we don't have them
860
+ for (var i = 0; i < this.instance.inputCount(); i++) {
861
+ var input = this.instance.input(i);
862
+ this.inputs.push(this.mapRuntimeInput(input, runtime));
863
+ }
864
+ };
865
+ /**
866
+ * Maps a runtime input to it's appropriate type
867
+ * @param input
868
+ */
869
+ StateMachine.prototype.mapRuntimeInput = function (input, runtime) {
870
+ if (input.type === runtime.SMIInput.bool) {
871
+ return new StateMachineInput(StateMachineInputType.Boolean, input.asBool());
872
+ }
873
+ else if (input.type === runtime.SMIInput.number) {
874
+ return new StateMachineInput(StateMachineInputType.Number, input.asNumber());
875
+ }
876
+ else if (input.type === runtime.SMIInput.trigger) {
877
+ return new StateMachineInput(StateMachineInputType.Trigger, input.asTrigger());
878
+ }
879
+ };
880
+ /**
881
+ * Deletes the backing Wasm state machine instance; once this is called, this
882
+ * state machine is no more.
883
+ */
884
+ StateMachine.prototype.cleanup = function () {
885
+ this.instance.delete();
886
+ };
887
+ return StateMachine;
888
+ }());
889
+ // #endregion
890
+ // #region animator
891
+ /**
892
+ * Manages animation
893
+ */
894
+ var Animator = /** @class */ (function () {
895
+ /**
896
+ * Constructs a new animator
897
+ * @constructor
898
+ * @param runtime Rive runtime; needed to instance animations & state machines
899
+ * @param artboard the artboard that holds all animations and state machines
900
+ * @param animations optional list of animations
901
+ * @param stateMachines optional list of state machines
902
+ */
903
+ function Animator(runtime, artboard, eventManager, animations, stateMachines) {
904
+ if (animations === void 0) { animations = []; }
905
+ if (stateMachines === void 0) { stateMachines = []; }
906
+ this.runtime = runtime;
907
+ this.artboard = artboard;
908
+ this.eventManager = eventManager;
909
+ this.animations = animations;
910
+ this.stateMachines = stateMachines;
911
+ }
912
+ /**
913
+ * Adds animations and state machines by their names. If names are shared
914
+ * between animations & state machines, then the first one found will be
915
+ * created. Best not to use the same names for these in your Rive file.
916
+ * @param animatable the name(s) of animations and state machines to add
917
+ * @returns a list of names of the playing animations and state machines
918
+ */
919
+ Animator.prototype.add = function (animatables, playing, fireEvent) {
920
+ if (fireEvent === void 0) { fireEvent = true; }
921
+ animatables = mapToStringArray(animatables);
922
+ // If animatables is empty, play or pause everything
923
+ if (animatables.length === 0) {
924
+ this.animations.forEach(function (a) { return (a.playing = playing); });
925
+ this.stateMachines.forEach(function (m) { return (m.playing = playing); });
926
+ }
927
+ else {
928
+ // Play/pause already instanced items, or create new instances
929
+ var instancedAnimationNames = this.animations.map(function (a) { return a.name; });
930
+ var instancedMachineNames = this.stateMachines.map(function (m) { return m.name; });
931
+ for (var i = 0; i < animatables.length; i++) {
932
+ var aIndex = instancedAnimationNames.indexOf(animatables[i]);
933
+ var mIndex = instancedMachineNames.indexOf(animatables[i]);
934
+ if (aIndex >= 0 || mIndex >= 0) {
935
+ if (aIndex >= 0) {
936
+ // Animation is instanced, play/pause it
937
+ this.animations[aIndex].playing = playing;
938
+ }
939
+ else {
940
+ // State machine is instanced, play/pause it
941
+ this.stateMachines[mIndex].playing = playing;
942
+ }
943
+ }
944
+ else {
945
+ // Try to create a new animation instance
946
+ var anim = this.artboard.animationByName(animatables[i]);
947
+ if (anim) {
948
+ var newAnimation = new Animation(anim, this.artboard, this.runtime, playing);
949
+ // Display the first frame of the specified animation
950
+ newAnimation.advance(0);
951
+ newAnimation.apply(1.0);
952
+ this.animations.push(newAnimation);
953
+ }
954
+ else {
955
+ // Try to create a new state machine instance
956
+ var sm = this.artboard.stateMachineByName(animatables[i]);
957
+ if (sm) {
958
+ var newStateMachine = new StateMachine(sm, this.runtime, playing, this.artboard);
959
+ this.stateMachines.push(newStateMachine);
960
+ }
961
+ }
962
+ }
963
+ }
964
+ }
965
+ // Fire play/paused events for animations
966
+ if (fireEvent) {
967
+ if (playing) {
968
+ this.eventManager.fire({
969
+ type: EventType.Play,
970
+ data: this.playing,
971
+ });
972
+ }
973
+ else {
974
+ this.eventManager.fire({
975
+ type: EventType.Pause,
976
+ data: this.paused,
977
+ });
978
+ }
979
+ }
980
+ return playing ? this.playing : this.paused;
981
+ };
982
+ /**
983
+ * Adds linear animations by their names.
984
+ * @param animatables the name(s) of animations to add
985
+ * @param playing whether animations should play on instantiation
986
+ */
987
+ Animator.prototype.initLinearAnimations = function (animatables, playing) {
988
+ // Play/pause already instanced items, or create new instances
989
+ // This validation is kept to maintain compatibility with current behavior.
990
+ // But given that it this is called during artboard initialization
991
+ // it should probably be safe to remove.
992
+ var instancedAnimationNames = this.animations.map(function (a) { return a.name; });
993
+ for (var i = 0; i < animatables.length; i++) {
994
+ var aIndex = instancedAnimationNames.indexOf(animatables[i]);
995
+ if (aIndex >= 0) {
996
+ this.animations[aIndex].playing = playing;
997
+ }
998
+ else {
999
+ // Try to create a new animation instance
1000
+ var anim = this.artboard.animationByName(animatables[i]);
1001
+ if (anim) {
1002
+ var newAnimation = new Animation(anim, this.artboard, this.runtime, playing);
1003
+ // Display the first frame of the specified animation
1004
+ newAnimation.advance(0);
1005
+ newAnimation.apply(1.0);
1006
+ this.animations.push(newAnimation);
1007
+ }
1008
+ }
1009
+ }
1010
+ };
1011
+ /**
1012
+ * Adds state machines by their names.
1013
+ * @param animatables the name(s) of state machines to add
1014
+ * @param playing whether state machines should play on instantiation
1015
+ */
1016
+ Animator.prototype.initStateMachines = function (animatables, playing) {
1017
+ // Play/pause already instanced items, or create new instances
1018
+ // This validation is kept to maintain compatibility with current behavior.
1019
+ // But given that it this is called during artboard initialization
1020
+ // it should probably be safe to remove.
1021
+ var instancedStateMachineNames = this.stateMachines.map(function (a) { return a.name; });
1022
+ for (var i = 0; i < animatables.length; i++) {
1023
+ var aIndex = instancedStateMachineNames.indexOf(animatables[i]);
1024
+ if (aIndex >= 0) {
1025
+ this.stateMachines[aIndex].playing = playing;
1026
+ }
1027
+ else {
1028
+ // Try to create a new state machine instance
1029
+ var sm = this.artboard.stateMachineByName(animatables[i]);
1030
+ if (sm) {
1031
+ var newStateMachine = new StateMachine(sm, this.runtime, playing, this.artboard);
1032
+ this.stateMachines.push(newStateMachine);
1033
+ }
1034
+ else {
1035
+ // In order to maintain compatibility with current behavior, if a state machine is not found
1036
+ // we look for an animation with the same name
1037
+ this.initLinearAnimations([animatables[i]], playing);
1038
+ }
1039
+ }
1040
+ }
1041
+ };
1042
+ /**
1043
+ * Play the named animations/state machines
1044
+ * @param animatables the names of the animations/machines to play; plays all if empty
1045
+ * @returns a list of the playing items
1046
+ */
1047
+ Animator.prototype.play = function (animatables) {
1048
+ return this.add(animatables, true);
1049
+ };
1050
+ /**
1051
+ * Pauses named animations and state machines, or everything if nothing is
1052
+ * specified
1053
+ * @param animatables names of the animations and state machines to pause
1054
+ * @returns a list of names of the animations and state machines paused
1055
+ */
1056
+ Animator.prototype.pause = function (animatables) {
1057
+ return this.add(animatables, false);
1058
+ };
1059
+ /**
1060
+ * Set time of named animations
1061
+ * @param animations names of the animations to scrub
1062
+ * @param value time scrub value, a floating point number to which the playhead is jumped
1063
+ * @returns a list of names of the animations that were scrubbed
1064
+ */
1065
+ Animator.prototype.scrub = function (animatables, value) {
1066
+ var forScrubbing = this.animations.filter(function (a) {
1067
+ return animatables.includes(a.name);
1068
+ });
1069
+ forScrubbing.forEach(function (a) { return (a.scrubTo = value); });
1070
+ return forScrubbing.map(function (a) { return a.name; });
1071
+ };
1072
+ Object.defineProperty(Animator.prototype, "playing", {
1073
+ /**
1074
+ * Returns a list of names of all animations and state machines currently
1075
+ * playing
1076
+ */
1077
+ get: function () {
1078
+ return this.animations
1079
+ .filter(function (a) { return a.playing; })
1080
+ .map(function (a) { return a.name; })
1081
+ .concat(this.stateMachines.filter(function (m) { return m.playing; }).map(function (m) { return m.name; }));
1082
+ },
1083
+ enumerable: false,
1084
+ configurable: true
1085
+ });
1086
+ Object.defineProperty(Animator.prototype, "paused", {
1087
+ /**
1088
+ * Returns a list of names of all animations and state machines currently
1089
+ * paused
1090
+ */
1091
+ get: function () {
1092
+ return this.animations
1093
+ .filter(function (a) { return !a.playing; })
1094
+ .map(function (a) { return a.name; })
1095
+ .concat(this.stateMachines.filter(function (m) { return !m.playing; }).map(function (m) { return m.name; }));
1096
+ },
1097
+ enumerable: false,
1098
+ configurable: true
1099
+ });
1100
+ /**
1101
+ * Stops and removes all named animations and state machines
1102
+ * @param animatables animations and state machines to remove
1103
+ * @returns a list of names of removed items
1104
+ */
1105
+ Animator.prototype.stop = function (animatables) {
1106
+ var _this = this;
1107
+ animatables = mapToStringArray(animatables);
1108
+ // If nothing's specified, wipe them out, all of them
1109
+ var removedNames = [];
1110
+ // Stop everything
1111
+ if (animatables.length === 0) {
1112
+ removedNames = this.animations
1113
+ .map(function (a) { return a.name; })
1114
+ .concat(this.stateMachines.map(function (m) { return m.name; }));
1115
+ // Clean up before emptying the arrays
1116
+ this.animations.forEach(function (a) { return a.cleanup(); });
1117
+ this.stateMachines.forEach(function (m) { return m.cleanup(); });
1118
+ // Empty out the arrays
1119
+ this.animations.splice(0, this.animations.length);
1120
+ this.stateMachines.splice(0, this.stateMachines.length);
1121
+ }
1122
+ else {
1123
+ // Remove only the named animations/state machines
1124
+ var animationsToRemove = this.animations.filter(function (a) {
1125
+ return animatables.includes(a.name);
1126
+ });
1127
+ animationsToRemove.forEach(function (a) {
1128
+ a.cleanup();
1129
+ _this.animations.splice(_this.animations.indexOf(a), 1);
1130
+ });
1131
+ var machinesToRemove = this.stateMachines.filter(function (m) {
1132
+ return animatables.includes(m.name);
1133
+ });
1134
+ machinesToRemove.forEach(function (m) {
1135
+ m.cleanup();
1136
+ _this.stateMachines.splice(_this.stateMachines.indexOf(m), 1);
1137
+ });
1138
+ removedNames = animationsToRemove
1139
+ .map(function (a) { return a.name; })
1140
+ .concat(machinesToRemove.map(function (m) { return m.name; }));
1141
+ }
1142
+ this.eventManager.fire({
1143
+ type: EventType.Stop,
1144
+ data: removedNames,
1145
+ });
1146
+ // Return the list of animations removed
1147
+ return removedNames;
1148
+ };
1149
+ Object.defineProperty(Animator.prototype, "isPlaying", {
1150
+ /**
1151
+ * Returns true if at least one animation is active
1152
+ */
1153
+ get: function () {
1154
+ return (this.animations.reduce(function (acc, curr) { return acc || curr.playing; }, false) ||
1155
+ this.stateMachines.reduce(function (acc, curr) { return acc || curr.playing; }, false));
1156
+ },
1157
+ enumerable: false,
1158
+ configurable: true
1159
+ });
1160
+ Object.defineProperty(Animator.prototype, "isPaused", {
1161
+ /**
1162
+ * Returns true if all animations are paused and there's at least one animation
1163
+ */
1164
+ get: function () {
1165
+ return (!this.isPlaying &&
1166
+ (this.animations.length > 0 || this.stateMachines.length > 0));
1167
+ },
1168
+ enumerable: false,
1169
+ configurable: true
1170
+ });
1171
+ Object.defineProperty(Animator.prototype, "isStopped", {
1172
+ /**
1173
+ * Returns true if there are no playing or paused animations/state machines
1174
+ */
1175
+ get: function () {
1176
+ return this.animations.length === 0 && this.stateMachines.length === 0;
1177
+ },
1178
+ enumerable: false,
1179
+ configurable: true
1180
+ });
1181
+ /**
1182
+ * If there are no animations or state machines, add the first one found
1183
+ * @returns the name of the animation or state machine instanced
1184
+ */
1185
+ Animator.prototype.atLeastOne = function (playing, fireEvent) {
1186
+ if (fireEvent === void 0) { fireEvent = true; }
1187
+ var instancedName;
1188
+ if (this.animations.length === 0 && this.stateMachines.length === 0) {
1189
+ if (this.artboard.animationCount() > 0) {
1190
+ // Add the first animation
1191
+ this.add([(instancedName = this.artboard.animationByIndex(0).name)], playing, fireEvent);
1192
+ }
1193
+ else if (this.artboard.stateMachineCount() > 0) {
1194
+ // Add the first state machine
1195
+ this.add([(instancedName = this.artboard.stateMachineByIndex(0).name)], playing, fireEvent);
1196
+ }
1197
+ }
1198
+ return instancedName;
1199
+ };
1200
+ /**
1201
+ * Checks if any animations have looped and if so, fire the appropriate event
1202
+ */
1203
+ Animator.prototype.handleLooping = function () {
1204
+ for (var _i = 0, _a = this.animations.filter(function (a) { return a.playing; }); _i < _a.length; _i++) {
1205
+ var animation = _a[_i];
1206
+ // Emit if the animation looped
1207
+ if (animation.loopValue === 0 && animation.loopCount) {
1208
+ animation.loopCount = 0;
1209
+ // This is a one-shot; if it has ended, delete the instance
1210
+ this.stop(animation.name);
1211
+ }
1212
+ else if (animation.loopValue === 1 && animation.loopCount) {
1213
+ this.eventManager.fire({
1214
+ type: EventType.Loop,
1215
+ data: { animation: animation.name, type: LoopType.Loop },
1216
+ });
1217
+ animation.loopCount = 0;
1218
+ }
1219
+ // Wasm indicates a loop at each time the animation
1220
+ // changes direction, so a full loop/lap occurs every
1221
+ // two loop counts
1222
+ else if (animation.loopValue === 2 && animation.loopCount > 1) {
1223
+ this.eventManager.fire({
1224
+ type: EventType.Loop,
1225
+ data: { animation: animation.name, type: LoopType.PingPong },
1226
+ });
1227
+ animation.loopCount = 0;
1228
+ }
1229
+ }
1230
+ };
1231
+ /**
1232
+ * Checks if states have changed in state machines and fires a statechange
1233
+ * event
1234
+ */
1235
+ Animator.prototype.handleStateChanges = function () {
1236
+ var statesChanged = [];
1237
+ for (var _i = 0, _a = this.stateMachines.filter(function (sm) { return sm.playing; }); _i < _a.length; _i++) {
1238
+ var stateMachine = _a[_i];
1239
+ statesChanged.push.apply(statesChanged, stateMachine.statesChanged);
1240
+ }
1241
+ if (statesChanged.length > 0) {
1242
+ this.eventManager.fire({
1243
+ type: EventType.StateChange,
1244
+ data: statesChanged,
1245
+ });
1246
+ }
1247
+ };
1248
+ Animator.prototype.handleAdvancing = function (time) {
1249
+ this.eventManager.fire({
1250
+ type: EventType.Advance,
1251
+ data: time,
1252
+ });
1253
+ };
1254
+ return Animator;
1255
+ }());
1256
+ // #endregion
1257
+ // #region events
1258
+ /**
1259
+ * Supported event types triggered in Rive
1260
+ */
1261
+ var EventType;
1262
+ (function (EventType) {
1263
+ EventType["Load"] = "load";
1264
+ EventType["LoadError"] = "loaderror";
1265
+ EventType["Play"] = "play";
1266
+ EventType["Pause"] = "pause";
1267
+ EventType["Stop"] = "stop";
1268
+ EventType["Loop"] = "loop";
1269
+ EventType["Draw"] = "draw";
1270
+ EventType["Advance"] = "advance";
1271
+ EventType["StateChange"] = "statechange";
1272
+ EventType["RiveEvent"] = "riveevent";
1273
+ })(EventType || (EventType = {}));
1274
+ /**
1275
+ * Looping types: one-shot, loop, and ping-pong
1276
+ */
1277
+ var LoopType;
1278
+ (function (LoopType) {
1279
+ LoopType["OneShot"] = "oneshot";
1280
+ LoopType["Loop"] = "loop";
1281
+ LoopType["PingPong"] = "pingpong";
1282
+ })(LoopType || (LoopType = {}));
1283
+ // Manages Rive events and listeners
1284
+ var EventManager = /** @class */ (function () {
1285
+ function EventManager(listeners) {
1286
+ if (listeners === void 0) { listeners = []; }
1287
+ this.listeners = listeners;
1288
+ }
1289
+ // Gets listeners of specified type
1290
+ EventManager.prototype.getListeners = function (type) {
1291
+ return this.listeners.filter(function (e) { return e.type === type; });
1292
+ };
1293
+ // Adds a listener
1294
+ EventManager.prototype.add = function (listener) {
1295
+ if (!this.listeners.includes(listener)) {
1296
+ this.listeners.push(listener);
1297
+ }
1298
+ };
1299
+ /**
1300
+ * Removes a listener
1301
+ * @param listener the listener with the callback to be removed
1302
+ */
1303
+ EventManager.prototype.remove = function (listener) {
1304
+ // We can't simply look for the listener as it'll be a different instance to
1305
+ // one originally subscribed. Find all the listeners of the right type and
1306
+ // then check their callbacks which should match.
1307
+ for (var i = 0; i < this.listeners.length; i++) {
1308
+ var currentListener = this.listeners[i];
1309
+ if (currentListener.type === listener.type) {
1310
+ if (currentListener.callback === listener.callback) {
1311
+ this.listeners.splice(i, 1);
1312
+ break;
1313
+ }
1314
+ }
1315
+ }
1316
+ };
1317
+ /**
1318
+ * Clears all listeners of specified type, or every listener if no type is
1319
+ * specified
1320
+ * @param type the type of listeners to clear, or all listeners if not
1321
+ * specified
1322
+ */
1323
+ EventManager.prototype.removeAll = function (type) {
1324
+ var _this = this;
1325
+ if (!type) {
1326
+ this.listeners.splice(0, this.listeners.length);
1327
+ }
1328
+ else {
1329
+ this.listeners
1330
+ .filter(function (l) { return l.type === type; })
1331
+ .forEach(function (l) { return _this.remove(l); });
1332
+ }
1333
+ };
1334
+ // Fires an event
1335
+ EventManager.prototype.fire = function (event) {
1336
+ var eventListeners = this.getListeners(event.type);
1337
+ eventListeners.forEach(function (listener) { return listener.callback(event); });
1338
+ };
1339
+ return EventManager;
1340
+ }());
1341
+ // Manages a queue of tasks
1342
+ var TaskQueueManager = /** @class */ (function () {
1343
+ function TaskQueueManager(eventManager) {
1344
+ this.eventManager = eventManager;
1345
+ this.queue = [];
1346
+ }
1347
+ // Adds a task top the queue
1348
+ TaskQueueManager.prototype.add = function (task) {
1349
+ this.queue.push(task);
1350
+ };
1351
+ // Processes all tasks in the queue
1352
+ TaskQueueManager.prototype.process = function () {
1353
+ while (this.queue.length > 0) {
1354
+ var task = this.queue.shift();
1355
+ if (task === null || task === void 0 ? void 0 : task.action) {
1356
+ task.action();
1357
+ }
1358
+ if (task === null || task === void 0 ? void 0 : task.event) {
1359
+ this.eventManager.fire(task.event);
1360
+ }
1361
+ }
1362
+ };
1363
+ return TaskQueueManager;
1364
+ }());
1365
+ var Rive = /** @class */ (function () {
1366
+ function Rive(params) {
1367
+ var _a;
1368
+ // Tracks if a Rive file is loaded
1369
+ this.loaded = false;
1370
+ /**
1371
+ * Tracks if a Rive file is loaded; we need this in addition to loaded as some
1372
+ * commands (e.g. contents) can be called as soon as the file is loaded.
1373
+ * However, playback commands need to be queued and run in order once initial
1374
+ * animations and autoplay has been sorted out. This applies to play, pause,
1375
+ * and start.
1376
+ */
1377
+ this.readyForPlaying = false;
1378
+ // Runtime artboard
1379
+ this.artboard = null;
1380
+ // place to clear up event listeners
1381
+ this.eventCleanup = null;
1382
+ this.shouldDisableRiveListeners = false;
1383
+ this.automaticallyHandleEvents = false;
1384
+ // Allow the runtime to automatically load assets hosted in Rive's runtime.
1385
+ this.enableRiveAssetCDN = true;
1386
+ // Durations to generate a frame for the last second. Used for performance profiling.
1387
+ this.durations = [];
1388
+ this.frameTimes = [];
1389
+ this.frameCount = 0;
1390
+ /**
1391
+ * Used be draw to track when a second of active rendering time has passed.
1392
+ * Used for debugging purposes
1393
+ */
1394
+ this.renderSecondTimer = 0;
1395
+ this.canvas = params.canvas;
1396
+ this.src = params.src;
1397
+ this.buffer = params.buffer;
1398
+ this.layout = (_a = params.layout) !== null && _a !== void 0 ? _a : new Layout();
1399
+ this.shouldDisableRiveListeners = !!params.shouldDisableRiveListeners;
1400
+ this.automaticallyHandleEvents = !!params.automaticallyHandleEvents;
1401
+ this.enableRiveAssetCDN =
1402
+ params.enableRiveAssetCDN === undefined
1403
+ ? true
1404
+ : params.enableRiveAssetCDN;
1405
+ // New event management system
1406
+ this.eventManager = new EventManager();
1407
+ if (params.onLoad)
1408
+ this.on(EventType.Load, params.onLoad);
1409
+ if (params.onLoadError)
1410
+ this.on(EventType.LoadError, params.onLoadError);
1411
+ if (params.onPlay)
1412
+ this.on(EventType.Play, params.onPlay);
1413
+ if (params.onPause)
1414
+ this.on(EventType.Pause, params.onPause);
1415
+ if (params.onStop)
1416
+ this.on(EventType.Stop, params.onStop);
1417
+ if (params.onLoop)
1418
+ this.on(EventType.Loop, params.onLoop);
1419
+ if (params.onStateChange)
1420
+ this.on(EventType.StateChange, params.onStateChange);
1421
+ if (params.onAdvance)
1422
+ this.on(EventType.Advance, params.onAdvance);
1423
+ /**
1424
+ * @deprecated Use camelCase'd versions instead.
1425
+ */
1426
+ if (params.onload && !params.onLoad)
1427
+ this.on(EventType.Load, params.onload);
1428
+ if (params.onloaderror && !params.onLoadError)
1429
+ this.on(EventType.LoadError, params.onloaderror);
1430
+ if (params.onplay && !params.onPlay)
1431
+ this.on(EventType.Play, params.onplay);
1432
+ if (params.onpause && !params.onPause)
1433
+ this.on(EventType.Pause, params.onpause);
1434
+ if (params.onstop && !params.onStop)
1435
+ this.on(EventType.Stop, params.onstop);
1436
+ if (params.onloop && !params.onLoop)
1437
+ this.on(EventType.Loop, params.onloop);
1438
+ if (params.onstatechange && !params.onStateChange)
1439
+ this.on(EventType.StateChange, params.onstatechange);
1440
+ /**
1441
+ * Asset loading
1442
+ */
1443
+ if (params.assetLoader)
1444
+ this.assetLoader = params.assetLoader;
1445
+ // Hook up the task queue
1446
+ this.taskQueue = new TaskQueueManager(this.eventManager);
1447
+ this.init({
1448
+ src: this.src,
1449
+ buffer: this.buffer,
1450
+ autoplay: params.autoplay,
1451
+ animations: params.animations,
1452
+ stateMachines: params.stateMachines,
1453
+ artboard: params.artboard,
1454
+ useOffscreenRenderer: params.useOffscreenRenderer,
1455
+ });
1456
+ }
1457
+ // Alternative constructor to build a Rive instance from an interface/object
1458
+ Rive.new = function (params) {
1459
+ console.warn("This function is deprecated: please use `new Rive({})` instead");
1460
+ return new Rive(params);
1461
+ };
1462
+ // Initializes the Rive object either from constructor or load()
1463
+ Rive.prototype.init = function (_a) {
1464
+ var _this = this;
1465
+ var src = _a.src, buffer = _a.buffer, animations = _a.animations, stateMachines = _a.stateMachines, artboard = _a.artboard, _b = _a.autoplay, autoplay = _b === void 0 ? false : _b, _c = _a.useOffscreenRenderer, useOffscreenRenderer = _c === void 0 ? false : _c;
1466
+ this.src = src;
1467
+ this.buffer = buffer;
1468
+ // If no source file url specified, it's a bust
1469
+ if (!this.src && !this.buffer) {
1470
+ throw new Error(Rive.missingErrorMessage);
1471
+ }
1472
+ // List of animations that should be initialized.
1473
+ var startingAnimationNames = mapToStringArray(animations);
1474
+ // List of state machines that should be initialized
1475
+ var startingStateMachineNames = mapToStringArray(stateMachines);
1476
+ // Ensure loaded is marked as false if loading new file
1477
+ this.loaded = false;
1478
+ this.readyForPlaying = false;
1479
+ // Ensure the runtime is loaded
1480
+ RuntimeLoader.awaitInstance()
1481
+ .then(function (runtime) {
1482
+ _this.runtime = runtime;
1483
+ // Get the canvas where you want to render the animation and create a renderer
1484
+ _this.renderer = _this.runtime.makeRenderer(_this.canvas, useOffscreenRenderer);
1485
+ // Initial size adjustment based on devicePixelRatio if no width/height are
1486
+ // specified explicitly
1487
+ if (!(_this.canvas.width || _this.canvas.height)) {
1488
+ _this.resizeDrawingSurfaceToCanvas();
1489
+ }
1490
+ // Load Rive data from a source uri or a data buffer
1491
+ _this.initData(artboard, startingAnimationNames, startingStateMachineNames, autoplay)
1492
+ .then(function () { return _this.setupRiveListeners(); })
1493
+ .catch(function (e) {
1494
+ console.error(e);
1495
+ });
1496
+ })
1497
+ .catch(function (e) {
1498
+ console.error(e);
1499
+ });
1500
+ };
1501
+ Rive.prototype.setupRiveListeners = function () {
1502
+ var _this = this;
1503
+ if (!this.shouldDisableRiveListeners) {
1504
+ var activeStateMachines = (this.animator.stateMachines || [])
1505
+ .filter(function (sm) { return sm.playing && _this.runtime.hasListeners(sm.instance); })
1506
+ .map(function (sm) { return sm.instance; });
1507
+ this.eventCleanup = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.registerTouchInteractions)({
1508
+ canvas: this.canvas,
1509
+ artboard: this.artboard,
1510
+ stateMachines: activeStateMachines,
1511
+ renderer: this.renderer,
1512
+ rive: this.runtime,
1513
+ fit: this._layout.runtimeFit(this.runtime),
1514
+ alignment: this._layout.runtimeAlignment(this.runtime),
1515
+ });
1516
+ }
1517
+ };
1518
+ // Initializes runtime with Rive data and preps for playing
1519
+ Rive.prototype.initData = function (artboardName, animationNames, stateMachineNames, autoplay) {
1520
+ var _a;
1521
+ return __awaiter(this, void 0, void 0, function () {
1522
+ var _b, loader, _c, msg;
1523
+ return __generator(this, function (_d) {
1524
+ switch (_d.label) {
1525
+ case 0:
1526
+ if (!this.src) return [3 /*break*/, 2];
1527
+ _b = this;
1528
+ return [4 /*yield*/, loadRiveFile(this.src)];
1529
+ case 1:
1530
+ _b.buffer = _d.sent();
1531
+ _d.label = 2;
1532
+ case 2:
1533
+ if (this.assetLoader) {
1534
+ loader = new this.runtime.CustomFileAssetLoader({
1535
+ loadContents: this.assetLoader,
1536
+ });
1537
+ }
1538
+ // Load the Rive file
1539
+ _c = this;
1540
+ return [4 /*yield*/, this.runtime.load(new Uint8Array(this.buffer), loader, this.enableRiveAssetCDN)];
1541
+ case 3:
1542
+ // Load the Rive file
1543
+ _c.file = _d.sent();
1544
+ if (this.file) {
1545
+ // Initialize and draw frame
1546
+ this.initArtboard(artboardName, animationNames, stateMachineNames, autoplay);
1547
+ // Everything's set up, emit a load event
1548
+ this.loaded = true;
1549
+ this.eventManager.fire({
1550
+ type: EventType.Load,
1551
+ data: (_a = this.src) !== null && _a !== void 0 ? _a : "buffer",
1552
+ });
1553
+ // Flag ready for playback commands and clear the task queue; this order
1554
+ // is important or it may infinitely recurse
1555
+ this.readyForPlaying = true;
1556
+ this.taskQueue.process();
1557
+ this.drawFrame();
1558
+ return [2 /*return*/, Promise.resolve()];
1559
+ }
1560
+ else {
1561
+ msg = "Problem loading file; may be corrupt!";
1562
+ console.warn(msg);
1563
+ this.eventManager.fire({ type: EventType.LoadError, data: msg });
1564
+ return [2 /*return*/, Promise.reject(msg)];
1565
+ }
1566
+ return [2 /*return*/];
1567
+ }
1568
+ });
1569
+ });
1570
+ };
1571
+ // Initialize for playback
1572
+ Rive.prototype.initArtboard = function (artboardName, animationNames, stateMachineNames, autoplay) {
1573
+ // Fetch the artboard
1574
+ var rootArtboard = artboardName
1575
+ ? this.file.artboardByName(artboardName)
1576
+ : this.file.defaultArtboard();
1577
+ // Check we have a working artboard
1578
+ if (!rootArtboard) {
1579
+ var msg = "Invalid artboard name or no default artboard";
1580
+ console.warn(msg);
1581
+ this.eventManager.fire({ type: EventType.LoadError, data: msg });
1582
+ return;
1583
+ }
1584
+ this.artboard = rootArtboard;
1585
+ // Check that the artboard has at least 1 animation
1586
+ if (this.artboard.animationCount() < 1) {
1587
+ var msg = "Artboard has no animations";
1588
+ this.eventManager.fire({ type: EventType.LoadError, data: msg });
1589
+ throw msg;
1590
+ }
1591
+ // Initialize the animator
1592
+ this.animator = new Animator(this.runtime, this.artboard, this.eventManager);
1593
+ // Initialize the animations; as loaded hasn't happened yet, we need to
1594
+ // suppress firing the play/pause events until the load event has fired. To
1595
+ // do this we tell the animator to suppress firing events, and add event
1596
+ // firing to the task queue.
1597
+ var instanceNames;
1598
+ if (animationNames.length > 0 || stateMachineNames.length > 0) {
1599
+ instanceNames = animationNames.concat(stateMachineNames);
1600
+ this.animator.initLinearAnimations(animationNames, autoplay);
1601
+ this.animator.initStateMachines(stateMachineNames, autoplay);
1602
+ }
1603
+ else {
1604
+ instanceNames = [this.animator.atLeastOne(autoplay, false)];
1605
+ }
1606
+ // Queue up firing the playback events
1607
+ this.taskQueue.add({
1608
+ event: {
1609
+ type: autoplay ? EventType.Play : EventType.Pause,
1610
+ data: instanceNames,
1611
+ },
1612
+ });
1613
+ };
1614
+ // Draws the current artboard frame
1615
+ Rive.prototype.drawFrame = function () {
1616
+ this.startRendering();
1617
+ };
1618
+ /**
1619
+ * Draw rendering loop; renders animation frames at the correct time interval.
1620
+ * @param time the time at which to render a frame
1621
+ */
1622
+ Rive.prototype.draw = function (time, onSecond) {
1623
+ var before = performance.now();
1624
+ // Clear the frameRequestId, as we're now rendering a fresh frame
1625
+ this.frameRequestId = null;
1626
+ // On the first pass, make sure lastTime has a valid value
1627
+ if (!this.lastRenderTime) {
1628
+ this.lastRenderTime = time;
1629
+ }
1630
+ // Handle the onSecond callback
1631
+ this.renderSecondTimer += time - this.lastRenderTime;
1632
+ if (this.renderSecondTimer > 5000) {
1633
+ this.renderSecondTimer = 0;
1634
+ onSecond === null || onSecond === void 0 ? void 0 : onSecond();
1635
+ }
1636
+ // Calculate the elapsed time between frames in seconds
1637
+ var elapsedTime = (time - this.lastRenderTime) / 1000;
1638
+ this.lastRenderTime = time;
1639
+ // - Advance non-paused animations by the elapsed number of seconds
1640
+ // - Advance any animations that require scrubbing
1641
+ // - Advance to the first frame even when autoplay is false
1642
+ var activeAnimations = this.animator.animations
1643
+ .filter(function (a) { return a.playing || a.needsScrub; })
1644
+ // The scrubbed animations must be applied first to prevent weird artifacts
1645
+ // if the playing animations conflict with the scrubbed animating attribuates.
1646
+ .sort(function (first) { return (first.needsScrub ? -1 : 1); });
1647
+ for (var _i = 0, activeAnimations_1 = activeAnimations; _i < activeAnimations_1.length; _i++) {
1648
+ var animation = activeAnimations_1[_i];
1649
+ animation.advance(elapsedTime);
1650
+ if (animation.instance.didLoop) {
1651
+ animation.loopCount += 1;
1652
+ }
1653
+ animation.apply(1.0);
1654
+ }
1655
+ // - Advance non-paused state machines by the elapsed number of seconds
1656
+ // - Advance to the first frame even when autoplay is false
1657
+ var activeStateMachines = this.animator.stateMachines.filter(function (a) { return a.playing; });
1658
+ for (var _a = 0, activeStateMachines_1 = activeStateMachines; _a < activeStateMachines_1.length; _a++) {
1659
+ var stateMachine = activeStateMachines_1[_a];
1660
+ // Check for events before the current frame's state machine advance
1661
+ var numEventsReported = stateMachine.reportedEventCount();
1662
+ if (numEventsReported) {
1663
+ for (var i = 0; i < numEventsReported; i++) {
1664
+ var event_1 = stateMachine.reportedEventAt(i);
1665
+ if (event_1) {
1666
+ if (event_1.type === RiveEventType.OpenUrl) {
1667
+ this.eventManager.fire({
1668
+ type: EventType.RiveEvent,
1669
+ data: event_1,
1670
+ });
1671
+ // Handle the event side effect if explicitly enabled
1672
+ if (this.automaticallyHandleEvents) {
1673
+ var newAnchorTag = document.createElement("a");
1674
+ var _b = event_1, url = _b.url, target = _b.target;
1675
+ var sanitizedUrl = (0,_utils__WEBPACK_IMPORTED_MODULE_2__.sanitizeUrl)(url);
1676
+ url && newAnchorTag.setAttribute("href", sanitizedUrl);
1677
+ target && newAnchorTag.setAttribute("target", target);
1678
+ if (sanitizedUrl && sanitizedUrl !== _utils__WEBPACK_IMPORTED_MODULE_2__.BLANK_URL) {
1679
+ newAnchorTag.click();
1680
+ }
1681
+ }
1682
+ }
1683
+ else {
1684
+ this.eventManager.fire({
1685
+ type: EventType.RiveEvent,
1686
+ data: event_1,
1687
+ });
1688
+ }
1689
+ }
1690
+ }
1691
+ }
1692
+ stateMachine.advance(elapsedTime);
1693
+ // stateMachine.instance.apply(this.artboard);
1694
+ }
1695
+ // Once the animations have been applied to the artboard, advance it
1696
+ // by the elapsed time.
1697
+ this.artboard.advance(elapsedTime);
1698
+ var renderer = this.renderer;
1699
+ // Canvas must be wiped to prevent artifacts
1700
+ renderer.clear();
1701
+ renderer.save();
1702
+ // Update the renderer alignment if necessary
1703
+ this.alignRenderer();
1704
+ this.artboard.draw(renderer);
1705
+ renderer.restore();
1706
+ renderer.flush();
1707
+ // Check for any animations that looped
1708
+ this.animator.handleLooping();
1709
+ // Check for any state machines that had a state change
1710
+ this.animator.handleStateChanges();
1711
+ // Report advanced time
1712
+ this.animator.handleAdvancing(elapsedTime);
1713
+ // Add duration to create frame to durations array
1714
+ this.frameCount++;
1715
+ var after = performance.now();
1716
+ this.frameTimes.push(after);
1717
+ this.durations.push(after - before);
1718
+ while (this.frameTimes[0] <= after - 1000) {
1719
+ this.frameTimes.shift();
1720
+ this.durations.shift();
1721
+ }
1722
+ // Calling requestAnimationFrame will rerun draw() at the correct rate:
1723
+ // https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations
1724
+ if (this.animator.isPlaying) {
1725
+ // Request a new rendering frame
1726
+ this.startRendering();
1727
+ }
1728
+ else if (this.animator.isPaused) {
1729
+ // Reset the end time so on playback it starts at the correct frame
1730
+ this.lastRenderTime = 0;
1731
+ }
1732
+ else if (this.animator.isStopped) {
1733
+ // Reset animation instances, artboard and time
1734
+ // TODO: implement this properly when we have instancing
1735
+ // this.initArtboard();
1736
+ // this.drawFrame();
1737
+ this.lastRenderTime = 0;
1738
+ }
1739
+ };
1740
+ /**
1741
+ * Align the renderer
1742
+ */
1743
+ Rive.prototype.alignRenderer = function () {
1744
+ var _a = this, renderer = _a.renderer, runtime = _a.runtime, _layout = _a._layout, artboard = _a.artboard;
1745
+ // Align things up safe in the knowledge we can restore if changed
1746
+ renderer.align(_layout.runtimeFit(runtime), _layout.runtimeAlignment(runtime), {
1747
+ minX: _layout.minX,
1748
+ minY: _layout.minY,
1749
+ maxX: _layout.maxX,
1750
+ maxY: _layout.maxY,
1751
+ }, artboard.bounds);
1752
+ };
1753
+ Object.defineProperty(Rive.prototype, "fps", {
1754
+ get: function () {
1755
+ return this.durations.length;
1756
+ },
1757
+ enumerable: false,
1758
+ configurable: true
1759
+ });
1760
+ Object.defineProperty(Rive.prototype, "frameTime", {
1761
+ get: function () {
1762
+ if (this.durations.length === 0) {
1763
+ return 0;
1764
+ }
1765
+ return (this.durations.reduce(function (a, b) { return a + b; }, 0) / this.durations.length).toFixed(4);
1766
+ },
1767
+ enumerable: false,
1768
+ configurable: true
1769
+ });
1770
+ /**
1771
+ * Cleans up all Wasm-generated objects that need to be manually destroyed:
1772
+ * artboard instances, animation instances, state machine instances,
1773
+ * renderer instance, file and runtime.
1774
+ *
1775
+ * Once this is called, you will need to initialise a new instance of the
1776
+ * Rive class
1777
+ */
1778
+ Rive.prototype.cleanup = function () {
1779
+ var _a, _b;
1780
+ // Stop the renderer if it hasn't already been stopped.
1781
+ this.stopRendering();
1782
+ // Clean up any artboard, animation or state machine instances.
1783
+ this.cleanupInstances();
1784
+ // Delete the renderer
1785
+ (_a = this.renderer) === null || _a === void 0 ? void 0 : _a.delete();
1786
+ this.renderer = null;
1787
+ // Delete the rive file
1788
+ (_b = this.file) === null || _b === void 0 ? void 0 : _b.delete();
1789
+ this.file = null;
1790
+ };
1791
+ /**
1792
+ * Cleans up any Wasm-generated objects that need to be manually destroyed:
1793
+ * artboard instances, animation instances, state machine instances.
1794
+ *
1795
+ * Once this is called, things will need to be reinitialized or bad things
1796
+ * might happen.
1797
+ */
1798
+ Rive.prototype.cleanupInstances = function () {
1799
+ if (this.eventCleanup !== null) {
1800
+ this.eventCleanup();
1801
+ }
1802
+ // Delete all animation and state machine instances
1803
+ this.stop();
1804
+ if (this.artboard) {
1805
+ this.artboard.delete();
1806
+ this.artboard = null;
1807
+ }
1808
+ };
1809
+ /**
1810
+ * Tries to query the setup Artboard for a text run node with the given name.
1811
+ *
1812
+ * @param textRunName - Name of the text run node associated with a text object
1813
+ * @returns - TextValueRun node or undefined if the text run cannot be queried
1814
+ */
1815
+ Rive.prototype.retrieveTextRun = function (textRunName) {
1816
+ var _a;
1817
+ if (!textRunName) {
1818
+ console.warn("No text run name provided");
1819
+ return;
1820
+ }
1821
+ if (!this.artboard) {
1822
+ console.warn("Tried to access text run, but the Artboard is null");
1823
+ return;
1824
+ }
1825
+ var textRun = this.artboard.textRun(textRunName);
1826
+ if (!textRun) {
1827
+ console.warn("Could not access a text run with name '".concat(textRunName, "' in the '").concat((_a = this.artboard) === null || _a === void 0 ? void 0 : _a.name, "' Artboard. Note that you must rename a text run node in the Rive editor to make it queryable at runtime."));
1828
+ return;
1829
+ }
1830
+ return textRun;
1831
+ };
1832
+ /**
1833
+ * Returns a string from a given text run node name, or undefined if the text run
1834
+ * cannot be queried.
1835
+ *
1836
+ * @param textRunName - Name of the text run node associated with a text object
1837
+ * @returns - String value of the text run node or undefined
1838
+ */
1839
+ Rive.prototype.getTextRunValue = function (textRunName) {
1840
+ var textRun = this.retrieveTextRun(textRunName);
1841
+ return textRun ? textRun.text : undefined;
1842
+ };
1843
+ /**
1844
+ * Sets a text value for a given text run node name if possible
1845
+ *
1846
+ * @param textRunName - Name of the text run node associated with a text object
1847
+ * @param textRunValue - String value to set on the text run node
1848
+ */
1849
+ Rive.prototype.setTextRunValue = function (textRunName, textRunValue) {
1850
+ var textRun = this.retrieveTextRun(textRunName);
1851
+ if (textRun) {
1852
+ textRun.text = textRunValue;
1853
+ }
1854
+ };
1855
+ // Plays specified animations; if none specified, it unpauses everything.
1856
+ Rive.prototype.play = function (animationNames, autoplay) {
1857
+ var _this = this;
1858
+ animationNames = mapToStringArray(animationNames);
1859
+ // If the file's not loaded, queue up the play
1860
+ if (!this.readyForPlaying) {
1861
+ this.taskQueue.add({
1862
+ action: function () { return _this.play(animationNames, autoplay); },
1863
+ });
1864
+ return;
1865
+ }
1866
+ this.animator.play(animationNames);
1867
+ if (this.eventCleanup) {
1868
+ this.eventCleanup();
1869
+ }
1870
+ this.setupRiveListeners();
1871
+ this.startRendering();
1872
+ };
1873
+ // Pauses specified animations; if none specified, pauses all.
1874
+ Rive.prototype.pause = function (animationNames) {
1875
+ var _this = this;
1876
+ animationNames = mapToStringArray(animationNames);
1877
+ // If the file's not loaded, early out, nothing to pause
1878
+ if (!this.readyForPlaying) {
1879
+ this.taskQueue.add({
1880
+ action: function () { return _this.pause(animationNames); },
1881
+ });
1882
+ return;
1883
+ }
1884
+ if (this.eventCleanup) {
1885
+ this.eventCleanup();
1886
+ }
1887
+ this.animator.pause(animationNames);
1888
+ };
1889
+ Rive.prototype.scrub = function (animationNames, value) {
1890
+ var _this = this;
1891
+ animationNames = mapToStringArray(animationNames);
1892
+ // If the file's not loaded, early out, nothing to pause
1893
+ if (!this.readyForPlaying) {
1894
+ this.taskQueue.add({
1895
+ action: function () { return _this.scrub(animationNames, value); },
1896
+ });
1897
+ return;
1898
+ }
1899
+ // Scrub the animation time; we draw a single frame here so that if
1900
+ // nothing's currently playing, the scrubbed animation is still rendered/
1901
+ this.animator.scrub(animationNames, value || 0);
1902
+ this.drawFrame();
1903
+ };
1904
+ // Stops specified animations; if none specifies, stops them all.
1905
+ Rive.prototype.stop = function (animationNames) {
1906
+ var _this = this;
1907
+ animationNames = mapToStringArray(animationNames);
1908
+ // If the file's not loaded, early out, nothing to pause
1909
+ if (!this.readyForPlaying) {
1910
+ this.taskQueue.add({
1911
+ action: function () { return _this.stop(animationNames); },
1912
+ });
1913
+ return;
1914
+ }
1915
+ this.animator.stop(animationNames);
1916
+ if (this.eventCleanup) {
1917
+ this.eventCleanup();
1918
+ }
1919
+ };
1920
+ /**
1921
+ * Resets the animation
1922
+ * @param artboard the name of the artboard, or default if none given
1923
+ * @param animations the names of animations for playback
1924
+ * @param stateMachines the names of state machines for playback
1925
+ * @param autoplay whether to autoplay when reset, defaults to false
1926
+ *
1927
+ */
1928
+ Rive.prototype.reset = function (params) {
1929
+ var _a;
1930
+ // Get the current artboard, animations, state machines, and playback states
1931
+ var artBoardName = params === null || params === void 0 ? void 0 : params.artboard;
1932
+ var animationNames = mapToStringArray(params === null || params === void 0 ? void 0 : params.animations);
1933
+ var stateMachineNames = mapToStringArray(params === null || params === void 0 ? void 0 : params.stateMachines);
1934
+ var autoplay = (_a = params === null || params === void 0 ? void 0 : params.autoplay) !== null && _a !== void 0 ? _a : false;
1935
+ // Stop everything and clean up
1936
+ this.cleanupInstances();
1937
+ // Reinitialize an artboard instance with the state
1938
+ this.initArtboard(artBoardName, animationNames, stateMachineNames, autoplay);
1939
+ this.taskQueue.process();
1940
+ };
1941
+ // Loads a new Rive file, keeping listeners in place
1942
+ Rive.prototype.load = function (params) {
1943
+ // Stop all animations
1944
+ this.stop();
1945
+ // Reinitialize
1946
+ this.init(params);
1947
+ };
1948
+ Object.defineProperty(Rive.prototype, "layout", {
1949
+ /**
1950
+ * Returns the current layout. Note that layout should be treated as
1951
+ * immutable. If you want to change the layout, create a new one use the
1952
+ * layout setter
1953
+ */
1954
+ get: function () {
1955
+ return this._layout;
1956
+ },
1957
+ // Sets a new layout
1958
+ set: function (layout) {
1959
+ this._layout = layout;
1960
+ // If the maxX or maxY are 0, then set them to the canvas width and height
1961
+ if (!layout.maxX || !layout.maxY) {
1962
+ this.resizeToCanvas();
1963
+ }
1964
+ if (this.loaded && !this.animator.isPlaying) {
1965
+ this.drawFrame();
1966
+ }
1967
+ },
1968
+ enumerable: false,
1969
+ configurable: true
1970
+ });
1971
+ /**
1972
+ * Sets the layout bounds to the current canvas size; this is typically called
1973
+ * when the canvas is resized
1974
+ */
1975
+ Rive.prototype.resizeToCanvas = function () {
1976
+ this._layout = this.layout.copyWith({
1977
+ minX: 0,
1978
+ minY: 0,
1979
+ maxX: this.canvas.width,
1980
+ maxY: this.canvas.height,
1981
+ });
1982
+ };
1983
+ /**
1984
+ * Accounts for devicePixelRatio as a multiplier to render the size of the canvas drawing surface.
1985
+ * Uses the size of the backing canvas to set new width/height attributes. Need to re-render
1986
+ * and resize the layout to match the new drawing surface afterwards.
1987
+ * Useful function for consumers to include in a window resize listener
1988
+ */
1989
+ Rive.prototype.resizeDrawingSurfaceToCanvas = function () {
1990
+ if (this.canvas instanceof HTMLCanvasElement && !!window) {
1991
+ var _a = this.canvas.getBoundingClientRect(), width = _a.width, height = _a.height;
1992
+ var dpr = window.devicePixelRatio || 1;
1993
+ this.canvas.width = dpr * width;
1994
+ this.canvas.height = dpr * height;
1995
+ this.startRendering();
1996
+ this.resizeToCanvas();
1997
+ }
1998
+ };
1999
+ Object.defineProperty(Rive.prototype, "source", {
2000
+ // Returns the animation source, which may be undefined
2001
+ get: function () {
2002
+ return this.src;
2003
+ },
2004
+ enumerable: false,
2005
+ configurable: true
2006
+ });
2007
+ Object.defineProperty(Rive.prototype, "activeArtboard", {
2008
+ /**
2009
+ * Returns the name of the active artboard
2010
+ */
2011
+ get: function () {
2012
+ return this.artboard ? this.artboard.name : "";
2013
+ },
2014
+ enumerable: false,
2015
+ configurable: true
2016
+ });
2017
+ Object.defineProperty(Rive.prototype, "animationNames", {
2018
+ // Returns a list of animation names on the chosen artboard
2019
+ get: function () {
2020
+ // If the file's not loaded, we got nothing to return
2021
+ if (!this.loaded) {
2022
+ return [];
2023
+ }
2024
+ var animationNames = [];
2025
+ for (var i = 0; i < this.artboard.animationCount(); i++) {
2026
+ animationNames.push(this.artboard.animationByIndex(i).name);
2027
+ }
2028
+ return animationNames;
2029
+ },
2030
+ enumerable: false,
2031
+ configurable: true
2032
+ });
2033
+ Object.defineProperty(Rive.prototype, "stateMachineNames", {
2034
+ /**
2035
+ * Returns a list of state machine names from the current artboard
2036
+ */
2037
+ get: function () {
2038
+ // If the file's not loaded, we got nothing to return
2039
+ if (!this.loaded) {
2040
+ return [];
2041
+ }
2042
+ var stateMachineNames = [];
2043
+ for (var i = 0; i < this.artboard.stateMachineCount(); i++) {
2044
+ stateMachineNames.push(this.artboard.stateMachineByIndex(i).name);
2045
+ }
2046
+ return stateMachineNames;
2047
+ },
2048
+ enumerable: false,
2049
+ configurable: true
2050
+ });
2051
+ /**
2052
+ * Returns the inputs for the specified instanced state machine, or an empty
2053
+ * list if the name is invalid or the state machine is not instanced
2054
+ * @param name the state machine name
2055
+ * @returns the inputs for the named state machine
2056
+ */
2057
+ Rive.prototype.stateMachineInputs = function (name) {
2058
+ // If the file's not loaded, early out, nothing to pause
2059
+ if (!this.loaded) {
2060
+ return;
2061
+ }
2062
+ var stateMachine = this.animator.stateMachines.find(function (m) { return m.name === name; });
2063
+ return stateMachine === null || stateMachine === void 0 ? void 0 : stateMachine.inputs;
2064
+ };
2065
+ Object.defineProperty(Rive.prototype, "playingStateMachineNames", {
2066
+ // Returns a list of playing machine names
2067
+ get: function () {
2068
+ // If the file's not loaded, we got nothing to return
2069
+ if (!this.loaded) {
2070
+ return [];
2071
+ }
2072
+ return this.animator.stateMachines
2073
+ .filter(function (m) { return m.playing; })
2074
+ .map(function (m) { return m.name; });
2075
+ },
2076
+ enumerable: false,
2077
+ configurable: true
2078
+ });
2079
+ Object.defineProperty(Rive.prototype, "playingAnimationNames", {
2080
+ // Returns a list of playing animation names
2081
+ get: function () {
2082
+ // If the file's not loaded, we got nothing to return
2083
+ if (!this.loaded) {
2084
+ return [];
2085
+ }
2086
+ return this.animator.animations.filter(function (a) { return a.playing; }).map(function (a) { return a.name; });
2087
+ },
2088
+ enumerable: false,
2089
+ configurable: true
2090
+ });
2091
+ Object.defineProperty(Rive.prototype, "pausedAnimationNames", {
2092
+ // Returns a list of paused animation names
2093
+ get: function () {
2094
+ // If the file's not loaded, we got nothing to return
2095
+ if (!this.loaded) {
2096
+ return [];
2097
+ }
2098
+ return this.animator.animations
2099
+ .filter(function (a) { return !a.playing; })
2100
+ .map(function (a) { return a.name; });
2101
+ },
2102
+ enumerable: false,
2103
+ configurable: true
2104
+ });
2105
+ Object.defineProperty(Rive.prototype, "pausedStateMachineNames", {
2106
+ /**
2107
+ * Returns a list of paused machine names
2108
+ * @returns a list of state machine names that are paused
2109
+ */
2110
+ get: function () {
2111
+ // If the file's not loaded, we got nothing to return
2112
+ if (!this.loaded) {
2113
+ return [];
2114
+ }
2115
+ return this.animator.stateMachines
2116
+ .filter(function (m) { return !m.playing; })
2117
+ .map(function (m) { return m.name; });
2118
+ },
2119
+ enumerable: false,
2120
+ configurable: true
2121
+ });
2122
+ Object.defineProperty(Rive.prototype, "isPlaying", {
2123
+ /**
2124
+ * @returns true if any animation is playing
2125
+ */
2126
+ get: function () {
2127
+ return this.animator.isPlaying;
2128
+ },
2129
+ enumerable: false,
2130
+ configurable: true
2131
+ });
2132
+ Object.defineProperty(Rive.prototype, "isPaused", {
2133
+ /**
2134
+ * @returns true if all instanced animations are paused
2135
+ */
2136
+ get: function () {
2137
+ return this.animator.isPaused;
2138
+ },
2139
+ enumerable: false,
2140
+ configurable: true
2141
+ });
2142
+ Object.defineProperty(Rive.prototype, "isStopped", {
2143
+ /**
2144
+ * @returns true if no animations are playing or paused
2145
+ */
2146
+ get: function () {
2147
+ return this.animator.isStopped;
2148
+ },
2149
+ enumerable: false,
2150
+ configurable: true
2151
+ });
2152
+ Object.defineProperty(Rive.prototype, "bounds", {
2153
+ /**
2154
+ * @returns the bounds of the current artboard, or undefined if the artboard
2155
+ * isn't loaded yet.
2156
+ */
2157
+ get: function () {
2158
+ return this.artboard ? this.artboard.bounds : undefined;
2159
+ },
2160
+ enumerable: false,
2161
+ configurable: true
2162
+ });
2163
+ /**
2164
+ * Subscribe to Rive-generated events
2165
+ * @param type the type of event to subscribe to
2166
+ * @param callback callback to fire when the event occurs
2167
+ */
2168
+ Rive.prototype.on = function (type, callback) {
2169
+ this.eventManager.add({
2170
+ type: type,
2171
+ callback: callback,
2172
+ });
2173
+ };
2174
+ /**
2175
+ * Unsubscribes from a Rive-generated event
2176
+ * @param type the type of event to unsubscribe from
2177
+ * @param callback the callback to unsubscribe
2178
+ */
2179
+ Rive.prototype.off = function (type, callback) {
2180
+ this.eventManager.remove({
2181
+ type: type,
2182
+ callback: callback,
2183
+ });
2184
+ };
2185
+ /**
2186
+ * Unsubscribes from a Rive-generated event
2187
+ * @deprecated
2188
+ * @param callback the callback to unsubscribe from
2189
+ */
2190
+ Rive.prototype.unsubscribe = function (type, callback) {
2191
+ console.warn("This function is deprecated: please use `off()` instead.");
2192
+ this.off(type, callback);
2193
+ };
2194
+ /**
2195
+ * Unsubscribes all Rive listeners from an event type, or everything if no type is
2196
+ * given
2197
+ * @param type the type of event to unsubscribe from, or all types if
2198
+ * undefined
2199
+ */
2200
+ Rive.prototype.removeAllRiveEventListeners = function (type) {
2201
+ this.eventManager.removeAll(type);
2202
+ };
2203
+ /**
2204
+ * Unsubscribes all listeners from an event type, or everything if no type is
2205
+ * given
2206
+ * @deprecated
2207
+ * @param type the type of event to unsubscribe from, or all types if
2208
+ * undefined
2209
+ */
2210
+ Rive.prototype.unsubscribeAll = function (type) {
2211
+ console.warn("This function is deprecated: please use `removeAllRiveEventListeners()` instead.");
2212
+ this.removeAllRiveEventListeners(type);
2213
+ };
2214
+ /**
2215
+ * Stops the rendering loop; this is different from pausing in that it doesn't
2216
+ * change the state of any animation. It stops rendering from occurring. This
2217
+ * is designed for situations such as when Rive isn't visible.
2218
+ *
2219
+ * The only way to start rendering again is to call `startRendering`.
2220
+ * Animations that are marked as playing will start from the position that
2221
+ * they would have been at if rendering had not been stopped.
2222
+ */
2223
+ Rive.prototype.stopRendering = function () {
2224
+ if (this.loaded && this.frameRequestId) {
2225
+ if (this.runtime.cancelAnimationFrame) {
2226
+ this.runtime.cancelAnimationFrame(this.frameRequestId);
2227
+ }
2228
+ else {
2229
+ cancelAnimationFrame(this.frameRequestId);
2230
+ }
2231
+ this.frameRequestId = null;
2232
+ }
2233
+ };
2234
+ /**
2235
+ * Starts the rendering loop if it has been previously stopped. If the
2236
+ * renderer is already active, then this will have zero effect.
2237
+ */
2238
+ Rive.prototype.startRendering = function () {
2239
+ if (this.loaded && this.artboard && !this.frameRequestId) {
2240
+ if (this.runtime.requestAnimationFrame) {
2241
+ this.frameRequestId = this.runtime.requestAnimationFrame(this.draw.bind(this));
2242
+ }
2243
+ else {
2244
+ this.frameRequestId = requestAnimationFrame(this.draw.bind(this));
2245
+ }
2246
+ }
2247
+ };
2248
+ /**
2249
+ * Enables frames-per-second (FPS) reporting for the runtime
2250
+ * If no callback is provided, Rive will append a fixed-position div at the top-right corner of
2251
+ * the page with the FPS reading
2252
+ * @param fpsCallback - Callback from the runtime during the RAF loop that supplies the FPS value
2253
+ */
2254
+ Rive.prototype.enableFPSCounter = function (fpsCallback) {
2255
+ this.runtime.enableFPSCounter(fpsCallback);
2256
+ };
2257
+ /**
2258
+ * Disables frames-per-second (FPS) reporting for the runtime
2259
+ */
2260
+ Rive.prototype.disableFPSCounter = function () {
2261
+ this.runtime.disableFPSCounter();
2262
+ };
2263
+ Object.defineProperty(Rive.prototype, "contents", {
2264
+ /**
2265
+ * Returns the contents of a Rive file: the artboards, animations, and state machines
2266
+ */
2267
+ get: function () {
2268
+ if (!this.loaded) {
2269
+ return undefined;
2270
+ }
2271
+ var riveContents = {
2272
+ artboards: [],
2273
+ };
2274
+ for (var i = 0; i < this.file.artboardCount(); i++) {
2275
+ var artboard = this.file.artboardByIndex(i);
2276
+ var artboardContents = {
2277
+ name: artboard.name,
2278
+ animations: [],
2279
+ stateMachines: [],
2280
+ };
2281
+ for (var j = 0; j < artboard.animationCount(); j++) {
2282
+ var animation = artboard.animationByIndex(j);
2283
+ artboardContents.animations.push(animation.name);
2284
+ }
2285
+ for (var k = 0; k < artboard.stateMachineCount(); k++) {
2286
+ var stateMachine = artboard.stateMachineByIndex(k);
2287
+ var name_1 = stateMachine.name;
2288
+ var instance = new this.runtime.StateMachineInstance(stateMachine, artboard);
2289
+ var inputContents = [];
2290
+ for (var l = 0; l < instance.inputCount(); l++) {
2291
+ var input = instance.input(l);
2292
+ inputContents.push({ name: input.name, type: input.type });
2293
+ }
2294
+ artboardContents.stateMachines.push({
2295
+ name: name_1,
2296
+ inputs: inputContents,
2297
+ });
2298
+ }
2299
+ riveContents.artboards.push(artboardContents);
2300
+ }
2301
+ return riveContents;
2302
+ },
2303
+ enumerable: false,
2304
+ configurable: true
2305
+ });
2306
+ // Error message for missing source or buffer
2307
+ Rive.missingErrorMessage = "Rive source file or data buffer required";
2308
+ return Rive;
2309
+ }());
2310
+
2311
+ // Loads Rive data from a URI via fetch.
2312
+ var loadRiveFile = function (src) { return __awaiter(void 0, void 0, void 0, function () {
2313
+ var req, res, buffer;
2314
+ return __generator(this, function (_a) {
2315
+ switch (_a.label) {
2316
+ case 0:
2317
+ req = new Request(src);
2318
+ return [4 /*yield*/, fetch(req)];
2319
+ case 1:
2320
+ res = _a.sent();
2321
+ return [4 /*yield*/, res.arrayBuffer()];
2322
+ case 2:
2323
+ buffer = _a.sent();
2324
+ return [2 /*return*/, buffer];
2325
+ }
2326
+ });
2327
+ }); };
2328
+ // #endregion
2329
+ // #region utility functions
2330
+ /*
2331
+ * Utility function to ensure an object is a string array
2332
+ */
2333
+ var mapToStringArray = function (obj) {
2334
+ if (typeof obj === "string") {
2335
+ return [obj];
2336
+ }
2337
+ else if (obj instanceof Array) {
2338
+ return obj;
2339
+ }
2340
+ // If obj is undefined, return empty array
2341
+ return [];
2342
+ };
2343
+ // #endregion
2344
+ // #region testing utilities
2345
+ // Exports to only be used for tests
2346
+ var Testing = {
2347
+ EventManager: EventManager,
2348
+ TaskQueueManager: TaskQueueManager,
2349
+ };
2350
+ // #endregion
2351
+ // #region asset loaders
2352
+ var decodeImage = function (bytes) {
2353
+ return new Promise(function (resolve) {
2354
+ return RuntimeLoader.getInstance(function (rive) {
2355
+ rive.decodeImage(bytes, resolve);
2356
+ });
2357
+ });
2358
+ };
2359
+ var decodeFont = function (bytes) {
2360
+ return new Promise(function (resolve) {
2361
+ return RuntimeLoader.getInstance(function (rive) {
2362
+ rive.decodeFont(bytes, resolve);
2363
+ });
2364
+ });
2365
+ };
2366
+ // #endregion
2367
+
2368
+ })();
2369
+
2370
+ /******/ return __webpack_exports__;
2371
+ /******/ })()
2372
+ ;
2373
+ });
2374
+ //# sourceMappingURL=rive.js.map