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