@aarsteinmedia/dotlottie-player 2.1.6 → 2.1.8

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/dist/esm/index.js CHANGED
@@ -1,2 +1,1028 @@
1
- import{css as e,LitElement as t,html as r,nothing as o}from"lit";import{property as i,query as n,state as a,customElement as s}from"lit/decorators.js";import l from"lottie-web";import{zip as c,strFromU8 as d,unzip as p}from"fflate";!function(e){e.Completed="completed",e.Destroyed="destroyed",e.Error="error",e.Frozen="frozen",e.Loading="loading",e.Paused="paused",e.Playing="playing",e.Stopped="stopped"}(PlayerState||(PlayerState={})),function(e){e.Bounce="bounce",e.Normal="normal"}(PlayMode||(PlayMode={})),function(e){e.Complete="complete",e.Destroyed="destroyed",e.Error="error",e.Frame="frame",e.Freeze="freeze",e.Load="load",e.Loop="loop",e.Pause="pause",e.Play="play",e.Ready="ready",e.Rendered="rendered",e.Stop="stop"}(PlayerEvents||(PlayerEvents={}));class CustomError extends Error{}function asyncGeneratorStep$1(e,t,r,o,i,n,a){try{var s=e[n](a),l=s.value}catch(e){r(e);return}s.done?t(l):Promise.resolve(l).then(o,i)}function _async_to_generator$1(e){return function(){var t=this,r=arguments;return new Promise(function(o,i){var n=e.apply(t,r);function a(e){asyncGeneratorStep$1(n,o,i,a,s,"next",e)}function s(e){asyncGeneratorStep$1(n,o,i,a,s,"throw",e)}a(void 0)})}}let addExt=(e,t)=>{if(t)return getExt(t)?getExt(t)===e?t:`${getFilename(t)}.${e}`:`${t}.${e}`},aspectRatio=e=>{switch(e){case"contain":case"scale-down":default:return"xMidYMid meet";case"cover":return"xMidYMid slice";case"fill":return"none";case"none":return"xMinYMin slice"}},base64ToU8=e=>{let t=e.substring(e.indexOf(",")+1);return strToU8(isServer()?Buffer.from(t,"base64").toString("binary"):atob(t))},createDotLottie=function(){var e=_async_to_generator$1(function*(e,t,r,o=!0){try{var i;if(!(null==e?void 0:e.length)||!t)throw Error(`Missing or malformed required parameter(s):
2
- ${(null==e?void 0:e.length)?"":"- animations\n"} ${t?"":"- manifest \n"}`);let n=addExt("lottie",r)||`${useId()}.lottie`,a={"manifest.json":[strToU8(JSON.stringify(t)),{level:0}]};for(let[r,o]of e.entries()){if(null===(i=o.assets)||void 0===i?void 0:i.length)for(let e of o.assets){let{id:t,p:r}=e;if(t&&r){let o=getExtFromB64(r);e.p=`${t}.${o}`,e.e=0,a[`images/${t}.${o}`]=[base64ToU8(r),{level:9}]}}a[`animations/${t.animations[r].id}.json`]=[strToU8(JSON.stringify(o)),{level:9}]}let s=yield getArrayBuffer(a);return o?download(s,{name:n,mimeType:"application/zip"}):s}catch(e){console.error(`❌ ${handleErrors(e).message}`)}});return function(t,r,o){return e.apply(this,arguments)}}(),download=(e,t)=>{let r=new Blob([e],{type:null==t?void 0:t.mimeType}),o=(null==t?void 0:t.name)||useId(),i=URL.createObjectURL(r),n=document.createElement("a");n.href=i,n.download=o,n.hidden=!0,document.body.appendChild(n),n.click(),setTimeout(()=>{n.remove(),URL.revokeObjectURL(i)},1e3)},handleErrors=e=>{let t={message:"Unknown error",status:isServer()?500:400};return e&&"object"==typeof e&&("message"in e&&"string"==typeof e.message&&(t.message=e.message),"status"in e&&(t.status=Number(e.status))),t},frameOutput=e=>((null!=e?e:0)+1).toString().padStart(3,"0"),getAnimationData=function(){var e=_async_to_generator$1(function*(e){try{if(!e||"string"!=typeof e&&"object"!=typeof e)throw Error("Broken file or invalid file format");if("string"!=typeof e){let t=Array.isArray(e)?e:[e];return{animations:t,manifest:null}}let t=yield fetch(e);if(!t.ok){let e=new CustomError(t.statusText);throw e.status=t.status,e}let r=getExt(e);if("json"===r||!r){if(r){let e=yield t.json();return{animations:[e],manifest:null}}let e=yield t.clone().text();try{let t=JSON.parse(e);return{animations:[t],manifest:null}}catch(e){}}let{data:o,manifest:i}=yield getLottieJSON(t);return{animations:o,manifest:i,isDotLottie:!0}}catch(e){return console.error(`❌ ${handleErrors(e).message}`),{animations:null,manifest:null}}});return function(t){return e.apply(this,arguments)}}(),getArrayBuffer=function(){var e=_async_to_generator$1(function*(e){let t=yield new Promise((t,r)=>{c(e,{level:9},(e,o)=>{if(e){r(e);return}t(o.buffer)})});return t});return function(t){return e.apply(this,arguments)}}(),getExt=e=>{var t;if(e&&hasExt(e))return null===(t=e.split(".").pop())||void 0===t?void 0:t.toLowerCase()},getExtFromB64=e=>{let t=e.split(":")[1].split(";")[0];return t.split("/")[1].split("+")[0]},getFilename=(e,t)=>{let r=getExt(e);return`${e.replace(/\.[^.]*$/,"").replace(/\W+/g,"")}${t&&r?`.${r}`:""}`.toLowerCase()},getLottieJSON=function(){var e=_async_to_generator$1(function*(e){let t=yield unzip(e),r=getManifest(t),o=[];for(let{id:e}of r.animations){let r=d(t[`animations/${e}.json`]),i=JSON.parse(r);yield resolveAssets(t,i.assets),o.push(i)}return{data:o,manifest:r}});return function(t){return e.apply(this,arguments)}}(),getManifest=e=>{let t=d(e["manifest.json"],!1),r=JSON.parse(t);if(!("animations"in r))throw Error("Manifest not found");if(!r.animations.length)throw Error("No animations listed in manifest");return r},getMimeFromExt=e=>{switch(e){case"svg":case"svg+xml":return"image/svg+xml";case"jpg":case"jpeg":return"image/jpeg";case"png":case"gif":case"webp":return`image/${e}`;case"mp3":case"mpeg":case"wav":return`audio/${e}`;default:return""}},hasExt=e=>{var t;let r=null==e?void 0:null===(t=e.split("/").pop())||void 0===t?void 0:t.lastIndexOf(".");return(null!=r?r:0)>1&&e&&e.length-1>(null!=r?r:0)},isAudio=e=>!("h"in e)&&!("w"in e)&&"p"in e&&"e"in e&&"u"in e&&"id"in e,isImage=e=>"w"in e&&"h"in e&&!("xt"in e)&&"p"in e,isServer=()=>!("undefined"!=typeof window&&window.document),strToU8=e=>{let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t},resolveAssets=function(){var e=_async_to_generator$1(function*(e,t){if(!Array.isArray(t))return;let r=[];for(let o of t){if(!isAudio(o)&&!isImage(o))continue;let t=isImage(o)?"images":"audio",i=null==e?void 0:e[`${t}/${o.p}`];i&&r.push(new Promise(e=>{let t=isServer()?Buffer.from(i).toString("base64"):btoa(i.reduce((e,t)=>e+String.fromCharCode(t),""));o.p=`data:${getMimeFromExt(getExt(o.p))};base64,${t}`,o.e=1,o.u="",e()}))}yield Promise.all(r)});return function(t,r){return e.apply(this,arguments)}}(),unzip=function(){var e=_async_to_generator$1(function*(e){let t=new Uint8Array((yield e.arrayBuffer())),r=yield new Promise((e,r)=>{p(t,(t,o)=>{t&&r(t),e(o)})});return r});return function(t){return e.apply(this,arguments)}}(),useId=e=>{let t=()=>((1+Math.random())*65536|0).toString(16).substring(1);return`${null!=e?e:`:${t()}`}-${t()}`};var PlayerState,PlayMode,PlayerEvents,name="@aarsteinmedia/dotlottie-player",version="2.1.6",description="Web Component for playing Lottie animations in your web app. Previously @johanaarstein/dotlottie-player",exports={".":{import:"./dist/esm/index.js",node:"./dist/esm/index.js",require:"./dist/cjs/index.js",types:"./dist/index.d.ts"}},main="./dist/index.js",unpkg="./dist/index.js",module="./dist/esm/index.js",types="./dist/index.d.ts",type="module",homepage="https://www.aarstein.media/en/dotlottie-player",repository={url:"https://github.com/aarsteinmedia/dotlottie-player.git",type:"git"},bugs="https://github.com/aarsteinmedia/dotlottie-player/issues",author={name:"Johan Martin Aarstein",email:"johan@aarstein.media",url:"https://www.aarstein.media",organization:"Aarstein Media"},license="GPL-2.0-or-later",scripts={build:"pnpm cleanup && rollup -c","build:types":"pnpm cleanup:types && tsc","build:cem":"npx cem analyze --config 'cem.config.mjs'",prod:"pnpm build:types && pnpm build && pnpm build:cem",dev:"pnpm cleanup && rollup -c --watch",lint:"tsc && eslint . --ext .ts,.js","lint:fix":"eslint . --ext .ts,.js --fix","cleanup:types":"shx rm -rf types && shx mkdir types",cleanup:"shx rm -rf dist && shx mkdir dist"},dependencies={fflate:"^0.8.1",lit:"^2.8.0","lottie-web":"^5.12.2"},peerDependencies={"@types/react":"^18.2.28"},devDependencies={"@custom-elements-manifest/analyzer":"^0.6.9","@rollup/plugin-commonjs":"^25.0.7","@rollup/plugin-json":"^6.0.1","@rollup/plugin-node-resolve":"^15.2.3","@rollup/plugin-replace":"^5.0.4","@swc/core":"1.3.75","@types/node":"^20.8.8","@typescript-eslint/eslint-plugin":"^5.62.0","@typescript-eslint/parser":"^5.62.0",eslint:"^8.52.0",rollup:"^3.29.4","rollup-plugin-dts":"^6.1.0","rollup-plugin-html-literals":"^1.1.8","rollup-plugin-summary":"^2.0.0","rollup-plugin-swc3":"^0.9.1",shx:"^0.3.4","ts-lit-plugin":"^1.2.1",typescript:"^5.2.2"},customElements="dist/custom-elements.json",files=["dist","README.md"],keywords=["lottie","dotlottie","animation","web component","component","lit-element","svg","vector","player"],publishConfig={access:"public"},engines={node:">= 7.6.0"},funding={type:"paypal",url:"https://www.paypal.com/donate/?hosted_button_id=E7C7DMN8KSQ6A"},pkg={name:name,version:version,description:description,exports:exports,main:main,unpkg:unpkg,module:module,types:types,type:type,homepage:homepage,repository:repository,bugs:bugs,author:author,license:license,scripts:scripts,dependencies:dependencies,peerDependencies:peerDependencies,devDependencies:devDependencies,customElements:customElements,files:files,keywords:keywords,publishConfig:publishConfig,engines:engines,funding:funding},styles=e`*{box-sizing:border-box}:host{--lottie-player-toolbar-height:35px;--lottie-player-toolbar-background-color:#FFF;--lottie-player-toolbar-icon-color:#000;--lottie-player-toolbar-icon-hover-color:#000;--lottie-player-toolbar-icon-active-color:#4285f4;--lottie-player-seeker-track-color:rgba(0, 0, 0, 0.2);--lottie-player-seeker-thumb-color:#4285f4;--lottie-player-seeker-display:block;display:block;width:100%;height:100%}@media (prefers-color-scheme:dark){:host{--lottie-player-toolbar-background-color:#000;--lottie-player-toolbar-icon-color:#FFF;--lottie-player-toolbar-icon-hover-color:#FFF;--lottie-player-seeker-track-color:rgba(255, 255, 255, 0.6)}}.main{display:flex;flex-direction:column;height:100%;width:100%;margin:0}.animation{width:100%;height:100%;display:flex}[data-controls=true] .animation{height:calc(100% - 35px)}.animation-container{position:relative}.popover{position:absolute;right:5px;bottom:40px;background-color:var(--lottie-player-toolbar-background-color);border-radius:5px;padding:10px 15px;border:solid 2px var(--lottie-player-toolbar-icon-color);animation:fadeIn .2s ease-in-out}.popover::before{content:"";right:10px;border:7px solid transparent;border-top-color:transparent;margin-right:-7px;height:0;width:0;position:absolute;pointer-events:none;top:100%;border-top-color:var(--lottie-player-toolbar-icon-color)}.toolbar{display:flex;align-items:center;justify-items:center;background:var(--lottie-player-toolbar-background-color);margin:0;height:35px;padding:5px;border-radius:5px;gap:5px}.toolbar.has-error{pointer-events:none;opacity:.5}.toolbar button{cursor:pointer;fill:var(--lottie-player-toolbar-icon-color);color:var(--lottie-player-toolbar-icon-color);display:flex;background:0 0;border:0;padding:0;outline:0;height:100%;margin:0;align-items:center;gap:5px;opacity:.9}.toolbar button:hover{opacity:1}.toolbar button[data-active=true]{opacity:1;fill:var(--lottie-player-toolbar-icon-active-color)}.toolbar button:disabled{opacity:.5}.toolbar button:focus{outline:0}.toolbar button svg{pointer-events:none}.toolbar button svg>*{fill:inherit}.toolbar button.disabled svg{display:none}.progress-container{position:relative;width:100%}.progress-container.simple{margin-right:12px}.seeker,.seeker::-webkit-slider-runnable-track,.seeker::-webkit-slider-thumb,progress{-webkit-appearance:none;appearance:none;outline:0}.seeker{width:100%;height:20px;border-radius:3px;border:0;cursor:pointer;background-color:transparent;display:var(--lottie-player-seeker-display);color:var(--lottie-player-seeker-thumb-color);margin:0;padding:7.5px 0;position:relative;z-index:1}progress{position:absolute;width:100%;height:5px;border-radius:3px;border:0;top:0;left:0;margin:7.5px 0;background-color:var(--lottie-player-seeker-track-color);pointer-events:none}::-moz-progress-bar{background-color:var(--lottie-player-seeker-thumb-color)}::-webkit-progress-inner-element{border-radius:3px;overflow:hidden}::-webkit-slider-runnable-track{background-color:transparent}::-webkit-progress-value{background-color:var(--lottie-player-seeker-thumb-color)}.seeker::-webkit-slider-thumb{height:15px;width:15px;border-radius:50%;border:0;background-color:var(--lottie-player-seeker-thumb-color);cursor:pointer;transition:transform .2s ease-in-out;transform:scale(0)}.seeker:focus::-webkit-slider-thumb,.seeker:hover::-webkit-slider-thumb{transform:scale(1)}.seeker::-moz-range-progress{background-color:var(--lottie-player-seeker-thumb-color);height:5px;border-radius:3px}.seeker::-moz-range-thumb{height:15px;width:15px;border-radius:50%;background-color:var(--lottie-player-seeker-thumb-color);border:0;cursor:pointer;transition:transform .2s ease-in-out;transform:scale(0)}.seeker:focus::-moz-range-thumb,.seeker:hover::-moz-range-thumb{transform:scale(1)}.seeker::-ms-track{width:100%;height:5px;cursor:pointer;background:0 0;border-color:transparent;color:transparent}.seeker::-ms-fill-upper{background:var(--lottie-player-seeker-track-color);border-radius:3px}.seeker::-ms-fill-lower{background-color:var(--lottie-player-seeker-thumb-color);border-radius:3px}.seeker::-ms-thumb{border:0;height:15px;width:15px;border-radius:50%;background:var(--lottie-player-seeker-thumb-color);cursor:pointer;transition:transform .2s ease-in-out;transform:scale(0)}.seeker:focus::-ms-thumb,.seeker:hover::-ms-thumb{transform:scale(1)}.seeker:focus::-ms-fill-lower{background:var(--lottie-player-seeker-track-color)}.seeker:focus::-ms-fill-upper{background:var(--lottie-player-seeker-track-color)}.error{display:flex;margin:auto;justify-content:center;height:100%;align-items:center}.error svg{width:100%;height:auto}@keyframes fadeIn{0%{opacity:0}100%{opacity:1}}`;function asyncGeneratorStep(e,t,r,o,i,n,a){try{var s=e[n](a),l=s.value}catch(e){r(e);return}s.done?t(l):Promise.resolve(l).then(o,i)}function _async_to_generator(e){return function(){var t=this,r=arguments;return new Promise(function(o,i){var n=e.apply(t,r);function a(e){asyncGeneratorStep(n,o,i,a,s,"next",e)}function s(e){asyncGeneratorStep(n,o,i,a,s,"throw",e)}a(void 0)})}}function _define_property(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function _object_spread(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},o=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),o.forEach(function(t){_define_property(e,t,r[t])})}return e}function ownKeys(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,o)}return r}function _object_spread_props(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}),e}function _ts_decorate(e,t,r,o){for(var i,n=arguments.length,a=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o,s=e.length-1;s>=0;s--)(i=e[s])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}let DotLottiePlayer=class extends t{_getOptions(){var e;let t=null!==(e=this.preserveAspectRatio)&&void 0!==e?e:this.objectfit&&aspectRatio(this.objectfit),r=!this.segment||this.segment.some(e=>e<0)?void 0:this.segment.every(e=>e>0)?[this.segment[0]-1,this.segment[1]-1]:this.segment,o={container:this.container,loop:!!this.loop,autoplay:!!this.autoplay,renderer:this.renderer,initialSegment:r,rendererSettings:{imagePreserveAspectRatio:t}};switch(this.renderer){case"svg":o.rendererSettings=_object_spread_props(_object_spread({},o.rendererSettings),{hideOnTransparent:!0,preserveAspectRatio:t,progressiveLoad:!0});break;case"canvas":o.rendererSettings=_object_spread_props(_object_spread({},o.rendererSettings),{clearCanvas:!0,preserveAspectRatio:t,progressiveLoad:!0});break;case"html":o.rendererSettings=_object_spread_props(_object_spread({},o.rendererSettings),{hideOnTransparent:!0})}return o}load(e){var t=this;return _async_to_generator(function*(){var r;if(t.shadowRoot){try{let{animations:r,manifest:o,isDotLottie:i}=yield getAnimationData(e);if(!r||r.some(e=>!t._isLottie(e)))throw Error("Broken or corrupted file");t._isDotLottie=!!i,t._animations=r,t._manifest=null!=o?o:{animations:[{id:useId(),autoplay:t.autoplay,loop:t.loop,direction:t.direction,mode:t.mode,speed:t.speed}]},t._lottieInstance&&t._lottieInstance.destroy(),t._lottieInstance=l.loadAnimation(_object_spread_props(_object_spread({},t._getOptions()),{animationData:r[t._currentAnimation]}))}catch(e){t._errorMessage=handleErrors(e).message,t.currentState=PlayerState.Error,t.dispatchEvent(new CustomEvent(PlayerEvents.Error));return}t._addEventListeners(),t.setSpeed(t.speed),t.setDirection(null!==(r=t.direction)&&void 0!==r?r:1),t.setSubframe(!!t.subframe),t.autoplay&&(-1===t.direction&&t.seek("99%"),t.play())}})()}_addEventListeners(){this._lottieInstance&&(this._lottieInstance.addEventListener("enterFrame",()=>{if(this._lottieInstance){let{currentFrame:e,totalFrames:t}=this._lottieInstance;this._seeker=Math.floor(e/t*100),this.dispatchEvent(new CustomEvent(PlayerEvents.Frame,{detail:{frame:e,seeker:this._seeker}}))}}),this._lottieInstance.addEventListener("complete",()=>{var e,t;this.currentState=PlayerState.Completed,this.dispatchEvent(new CustomEvent(PlayerEvents.Complete)),(null===(e=this._animations)||void 0===e?void 0:e.length)>1&&this.autoplay&&this._currentAnimation<(null===(t=this._animations)||void 0===t?void 0:t.length)-1&&this.next()}),this._lottieInstance.addEventListener("loopComplete",()=>{var e,t,r;if(!this._lottieInstance)return;let{firstFrame:o,totalFrames:i,playDirection:n}=this._lottieInstance;if(this.count&&(this.mode===PlayMode.Bounce?this._playerState.count+=1:this._playerState.count+=.5,this._playerState.count>=this.count)){this.setLooping(!1),this.currentState=PlayerState.Completed,this.dispatchEvent(new CustomEvent(PlayerEvents.Complete));return}return(this.dispatchEvent(new CustomEvent(PlayerEvents.Loop)),this.mode===PlayMode.Bounce)?(null===(t=this._lottieInstance)||void 0===t||t.goToAndStop(-1===n?o:.99*i,!0),null===(r=this._lottieInstance)||void 0===r||r.setDirection(-1*n),setTimeout(()=>{var e;null===(e=this._lottieInstance)||void 0===e||e.play()},this.intermission)):(null===(e=this._lottieInstance)||void 0===e||e.goToAndStop(-1===n?.99*i:o,!0),setTimeout(()=>{var e;null===(e=this._lottieInstance)||void 0===e||e.play()},this.intermission))}),this._lottieInstance.addEventListener("DOMLoaded",()=>{this._playerState.loaded=!0,this.dispatchEvent(new CustomEvent(PlayerEvents.Ready))}),this._lottieInstance.addEventListener("data_ready",()=>{this.dispatchEvent(new CustomEvent(PlayerEvents.Load))}),this._lottieInstance.addEventListener("data_failed",()=>{this.currentState=PlayerState.Error,this.dispatchEvent(new CustomEvent(PlayerEvents.Error))}),this.container&&(this.container.addEventListener("mouseenter",()=>{this.hover&&this.currentState!==PlayerState.Playing&&this.play()}),this.container.addEventListener("mouseleave",()=>{this.hover&&this.currentState===PlayerState.Playing&&this.stop()})))}_onVisibilityChange(){document.hidden&&this.currentState===PlayerState.Playing?this._freeze():this.currentState===PlayerState.Frozen&&this.play()}_handleSeekChange({target:e}){!(!(e instanceof HTMLInputElement)||!this._lottieInstance||isNaN(Number(e.value)))&&(this.seek(Math.floor(Number(e.value)/100*this._lottieInstance.totalFrames)),setTimeout(()=>{e.parentElement instanceof HTMLFormElement&&e.parentElement.reset()},100))}_isLottie(e){return["v","ip","op","layers","fr","w","h"].every(t=>Object.prototype.hasOwnProperty.call(e,t))}addAnimation(e,t,r=!0){var o=this;return _async_to_generator(function*(){try{let i=o._manifest||{animations:[]},n=_object_spread_props(_object_spread({},i),{generator:pkg.name}),a=o._animations||[];for(let t of e){let{url:e}=t,{animations:r}=yield getAnimationData(e);if(!r)throw Error("No animation loaded");if(n.animations.some(({id:e})=>e===t.id))throw Error("Duplicate id for animation");n=_object_spread_props(_object_spread({},n),{animations:[...n.animations,t]}),a=[...a,...r]}return createDotLottie(a,n,t,r)}catch(e){console.error(handleErrors(e).message)}})()}getLottie(){return this._lottieInstance}play(){this._lottieInstance&&(this.currentState&&(this._playerState.prev=this.currentState),this._lottieInstance.play(),setTimeout(()=>{this.currentState=PlayerState.Playing},0),this.dispatchEvent(new CustomEvent(PlayerEvents.Play)))}pause(){this._lottieInstance&&(this.currentState&&(this._playerState.prev=this.currentState),this._lottieInstance.pause(),setTimeout(()=>{this.currentState=PlayerState.Paused},0),this.dispatchEvent(new CustomEvent(PlayerEvents.Pause)))}stop(){this._lottieInstance&&(this.currentState&&(this._playerState.prev=this.currentState),this._playerState.count=0,this._lottieInstance.stop(),setTimeout(()=>{this.currentState=PlayerState.Stopped},0),this.dispatchEvent(new CustomEvent(PlayerEvents.Stop)))}destroy(){this._lottieInstance&&(this.currentState=PlayerState.Destroyed,this._lottieInstance.destroy(),this._lottieInstance=null,this.dispatchEvent(new CustomEvent(PlayerEvents.Destroyed)),this.remove())}seek(e){if(!this._lottieInstance)return;let t=e.toString().match(/^([0-9]+)(%?)$/);if(!t)return;let r=Math.floor("%"===t[2]?this._lottieInstance.totalFrames*Number(t[1])/100:Number(t[1]));this._seeker=r,this.currentState===PlayerState.Playing||this.currentState===PlayerState.Frozen&&this._playerState.prev===PlayerState.Playing?(this._lottieInstance.goToAndPlay(r,!0),this.currentState=PlayerState.Playing):(this._lottieInstance.goToAndStop(r,!0),this._lottieInstance.pause())}snapshot(){if(!this.shadowRoot)return;let e=this.shadowRoot.querySelector(".animation svg"),t=e instanceof Node?new XMLSerializer().serializeToString(e):null;if(!t){console.error("Could not serialize data");return}return download(t,{name:`${getFilename(this.src)}-${frameOutput(this._seeker)}.svg`,mimeType:"image/svg+xml"}),t}setSubframe(e){this._lottieInstance&&(this.subframe=e,this._lottieInstance.setSubframe(e))}_freeze(){this._lottieInstance&&(this.currentState&&(this._playerState.prev=this.currentState),this._lottieInstance.pause(),setTimeout(()=>{this.currentState=PlayerState.Frozen},0),this.dispatchEvent(new CustomEvent(PlayerEvents.Freeze)))}reload(){var e=this;return _async_to_generator(function*(){e._lottieInstance&&(e._lottieInstance.destroy(),e.src&&(yield e.load(e.src)))})()}setSpeed(e=1){this._lottieInstance&&(this.speed=e,this._lottieInstance.setSpeed(e))}setDirection(e){this._lottieInstance&&(this.direction=e,this._lottieInstance.setDirection(e))}setLooping(e){this._lottieInstance&&(this.loop=e,this._lottieInstance.setLoop(e))}togglePlay(){if(!this._lottieInstance)return;let{currentFrame:e,playDirection:t,totalFrames:r}=this._lottieInstance;return this.currentState===PlayerState.Playing?this.pause():this.currentState===PlayerState.Completed?(this.currentState=PlayerState.Playing,this.mode===PlayMode.Bounce)?(this.setDirection(-1*t),this._lottieInstance.goToAndPlay(e,!0)):-1===t?this._lottieInstance.goToAndPlay(r,!0):this._lottieInstance.goToAndPlay(0,!0):this.play()}toggleLooping(){this.setLooping(!this.loop)}toggleBoomerang(){this.mode===PlayMode.Normal?this.mode=PlayMode.Bounce:this.mode=PlayMode.Normal}_toggleSettings(e){void 0===e?this._isSettingsOpen=!this._isSettingsOpen:this._isSettingsOpen=e}_switchInstance(){this._lottieInstance&&this._lottieInstance.destroy(),this._lottieInstance=l.loadAnimation(_object_spread_props(_object_spread({},this._getOptions()),{animationData:this._animations[this._currentAnimation]})),this._addEventListeners(),this.autoplay?(this._lottieInstance.goToAndPlay(0,!0),this.currentState=PlayerState.Playing):this._lottieInstance.goToAndStop(0,!0)}next(){this._currentAnimation++,this._switchInstance()}prev(){this._currentAnimation--,this._switchInstance()}convert(e,t,r,o,i=!0){if(e||this._isDotLottie)return;let n=t||this._manifest,a=_object_spread_props(_object_spread({},n),{generator:pkg.name});return createDotLottie(r||this._animations,a,`${getFilename(o||this.src)}.lottie`,i)}static get styles(){return styles}connectedCallback(){super.connectedCallback(),void 0!==document.hidden&&document.addEventListener("visibilitychange",this._onVisibilityChange)}firstUpdated(){var e=this;return _async_to_generator(function*(){"IntersectionObserver"in window&&(e._intersectionObserver=new IntersectionObserver(t=>{t[0].isIntersecting?document.hidden||e.currentState!==PlayerState.Frozen||e.play():e.currentState===PlayerState.Playing&&e._freeze()}),e._intersectionObserver.observe(e.container)),e.src&&(yield e.load(e.src)),e.dispatchEvent(new CustomEvent(PlayerEvents.Rendered))})()}disconnectedCallback(){super.disconnectedCallback(),this._intersectionObserver&&(this._intersectionObserver.disconnect(),this._intersectionObserver=void 0),this._lottieInstance&&this._lottieInstance.destroy(),document.removeEventListener("visibilitychange",this._onVisibilityChange)}renderControls(){var e,t;let i=this.currentState===PlayerState.Playing,n=this.currentState===PlayerState.Paused,a=this.currentState===PlayerState.Stopped,s=this.currentState===PlayerState.Error;return r`<div class="${`lottie-controls toolbar ${s?"has-error":""}`}" aria-label="Lottie Animation controls"><button @click="${this.togglePlay}" data-active="${i||n}" tabindex="0" aria-label="Toggle Play/Pause">${i?r`<svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M14.016 5.016H18v13.969h-3.984V5.016zM6 18.984V5.015h3.984v13.969H6z"/></svg>`:r`<svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M8.016 5.016L18.985 12 8.016 18.984V5.015z"/></svg>`}</button> <button @click="${this.stop}" data-active="${a}" tabindex="0" aria-label="Stop"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M6 6h12v12H6V6z"/></svg></button> ${(null===(e=this._animations)||void 0===e?void 0:e.length)>1?r`${this._currentAnimation>0?r`<button @click="${this.prev}" tabindex="0" aria-label="Previous animation"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M17.9 18.2 8.1 12l9.8-6.2v12.4zm-10.3 0H6.1V5.8h1.5v12.4z"/></svg></button>`:o} ${this._currentAnimation+1<(null===(t=this._animations)||void 0===t?void 0:t.length)?r`<button @click="${this.next}" tabindex="0" aria-label="Next animation"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="m6.1 5.8 9.8 6.2-9.8 6.2V5.8zM16.4 5.8h1.5v12.4h-1.5z"/></svg></button>`:o}`:o}<form class="progress-container${this.simple?" simple":""}"><input class="seeker" type="range" min="0" max="100" step="1" value="${this._seeker}" @change="${this._handleSeekChange}" @mousedown="${this._freeze}" aria-valuemin="0" aria-valuemax="100" role="slider" aria-valuenow="${this._seeker}" tabindex="0" aria-label="Slider for search"><progress min="0" max="100" value="${this._seeker}"></progress></form>${this.simple?o:r`<button @click="${this.toggleLooping}" data-active="${this.loop}" tabindex="0" aria-label="Toggle looping"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M17.016 17.016v-4.031h1.969v6h-12v3l-3.984-3.984 3.984-3.984v3h10.031zM6.984 6.984v4.031H5.015v-6h12v-3l3.984 3.984-3.984 3.984v-3H6.984z"/></svg></button> <button @click="${this.toggleBoomerang}" data-active="${this.mode===PlayMode.Bounce}" aria-label="Toggle boomerang" tabindex="0"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="m11.8 13.2-.3.3c-.5.5-1.1 1.1-1.7 1.5-.5.4-1 .6-1.5.8-.5.2-1.1.3-1.6.3s-1-.1-1.5-.3c-.6-.2-1-.5-1.4-1-.5-.6-.8-1.2-.9-1.9-.2-.9-.1-1.8.3-2.6.3-.7.8-1.2 1.3-1.6.3-.2.6-.4 1-.5.2-.2.5-.2.8-.3.3 0 .7-.1 1 0 .3 0 .6.1.9.2.9.3 1.7.9 2.4 1.5.4.4.8.7 1.1 1.1l.1.1.4-.4c.6-.6 1.2-1.2 1.9-1.6.5-.3 1-.6 1.5-.7.4-.1.7-.2 1-.2h.9c1 .1 1.9.5 2.6 1.4.4.5.7 1.1.8 1.8.2.9.1 1.7-.2 2.5-.4.9-1 1.5-1.8 2-.4.2-.7.4-1.1.4-.4.1-.8.1-1.2.1-.5 0-.9-.1-1.3-.3-.8-.3-1.5-.9-2.1-1.5-.4-.4-.8-.7-1.1-1.1h-.3zm-1.1-1.1c-.1-.1-.1-.1 0 0-.3-.3-.6-.6-.8-.9-.5-.5-1-.9-1.6-1.2-.4-.3-.8-.4-1.3-.4-.4 0-.8 0-1.1.2-.5.2-.9.6-1.1 1-.2.3-.3.7-.3 1.1 0 .3 0 .6.1.9.1.5.4.9.8 1.2.5.4 1.1.5 1.7.5.5 0 1-.2 1.5-.5.6-.4 1.1-.8 1.6-1.3.1-.3.3-.5.5-.6zM13 12c.5.5 1 1 1.5 1.4.5.5 1.1.9 1.9 1 .4.1.8 0 1.2-.1.3-.1.6-.3.9-.5.4-.4.7-.9.8-1.4.1-.5 0-.9-.1-1.4-.3-.8-.8-1.2-1.7-1.4-.4-.1-.8-.1-1.2 0-.5.1-1 .4-1.4.7-.5.4-1 .8-1.4 1.2-.2.2-.4.3-.5.5z"/></svg></button> <button @click="${({target:e})=>{this._toggleSettings(),e instanceof HTMLElement&&e.focus()}}" @blur="${()=>setTimeout(()=>this._toggleSettings(!1),200)}" aria-label="Settings" aria-haspopup="true" aria-expanded="${!!this._isSettingsOpen}" aria-controls="${`${this._identifier}-settings`}"><svg width="24" height="24" aria-hidden="true" focusable="false"><circle cx="12" cy="5.4" r="2.5"/><circle cx="12" cy="12" r="2.5"/><circle cx="12" cy="18.6" r="2.5"/></svg></button><div id="${`${this._identifier}-settings`}" class="popover" style="display:${this._isSettingsOpen?"block":"none"}">${this._isDotLottie?o:r`<button @click="${this.convert}" aria-label="Convert JSON animation to dotLottie format" tabindex="0"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M17.016 17.016v-4.031h1.969v6h-12v3l-3.984-3.984 3.984-3.984v3h10.031zM6.984 6.984v4.031H5.015v-6h12v-3l3.984 3.984-3.984 3.984v-3H6.984z"/></svg> Convert to dotLottie</button>`} <button @click="${this.snapshot}" aria-label="Download still image" tabindex="0"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M16.8 10.8 12 15.6l-4.8-4.8h3V3.6h3.6v7.2h3zM12 15.6H3v4.8h18v-4.8h-9zm7.8 2.4h-2.4v-1.2h2.4V18z"/></svg> Download still image</button></div>`}</div>`}render(){var e,t,i;return r`<figure class="${"animation-container main"}" data-controls="${this.controls}" lang="${this.description?null===(t=document)||void 0===t?void 0:null===(e=t.documentElement)||void 0===e?void 0:e.lang:"en"}" role="img" aria-label="${null!==(i=this.description)&&void 0!==i?i:"Lottie animation"}" data-loaded="${this._playerState.loaded}"><div class="animation" style="background:${this.background}">${this.currentState===PlayerState.Error?r`<div class="error"><svg preserveAspectRatio="xMidYMid slice" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="1920" height="1080" viewBox="0 0 1920 1080"><path fill="#fff" d="M0 0h1920v1080H0z"/><path fill="#3a6d8b" d="M1190.2 531 1007 212.4c-22-38.2-77.2-38-98.8.5L729.5 531.3c-21.3 37.9 6.1 84.6 49.5 84.6l361.9.3c43.7 0 71.1-47.3 49.3-85.2zM937.3 288.7c.2-7.5 3.3-23.9 23.2-23.9 16.3 0 23 16.1 23 23.5 0 55.3-10.7 197.2-12.2 214.5-.1 1-.9 1.7-1.9 1.7h-18.3c-1 0-1.8-.7-1.9-1.7-1.4-17.5-13.4-162.9-11.9-214.1zm24.2 283.8c-13.1 0-23.7-10.6-23.7-23.7s10.6-23.7 23.7-23.7 23.7 10.6 23.7 23.7-10.6 23.7-23.7 23.7zM722.1 644h112.6v34.4h-70.4V698h58.8v31.7h-58.8v22.6h72.4v36.2H722.1V644zm162 57.1h.6c8.3-12.9 18.2-17.8 31.3-17.8 3 0 5.1.4 6.3 1v32.6h-.8c-22.4-3.8-35.6 6.3-35.6 29.5v42.3h-38.2V685.5h36.4v15.6zm78.9 0h.6c8.3-12.9 18.2-17.8 31.3-17.8 3 0 5.1.4 6.3 1v32.6h-.8c-22.4-3.8-35.6 6.3-35.6 29.5v42.3h-38.2V685.5H963v15.6zm39.5 36.2c0-31.3 22.2-54.8 56.6-54.8 34.4 0 56.2 23.5 56.2 54.8s-21.8 54.6-56.2 54.6c-34.4-.1-56.6-23.3-56.6-54.6zm74 0c0-17.4-6.1-29.1-17.8-29.1-11.7 0-17.4 11.7-17.4 29.1 0 17.4 5.7 29.1 17.4 29.1s17.8-11.8 17.8-29.1zm83.1-36.2h.6c8.3-12.9 18.2-17.8 31.3-17.8 3 0 5.1.4 6.3 1v32.6h-.8c-22.4-3.8-35.6 6.3-35.6 29.5v42.3h-38.2V685.5h36.4v15.6z"/><path fill="none" d="M718.9 807.7h645v285.4h-645z"/><text fill="#3a6d8b" style="text-align:center;position:absolute;left:100%;font-size:47px;font-family:system-ui,-apple-system,BlinkMacSystemFont,'.SFNSText-Regular',sans-serif" x="50%" y="848.017" text-anchor="middle">${this._errorMessage}</text></svg></div>`:o}</div>${this.controls?this.renderControls():o}</figure>`}constructor(...e){super(...e),this.background="transparent",this.controls=!1,this.currentState=PlayerState.Loading,this.direction=1,this.hover=!1,this.intermission=0,this.loop=!1,this.mode=PlayMode.Normal,this.objectfit="contain",this.renderer="svg",this.simple=!1,this.speed=1,this.subframe=!0,this._isSettingsOpen=!1,this._seeker=0,this._currentAnimation=0,this._lottieInstance=null,this._identifier=this.id||useId("dotlottie"),this._errorMessage="Something went wrong",this._isDotLottie=!1,this._playerState={prev:PlayerState.Loading,count:0,loaded:!1}}};_ts_decorate([i({type:Boolean,reflect:!0})],DotLottiePlayer.prototype,"autoplay",void 0),_ts_decorate([i({type:String})],DotLottiePlayer.prototype,"background",void 0),_ts_decorate([i({type:Boolean,reflect:!0})],DotLottiePlayer.prototype,"controls",void 0),_ts_decorate([i({type:Number})],DotLottiePlayer.prototype,"count",void 0),_ts_decorate([i({type:String})],DotLottiePlayer.prototype,"currentState",void 0),_ts_decorate([i({type:String})],DotLottiePlayer.prototype,"description",void 0),_ts_decorate([i({type:Number})],DotLottiePlayer.prototype,"direction",void 0),_ts_decorate([i({type:Boolean})],DotLottiePlayer.prototype,"hover",void 0),_ts_decorate([i({type:Number})],DotLottiePlayer.prototype,"intermission",void 0),_ts_decorate([i({type:Boolean,reflect:!0})],DotLottiePlayer.prototype,"loop",void 0),_ts_decorate([i({type:String})],DotLottiePlayer.prototype,"mode",void 0),_ts_decorate([i({type:String})],DotLottiePlayer.prototype,"objectfit",void 0),_ts_decorate([i({type:String})],DotLottiePlayer.prototype,"preserveAspectRatio",void 0),_ts_decorate([i({type:String})],DotLottiePlayer.prototype,"renderer",void 0),_ts_decorate([i({type:Array})],DotLottiePlayer.prototype,"segment",void 0),_ts_decorate([i({type:Boolean})],DotLottiePlayer.prototype,"simple",void 0),_ts_decorate([i({type:Number})],DotLottiePlayer.prototype,"speed",void 0),_ts_decorate([i({type:String})],DotLottiePlayer.prototype,"src",void 0),_ts_decorate([i({type:Boolean})],DotLottiePlayer.prototype,"subframe",void 0),_ts_decorate([n(".animation")],DotLottiePlayer.prototype,"container",void 0),_ts_decorate([a()],DotLottiePlayer.prototype,"_isSettingsOpen",void 0),_ts_decorate([a()],DotLottiePlayer.prototype,"_seeker",void 0),_ts_decorate([a()],DotLottiePlayer.prototype,"_currentAnimation",void 0),_ts_decorate([a()],DotLottiePlayer.prototype,"_animations",void 0),DotLottiePlayer=_ts_decorate([s("dotlottie-player")],DotLottiePlayer),globalThis.dotLottiePlayer=()=>new DotLottiePlayer;export{DotLottiePlayer,PlayMode,PlayerEvents,PlayerState};
1
+ import { css, LitElement, html, nothing } from 'lit';
2
+ import { property, query, state, customElement } from 'lit/decorators.js';
3
+ import Lottie from 'lottie-web';
4
+ import { zip, strFromU8, unzip as unzip$1 } from 'fflate';
5
+
6
+ var PlayerState;
7
+ (function(PlayerState) {
8
+ PlayerState["Completed"] = "completed";
9
+ PlayerState["Destroyed"] = "destroyed";
10
+ PlayerState["Error"] = "error";
11
+ PlayerState["Frozen"] = "frozen";
12
+ PlayerState["Loading"] = "loading";
13
+ PlayerState["Paused"] = "paused";
14
+ PlayerState["Playing"] = "playing";
15
+ PlayerState["Stopped"] = "stopped";
16
+ })(PlayerState || (PlayerState = {}));
17
+ var PlayMode;
18
+ (function(PlayMode) {
19
+ PlayMode["Bounce"] = "bounce";
20
+ PlayMode["Normal"] = "normal";
21
+ })(PlayMode || (PlayMode = {}));
22
+ var PlayerEvents;
23
+ (function(PlayerEvents) {
24
+ PlayerEvents["Complete"] = "complete";
25
+ PlayerEvents["Destroyed"] = "destroyed";
26
+ PlayerEvents["Error"] = "error";
27
+ PlayerEvents["Frame"] = "frame";
28
+ PlayerEvents["Freeze"] = "freeze";
29
+ PlayerEvents["Load"] = "load";
30
+ PlayerEvents["Loop"] = "loop";
31
+ PlayerEvents["Pause"] = "pause";
32
+ PlayerEvents["Play"] = "play";
33
+ PlayerEvents["Ready"] = "ready";
34
+ PlayerEvents["Rendered"] = "rendered";
35
+ PlayerEvents["Stop"] = "stop";
36
+ })(PlayerEvents || (PlayerEvents = {}));
37
+ class CustomError extends Error {
38
+ }
39
+
40
+ const addExt = (ext, str)=>{
41
+ if (!str) return;
42
+ if (getExt(str)) {
43
+ if (getExt(str) === ext) return str;
44
+ return `${getFilename(str)}.${ext}`;
45
+ }
46
+ return `${str}.${ext}`;
47
+ }, aspectRatio = (objectFit)=>{
48
+ switch(objectFit){
49
+ case 'contain':
50
+ case 'scale-down':
51
+ return 'xMidYMid meet';
52
+ case 'cover':
53
+ return 'xMidYMid slice';
54
+ case 'fill':
55
+ return 'none';
56
+ case 'none':
57
+ return 'xMinYMin slice';
58
+ default:
59
+ return 'xMidYMid meet';
60
+ }
61
+ }, base64ToU8 = (str)=>{
62
+ const parsedStr = str.substring(str.indexOf(',') + 1);
63
+ return strToU8(isServer() ? Buffer.from(parsedStr, 'base64').toString('binary') : atob(parsedStr));
64
+ }, createDotLottie = async (animations, manifest, filename, triggerDownload = true)=>{
65
+ try {
66
+ if (!animations?.length || !manifest) {
67
+ throw new Error(`Missing or malformed required parameter(s):\n ${!animations?.length ? '- animations\n' : ''} ${!manifest ? '- manifest \n' : ''}`);
68
+ }
69
+ const name = addExt('lottie', filename) || `${useId()}.lottie`, dotlottie = {
70
+ 'manifest.json': [
71
+ strToU8(JSON.stringify(manifest)),
72
+ {
73
+ level: 0
74
+ }
75
+ ]
76
+ };
77
+ for (const [i, animation] of animations.entries()){
78
+ if (animation.assets?.length) {
79
+ for (const asset of animation.assets){
80
+ const { id, p } = asset;
81
+ if (id && p) {
82
+ const ext = getExtFromB64(p);
83
+ asset.p = `${id}.${ext}`;
84
+ asset.e = 0;
85
+ dotlottie[`images/${id}.${ext}`] = [
86
+ base64ToU8(p),
87
+ {
88
+ level: 9
89
+ }
90
+ ];
91
+ }
92
+ }
93
+ }
94
+ dotlottie[`animations/${manifest.animations[i].id}.json`] = [
95
+ strToU8(JSON.stringify(animation)),
96
+ {
97
+ level: 9
98
+ }
99
+ ];
100
+ }
101
+ const buffer = await getArrayBuffer(dotlottie);
102
+ return triggerDownload ? download(buffer, {
103
+ name,
104
+ mimeType: 'application/zip'
105
+ }) : buffer;
106
+ } catch (err) {
107
+ console.error(`❌ ${handleErrors(err).message}`);
108
+ }
109
+ }, download = (data, options)=>{
110
+ const blob = new Blob([
111
+ data
112
+ ], {
113
+ type: options?.mimeType
114
+ }), fileName = options?.name || useId(), dataURL = URL.createObjectURL(blob), link = document.createElement('a');
115
+ link.href = dataURL;
116
+ link.download = fileName;
117
+ link.hidden = true;
118
+ document.body.appendChild(link);
119
+ link.click();
120
+ setTimeout(()=>{
121
+ link.remove();
122
+ URL.revokeObjectURL(dataURL);
123
+ }, 1000);
124
+ }, handleErrors = (err)=>{
125
+ const res = {
126
+ message: 'Unknown error',
127
+ status: isServer() ? 500 : 400
128
+ };
129
+ if (err && typeof err === 'object') {
130
+ if ('message' in err && typeof err.message === 'string') {
131
+ res.message = err.message;
132
+ }
133
+ if ('status' in err) {
134
+ res.status = Number(err.status);
135
+ }
136
+ }
137
+ return res;
138
+ }, frameOutput = (frame)=>{
139
+ return ((frame ?? 0) + 1).toString().padStart(3, '0');
140
+ }, getAnimationData = async (input)=>{
141
+ try {
142
+ if (!input || typeof input !== 'string' && typeof input !== 'object') {
143
+ throw new Error('Broken file or invalid file format');
144
+ }
145
+ if (typeof input !== 'string') {
146
+ const animations = Array.isArray(input) ? input : [
147
+ input
148
+ ];
149
+ return {
150
+ animations,
151
+ manifest: null
152
+ };
153
+ }
154
+ const result = await fetch(input);
155
+ if (!result.ok) {
156
+ const error = new CustomError(result.statusText);
157
+ error.status = result.status;
158
+ throw error;
159
+ }
160
+ const ext = getExt(input);
161
+ if (ext === 'json' || !ext) {
162
+ if (ext) {
163
+ const lottie = await result.json();
164
+ return {
165
+ animations: [
166
+ lottie
167
+ ],
168
+ manifest: null
169
+ };
170
+ }
171
+ const text = await result.clone().text();
172
+ try {
173
+ const lottie = JSON.parse(text);
174
+ return {
175
+ animations: [
176
+ lottie
177
+ ],
178
+ manifest: null
179
+ };
180
+ } catch {}
181
+ }
182
+ const { data, manifest } = await getLottieJSON(result);
183
+ return {
184
+ animations: data,
185
+ manifest,
186
+ isDotLottie: true
187
+ };
188
+ } catch (err) {
189
+ console.error(`❌ ${handleErrors(err).message}`);
190
+ return {
191
+ animations: null,
192
+ manifest: null
193
+ };
194
+ }
195
+ }, getArrayBuffer = async (zippable)=>{
196
+ const arrayBuffer = await new Promise((resolve, reject)=>{
197
+ zip(zippable, {
198
+ level: 9
199
+ }, (err, data)=>{
200
+ if (err) {
201
+ reject(err);
202
+ return;
203
+ }
204
+ resolve(data.buffer);
205
+ });
206
+ });
207
+ return arrayBuffer;
208
+ }, getExt = (str)=>{
209
+ if (!str || !hasExt(str)) return;
210
+ return str.split('.').pop()?.toLowerCase();
211
+ }, getExtFromB64 = (str)=>{
212
+ const mime = str.split(':')[1].split(';')[0];
213
+ return mime.split('/')[1].split('+')[0];
214
+ }, getFilename = (src, keepExt)=>{
215
+ const ext = getExt(src);
216
+ return `${src.replace(/\.[^.]*$/, '').replace(/\W+/g, '')}${keepExt && ext ? `.${ext}` : ''}`.toLowerCase();
217
+ }, getLottieJSON = async (resp)=>{
218
+ const unzipped = await unzip(resp), manifest = getManifest(unzipped), data = [];
219
+ for (const { id } of manifest.animations){
220
+ const str = strFromU8(unzipped[`animations/${id}.json`]), lottie = JSON.parse(str);
221
+ await resolveAssets(unzipped, lottie.assets);
222
+ data.push(lottie);
223
+ }
224
+ return {
225
+ data,
226
+ manifest
227
+ };
228
+ }, getManifest = (unzipped)=>{
229
+ const file = strFromU8(unzipped['manifest.json'], false), manifest = JSON.parse(file);
230
+ if (!('animations' in manifest)) throw new Error('Manifest not found');
231
+ if (!manifest.animations.length) throw new Error('No animations listed in manifest');
232
+ return manifest;
233
+ }, getMimeFromExt = (ext)=>{
234
+ switch(ext){
235
+ case 'svg':
236
+ case 'svg+xml':
237
+ return 'image/svg+xml';
238
+ case 'jpg':
239
+ case 'jpeg':
240
+ return 'image/jpeg';
241
+ case 'png':
242
+ case 'gif':
243
+ case 'webp':
244
+ return `image/${ext}`;
245
+ case 'mp3':
246
+ case 'mpeg':
247
+ case 'wav':
248
+ return `audio/${ext}`;
249
+ default:
250
+ return '';
251
+ }
252
+ }, hasExt = (path)=>{
253
+ const lastDotIndex = path?.split('/').pop()?.lastIndexOf('.');
254
+ return (lastDotIndex ?? 0) > 1 && path && path.length - 1 > (lastDotIndex ?? 0);
255
+ }, isAudio = (asset)=>{
256
+ return !('h' in asset) && !('w' in asset) && 'p' in asset && 'e' in asset && 'u' in asset && 'id' in asset;
257
+ }, isImage = (asset)=>{
258
+ return 'w' in asset && 'h' in asset && !('xt' in asset) && 'p' in asset;
259
+ }, isServer = ()=>{
260
+ return !(typeof window !== 'undefined' && window.document);
261
+ }, strToU8 = (str)=>{
262
+ const u8 = new Uint8Array(str.length);
263
+ for(let i = 0; i < str.length; i++){
264
+ u8[i] = str.charCodeAt(i);
265
+ }
266
+ return u8;
267
+ }, resolveAssets = async (unzipped, assets)=>{
268
+ if (!Array.isArray(assets)) return;
269
+ const toResolve = [];
270
+ for (const asset of assets){
271
+ if (!isAudio(asset) && !isImage(asset)) continue;
272
+ const type = isImage(asset) ? 'images' : 'audio', u8 = unzipped?.[`${type}/${asset.p}`];
273
+ if (!u8) continue;
274
+ toResolve.push(new Promise((resolveAsset)=>{
275
+ const assetB64 = isServer() ? Buffer.from(u8).toString('base64') : btoa(u8.reduce((dat, byte)=>dat + String.fromCharCode(byte), ''));
276
+ asset.p = `data:${getMimeFromExt(getExt(asset.p))};base64,${assetB64}`;
277
+ asset.e = 1;
278
+ asset.u = '';
279
+ resolveAsset();
280
+ }));
281
+ }
282
+ await Promise.all(toResolve);
283
+ }, unzip = async (resp)=>{
284
+ const u8 = new Uint8Array(await resp.arrayBuffer()), unzipped = await new Promise((resolve, reject)=>{
285
+ unzip$1(u8, (err, file)=>{
286
+ if (err) {
287
+ reject(err);
288
+ }
289
+ resolve(file);
290
+ });
291
+ });
292
+ return unzipped;
293
+ }, useId = (prefix)=>{
294
+ const s4 = ()=>{
295
+ return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
296
+ };
297
+ return `${prefix ?? `:${s4()}`}-${s4()}`;
298
+ };
299
+
300
+ var name = "@aarsteinmedia/dotlottie-player";
301
+ var version = "2.1.8";
302
+ var description = "Web Component for playing Lottie animations in your web app. Previously @johanaarstein/dotlottie-player";
303
+ var exports = {
304
+ ".": {
305
+ "import": "./dist/esm/index.js",
306
+ node: "./dist/esm/index.js",
307
+ require: "./dist/cjs/index.js",
308
+ types: "./dist/index.d.ts"
309
+ }
310
+ };
311
+ var main = "./dist/esm/index.js";
312
+ var unpkg = "./dist/index.js";
313
+ var module = "./dist/esm/index.js";
314
+ var types = "./dist/index.d.ts";
315
+ var type = "module";
316
+ var homepage = "https://www.aarstein.media/en/dotlottie-player";
317
+ var repository = {
318
+ url: "https://github.com/aarsteinmedia/dotlottie-player.git",
319
+ type: "git"
320
+ };
321
+ var bugs = "https://github.com/aarsteinmedia/dotlottie-player/issues";
322
+ var author = {
323
+ name: "Johan Martin Aarstein",
324
+ email: "johan@aarstein.media",
325
+ url: "https://www.aarstein.media",
326
+ organization: "Aarstein Media"
327
+ };
328
+ var license = "GPL-2.0-or-later";
329
+ var scripts = {
330
+ build: "pnpm cleanup && rollup -c",
331
+ "build:types": "pnpm cleanup:types && tsc",
332
+ "build:cem": "npx cem analyze --config 'cem.config.mjs'",
333
+ prod: "pnpm build:types && pnpm build && pnpm build:cem",
334
+ dev: "pnpm cleanup && rollup -c --watch",
335
+ lint: "tsc && eslint . --ext .ts,.js",
336
+ "lint:fix": "eslint . --ext .ts,.js --fix",
337
+ "cleanup:types": "shx rm -rf types && shx mkdir types",
338
+ cleanup: "shx rm -rf dist && shx mkdir dist"
339
+ };
340
+ var dependencies = {
341
+ fflate: "^0.8.1",
342
+ lit: "^2.8.0",
343
+ "lottie-web": "^5.12.2"
344
+ };
345
+ var peerDependencies = {
346
+ "@types/react": ">= 16.0.0"
347
+ };
348
+ var devDependencies = {
349
+ "@custom-elements-manifest/analyzer": "^0.6.9",
350
+ "@rollup/plugin-commonjs": "^25.0.7",
351
+ "@rollup/plugin-json": "^6.0.1",
352
+ "@rollup/plugin-node-resolve": "^15.2.3",
353
+ "@rollup/plugin-replace": "^5.0.5",
354
+ "@swc/core": "^1.3.99",
355
+ "@types/node": "^20.10.0",
356
+ "@typescript-eslint/eslint-plugin": "^5.62.0",
357
+ "@typescript-eslint/parser": "^5.62.0",
358
+ eslint: "^8.54.0",
359
+ "eslint-plugin-lit": "^1.10.1",
360
+ rollup: "^3.29.4",
361
+ "rollup-plugin-dts": "^6.1.0",
362
+ "rollup-plugin-html-literals": "^1.1.8",
363
+ "rollup-plugin-summary": "^2.0.0",
364
+ "rollup-plugin-swc3": "^0.9.1",
365
+ shx: "^0.3.4",
366
+ "ts-lit-plugin": "^1.2.1",
367
+ typescript: "^5.3.2"
368
+ };
369
+ var customElements = "dist/custom-elements.json";
370
+ var files = [
371
+ "dist",
372
+ "README.md"
373
+ ];
374
+ var keywords = [
375
+ "lottie",
376
+ "dotlottie",
377
+ "animation",
378
+ "web component",
379
+ "component",
380
+ "lit-element",
381
+ "svg",
382
+ "vector",
383
+ "player"
384
+ ];
385
+ var publishConfig = {
386
+ access: "public"
387
+ };
388
+ var engines = {
389
+ node: ">= 7.6.0"
390
+ };
391
+ var funding = {
392
+ type: "paypal",
393
+ url: "https://www.paypal.com/donate/?hosted_button_id=E7C7DMN8KSQ6A"
394
+ };
395
+ var pkg = {
396
+ name: name,
397
+ version: version,
398
+ description: description,
399
+ exports: exports,
400
+ main: main,
401
+ unpkg: unpkg,
402
+ module: module,
403
+ types: types,
404
+ type: type,
405
+ homepage: homepage,
406
+ repository: repository,
407
+ bugs: bugs,
408
+ author: author,
409
+ license: license,
410
+ scripts: scripts,
411
+ dependencies: dependencies,
412
+ peerDependencies: peerDependencies,
413
+ devDependencies: devDependencies,
414
+ customElements: customElements,
415
+ files: files,
416
+ keywords: keywords,
417
+ publishConfig: publishConfig,
418
+ engines: engines,
419
+ funding: funding
420
+ };
421
+
422
+ var styles = css`*{box-sizing:border-box}:host{--lottie-player-toolbar-height:35px;--lottie-player-toolbar-background-color:#FFF;--lottie-player-toolbar-icon-color:#000;--lottie-player-toolbar-icon-hover-color:#000;--lottie-player-toolbar-icon-active-color:#4285f4;--lottie-player-seeker-track-color:rgba(0, 0, 0, 0.2);--lottie-player-seeker-thumb-color:#4285f4;--lottie-player-seeker-display:block;display:block;width:100%;height:100%}@media (prefers-color-scheme:dark){:host{--lottie-player-toolbar-background-color:#000;--lottie-player-toolbar-icon-color:#FFF;--lottie-player-toolbar-icon-hover-color:#FFF;--lottie-player-seeker-track-color:rgba(255, 255, 255, 0.6)}}.main{display:flex;flex-direction:column;height:100%;width:100%;margin:0}.animation{width:100%;height:100%;display:flex}[data-controls=true] .animation{height:calc(100% - 35px)}.animation-container{position:relative}.popover{position:absolute;right:5px;bottom:40px;background-color:var(--lottie-player-toolbar-background-color);border-radius:5px;padding:10px 15px;border:solid 2px var(--lottie-player-toolbar-icon-color);animation:fadeIn .2s ease-in-out}.popover::before{content:"";right:10px;border:7px solid transparent;border-top-color:transparent;margin-right:-7px;height:0;width:0;position:absolute;pointer-events:none;top:100%;border-top-color:var(--lottie-player-toolbar-icon-color)}.toolbar{display:flex;align-items:center;justify-items:center;background:var(--lottie-player-toolbar-background-color);margin:0;height:35px;padding:5px;border-radius:5px;gap:5px}.toolbar.has-error{pointer-events:none;opacity:.5}.toolbar button{cursor:pointer;fill:var(--lottie-player-toolbar-icon-color);color:var(--lottie-player-toolbar-icon-color);display:flex;background:0 0;border:0;padding:0;outline:0;height:100%;margin:0;align-items:center;gap:5px;opacity:.9}.toolbar button:hover{opacity:1}.toolbar button[data-active=true]{opacity:1;fill:var(--lottie-player-toolbar-icon-active-color)}.toolbar button:disabled{opacity:.5}.toolbar button:focus{outline:0}.toolbar button svg{pointer-events:none}.toolbar button svg>*{fill:inherit}.toolbar button.disabled svg{display:none}.progress-container{position:relative;width:100%}.progress-container.simple{margin-right:12px}.seeker,.seeker::-webkit-slider-runnable-track,.seeker::-webkit-slider-thumb,progress{-webkit-appearance:none;appearance:none;outline:0}.seeker{width:100%;height:20px;border-radius:3px;border:0;cursor:pointer;background-color:transparent;display:var(--lottie-player-seeker-display);color:var(--lottie-player-seeker-thumb-color);margin:0;padding:7.5px 0;position:relative;z-index:1}progress{position:absolute;width:100%;height:5px;border-radius:3px;border:0;top:0;left:0;margin:7.5px 0;background-color:var(--lottie-player-seeker-track-color);pointer-events:none}::-moz-progress-bar{background-color:var(--lottie-player-seeker-thumb-color)}::-webkit-progress-inner-element{border-radius:3px;overflow:hidden}::-webkit-slider-runnable-track{background-color:transparent}::-webkit-progress-value{background-color:var(--lottie-player-seeker-thumb-color)}.seeker::-webkit-slider-thumb{height:15px;width:15px;border-radius:50%;border:0;background-color:var(--lottie-player-seeker-thumb-color);cursor:pointer;transition:transform .2s ease-in-out;transform:scale(0)}.seeker:focus::-webkit-slider-thumb,.seeker:hover::-webkit-slider-thumb{transform:scale(1)}.seeker::-moz-range-progress{background-color:var(--lottie-player-seeker-thumb-color);height:5px;border-radius:3px}.seeker::-moz-range-thumb{height:15px;width:15px;border-radius:50%;background-color:var(--lottie-player-seeker-thumb-color);border:0;cursor:pointer;transition:transform .2s ease-in-out;transform:scale(0)}.seeker:focus::-moz-range-thumb,.seeker:hover::-moz-range-thumb{transform:scale(1)}.seeker::-ms-track{width:100%;height:5px;cursor:pointer;background:0 0;border-color:transparent;color:transparent}.seeker::-ms-fill-upper{background:var(--lottie-player-seeker-track-color);border-radius:3px}.seeker::-ms-fill-lower{background-color:var(--lottie-player-seeker-thumb-color);border-radius:3px}.seeker::-ms-thumb{border:0;height:15px;width:15px;border-radius:50%;background:var(--lottie-player-seeker-thumb-color);cursor:pointer;transition:transform .2s ease-in-out;transform:scale(0)}.seeker:focus::-ms-thumb,.seeker:hover::-ms-thumb{transform:scale(1)}.seeker:focus::-ms-fill-lower{background:var(--lottie-player-seeker-track-color)}.seeker:focus::-ms-fill-upper{background:var(--lottie-player-seeker-track-color)}.error{display:flex;margin:auto;justify-content:center;height:100%;align-items:center}.error svg{width:100%;height:auto}@keyframes fadeIn{0%{opacity:0}100%{opacity:1}}`;
423
+
424
+ function _ts_decorate(decorators, target, key, desc) {
425
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
426
+ if (typeof Reflect === "object" && typeof undefined === "function") r = undefined(decorators, target, key, desc);
427
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
428
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
429
+ }
430
+ class DotLottiePlayer extends LitElement {
431
+ _getOptions() {
432
+ const preserveAspectRatio = this.preserveAspectRatio ?? (this.objectfit && aspectRatio(this.objectfit)), initialSegment = !this.segment || this.segment.some((val)=>val < 0) ? undefined : this.segment.every((val)=>val > 0) ? [
433
+ this.segment[0] - 1,
434
+ this.segment[1] - 1
435
+ ] : this.segment, options = {
436
+ container: this.container,
437
+ loop: !!this.loop,
438
+ autoplay: !!this.autoplay,
439
+ renderer: this.renderer,
440
+ initialSegment,
441
+ rendererSettings: {
442
+ imagePreserveAspectRatio: preserveAspectRatio
443
+ }
444
+ };
445
+ switch(this.renderer){
446
+ case 'svg':
447
+ options.rendererSettings = {
448
+ ...options.rendererSettings,
449
+ hideOnTransparent: true,
450
+ preserveAspectRatio,
451
+ progressiveLoad: true
452
+ };
453
+ break;
454
+ case 'canvas':
455
+ options.rendererSettings = {
456
+ ...options.rendererSettings,
457
+ clearCanvas: true,
458
+ preserveAspectRatio,
459
+ progressiveLoad: true
460
+ };
461
+ break;
462
+ case 'html':
463
+ options.rendererSettings = {
464
+ ...options.rendererSettings,
465
+ hideOnTransparent: true
466
+ };
467
+ }
468
+ return options;
469
+ }
470
+ async load(src) {
471
+ if (!this.shadowRoot) return;
472
+ try {
473
+ const { animations, manifest, isDotLottie } = await getAnimationData(src);
474
+ if (!animations || animations.some((animation)=>!this._isLottie(animation))) {
475
+ throw new Error('Broken or corrupted file');
476
+ }
477
+ this._isDotLottie = !!isDotLottie;
478
+ this._animations = animations;
479
+ this._manifest = manifest ?? {
480
+ animations: [
481
+ {
482
+ id: useId(),
483
+ autoplay: this.autoplay,
484
+ loop: this.loop,
485
+ direction: this.direction,
486
+ mode: this.mode,
487
+ speed: this.speed
488
+ }
489
+ ]
490
+ };
491
+ if (this._lottieInstance) this._lottieInstance.destroy();
492
+ this._lottieInstance = Lottie.loadAnimation({
493
+ ...this._getOptions(),
494
+ animationData: animations[this._currentAnimation]
495
+ });
496
+ } catch (err) {
497
+ this._errorMessage = handleErrors(err).message;
498
+ this.currentState = PlayerState.Error;
499
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Error));
500
+ return;
501
+ }
502
+ this._addEventListeners();
503
+ this.setSpeed(this.speed);
504
+ this.setDirection(this.direction ?? 1);
505
+ this.setSubframe(!!this.subframe);
506
+ if (this.autoplay) {
507
+ if (this.direction === -1) this.seek('99%');
508
+ this.play();
509
+ }
510
+ }
511
+ getManifest() {
512
+ return this._manifest;
513
+ }
514
+ _addEventListeners() {
515
+ if (!this._lottieInstance) return;
516
+ this._lottieInstance.addEventListener('enterFrame', ()=>{
517
+ if (this._lottieInstance) {
518
+ const { currentFrame, totalFrames } = this._lottieInstance;
519
+ this._seeker = Math.floor(currentFrame / totalFrames * 100);
520
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Frame, {
521
+ detail: {
522
+ frame: currentFrame,
523
+ seeker: this._seeker
524
+ }
525
+ }));
526
+ }
527
+ });
528
+ this._lottieInstance.addEventListener('complete', ()=>{
529
+ this.currentState = PlayerState.Completed;
530
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Complete));
531
+ if (this._animations?.length > 1 && this.autoplay && this._currentAnimation < this._animations?.length - 1) {
532
+ this.next();
533
+ }
534
+ });
535
+ const loopComplete = ()=>{
536
+ if (!this._lottieInstance) {
537
+ return;
538
+ }
539
+ const { firstFrame, totalFrames, playDirection } = this._lottieInstance;
540
+ if (this.count) {
541
+ this.mode === PlayMode.Bounce ? this._playerState.count += 1 : this._playerState.count += 0.5;
542
+ if (this._playerState.count >= this.count) {
543
+ this.setLooping(false);
544
+ this.currentState = PlayerState.Completed;
545
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Complete));
546
+ return;
547
+ }
548
+ }
549
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Loop));
550
+ if (this.mode === PlayMode.Bounce) {
551
+ this._lottieInstance?.goToAndStop(playDirection === -1 ? firstFrame : totalFrames * 0.99, true);
552
+ this._lottieInstance?.setDirection(playDirection * -1);
553
+ return setTimeout(()=>{
554
+ this._lottieInstance?.play();
555
+ }, this.intermission);
556
+ }
557
+ this._lottieInstance?.goToAndStop(playDirection === -1 ? totalFrames * 0.99 : firstFrame, true);
558
+ return setTimeout(()=>{
559
+ this._lottieInstance?.play();
560
+ }, this.intermission);
561
+ };
562
+ this._lottieInstance.addEventListener('loopComplete', loopComplete);
563
+ this._lottieInstance.addEventListener('DOMLoaded', ()=>{
564
+ this._playerState.loaded = true;
565
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Ready));
566
+ });
567
+ this._lottieInstance.addEventListener('data_ready', ()=>{
568
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Load));
569
+ });
570
+ this._lottieInstance.addEventListener('data_failed', ()=>{
571
+ this.currentState = PlayerState.Error;
572
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Error));
573
+ });
574
+ if (this.container) {
575
+ this.container.addEventListener('mouseenter', ()=>{
576
+ if (this.hover && this.currentState !== PlayerState.Playing) {
577
+ this.play();
578
+ }
579
+ });
580
+ this.container.addEventListener('mouseleave', ()=>{
581
+ if (this.hover && this.currentState === PlayerState.Playing) {
582
+ this.stop();
583
+ }
584
+ });
585
+ }
586
+ }
587
+ _onVisibilityChange() {
588
+ if (document.hidden && this.currentState === PlayerState.Playing) {
589
+ this._freeze();
590
+ } else if (this.currentState === PlayerState.Frozen) {
591
+ this.play();
592
+ }
593
+ }
594
+ _handleSeekChange({ target }) {
595
+ if (!(target instanceof HTMLInputElement) || !this._lottieInstance || isNaN(Number(target.value))) return;
596
+ this.seek(Math.floor(Number(target.value) / 100 * this._lottieInstance.totalFrames));
597
+ setTimeout(()=>{
598
+ if (target.parentElement instanceof HTMLFormElement) {
599
+ target.parentElement.reset();
600
+ }
601
+ }, 100);
602
+ }
603
+ _isLottie(json) {
604
+ const mandatory = [
605
+ 'v',
606
+ 'ip',
607
+ 'op',
608
+ 'layers',
609
+ 'fr',
610
+ 'w',
611
+ 'h'
612
+ ];
613
+ return mandatory.every((field)=>Object.prototype.hasOwnProperty.call(json, field));
614
+ }
615
+ async addAnimation(configs, fileName, triggerDownload = true) {
616
+ try {
617
+ const oldManifest = this._manifest || {
618
+ animations: []
619
+ };
620
+ let manifest = {
621
+ ...oldManifest,
622
+ generator: pkg.name
623
+ }, animations = this._animations || [];
624
+ for (const config of configs){
625
+ const { url } = config, { animations: animationsToAdd } = await getAnimationData(url);
626
+ if (!animationsToAdd) {
627
+ throw new Error('No animation loaded');
628
+ }
629
+ if (manifest.animations.some(({ id })=>id === config.id)) {
630
+ throw new Error('Duplicate id for animation');
631
+ }
632
+ manifest = {
633
+ ...manifest,
634
+ animations: [
635
+ ...manifest.animations,
636
+ config
637
+ ]
638
+ };
639
+ animations = [
640
+ ...animations,
641
+ ...animationsToAdd
642
+ ];
643
+ }
644
+ return createDotLottie(animations, manifest, fileName, triggerDownload);
645
+ } catch (err) {
646
+ console.error(handleErrors(err).message);
647
+ }
648
+ }
649
+ getLottie() {
650
+ return this._lottieInstance;
651
+ }
652
+ play() {
653
+ if (!this._lottieInstance) return;
654
+ if (this.currentState) {
655
+ this._playerState.prev = this.currentState;
656
+ }
657
+ this._lottieInstance.play();
658
+ setTimeout(()=>{
659
+ this.currentState = PlayerState.Playing;
660
+ }, 0);
661
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Play));
662
+ }
663
+ pause() {
664
+ if (!this._lottieInstance) return;
665
+ if (this.currentState) {
666
+ this._playerState.prev = this.currentState;
667
+ }
668
+ this._lottieInstance.pause();
669
+ setTimeout(()=>{
670
+ this.currentState = PlayerState.Paused;
671
+ }, 0);
672
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Pause));
673
+ }
674
+ stop() {
675
+ if (!this._lottieInstance) return;
676
+ if (this.currentState) {
677
+ this._playerState.prev = this.currentState;
678
+ }
679
+ this._playerState.count = 0;
680
+ this._lottieInstance.stop();
681
+ setTimeout(()=>{
682
+ this.currentState = PlayerState.Stopped;
683
+ }, 0);
684
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Stop));
685
+ }
686
+ destroy() {
687
+ if (!this._lottieInstance) return;
688
+ this.currentState = PlayerState.Destroyed;
689
+ this._lottieInstance.destroy();
690
+ this._lottieInstance = null;
691
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Destroyed));
692
+ this.remove();
693
+ }
694
+ seek(value) {
695
+ if (!this._lottieInstance) return;
696
+ const matches = value.toString().match(/^([0-9]+)(%?)$/);
697
+ if (!matches) {
698
+ return;
699
+ }
700
+ const frame = Math.floor(matches[2] === '%' ? this._lottieInstance.totalFrames * Number(matches[1]) / 100 : Number(matches[1]));
701
+ this._seeker = frame;
702
+ if (this.currentState === PlayerState.Playing || this.currentState === PlayerState.Frozen && this._playerState.prev === PlayerState.Playing) {
703
+ this._lottieInstance.goToAndPlay(frame, true);
704
+ this.currentState = PlayerState.Playing;
705
+ } else {
706
+ this._lottieInstance.goToAndStop(frame, true);
707
+ this._lottieInstance.pause();
708
+ }
709
+ }
710
+ snapshot() {
711
+ if (!this.shadowRoot) return;
712
+ const svgElement = this.shadowRoot.querySelector('.animation svg'), data = svgElement instanceof Node ? new XMLSerializer().serializeToString(svgElement) : null;
713
+ if (!data) {
714
+ console.error('Could not serialize data');
715
+ return;
716
+ }
717
+ download(data, {
718
+ name: `${getFilename(this.src)}-${frameOutput(this._seeker)}.svg`,
719
+ mimeType: 'image/svg+xml'
720
+ });
721
+ return data;
722
+ }
723
+ setSubframe(value) {
724
+ if (!this._lottieInstance) return;
725
+ this.subframe = value;
726
+ this._lottieInstance.setSubframe(value);
727
+ }
728
+ _freeze() {
729
+ if (!this._lottieInstance) return;
730
+ if (this.currentState) {
731
+ this._playerState.prev = this.currentState;
732
+ }
733
+ this._lottieInstance.pause();
734
+ setTimeout(()=>{
735
+ this.currentState = PlayerState.Frozen;
736
+ }, 0);
737
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Freeze));
738
+ }
739
+ async reload() {
740
+ if (!this._lottieInstance) return;
741
+ this._lottieInstance.destroy();
742
+ if (this.src) {
743
+ await this.load(this.src);
744
+ }
745
+ }
746
+ setSpeed(value = 1) {
747
+ if (!this._lottieInstance) return;
748
+ this.speed = value;
749
+ this._lottieInstance.setSpeed(value);
750
+ }
751
+ setDirection(value) {
752
+ if (!this._lottieInstance) return;
753
+ this.direction = value;
754
+ this._lottieInstance.setDirection(value);
755
+ }
756
+ setLooping(value) {
757
+ if (this._lottieInstance) {
758
+ this.loop = value;
759
+ this._lottieInstance.setLoop(value);
760
+ }
761
+ }
762
+ togglePlay() {
763
+ if (!this._lottieInstance) return;
764
+ const { currentFrame, playDirection, totalFrames } = this._lottieInstance;
765
+ if (this.currentState === PlayerState.Playing) {
766
+ return this.pause();
767
+ }
768
+ if (this.currentState === PlayerState.Completed) {
769
+ this.currentState = PlayerState.Playing;
770
+ if (this.mode === PlayMode.Bounce) {
771
+ this.setDirection(playDirection * -1);
772
+ return this._lottieInstance.goToAndPlay(currentFrame, true);
773
+ }
774
+ if (playDirection === -1) {
775
+ return this._lottieInstance.goToAndPlay(totalFrames, true);
776
+ }
777
+ return this._lottieInstance.goToAndPlay(0, true);
778
+ }
779
+ return this.play();
780
+ }
781
+ toggleLooping() {
782
+ this.setLooping(!this.loop);
783
+ }
784
+ toggleBoomerang() {
785
+ if (this.mode === PlayMode.Normal) {
786
+ this.mode = PlayMode.Bounce;
787
+ } else {
788
+ this.mode = PlayMode.Normal;
789
+ }
790
+ }
791
+ _toggleSettings(flag) {
792
+ if (flag === undefined) {
793
+ this._isSettingsOpen = !this._isSettingsOpen;
794
+ } else {
795
+ this._isSettingsOpen = flag;
796
+ }
797
+ }
798
+ _handleBlur() {
799
+ setTimeout(()=>this._toggleSettings(false), 200);
800
+ }
801
+ _switchInstance() {
802
+ if (this._lottieInstance) this._lottieInstance.destroy();
803
+ this._lottieInstance = Lottie.loadAnimation({
804
+ ...this._getOptions(),
805
+ animationData: this._animations[this._currentAnimation]
806
+ });
807
+ this._addEventListeners();
808
+ if (this.autoplay) {
809
+ this._lottieInstance?.goToAndPlay(0, true);
810
+ this.currentState = PlayerState.Playing;
811
+ } else {
812
+ this._lottieInstance?.goToAndStop(0, true);
813
+ }
814
+ }
815
+ next() {
816
+ this._currentAnimation++;
817
+ this._switchInstance();
818
+ }
819
+ prev() {
820
+ this._currentAnimation--;
821
+ this._switchInstance();
822
+ }
823
+ convert(typeCheck, manifest, animations, fileName, download = true) {
824
+ if (typeCheck || this._isDotLottie) return;
825
+ const oldManifest = manifest || this._manifest, newManifest = {
826
+ ...oldManifest,
827
+ generator: pkg.name
828
+ };
829
+ return createDotLottie(animations || this._animations, newManifest, `${getFilename(fileName || this.src)}.lottie`, download);
830
+ }
831
+ static get styles() {
832
+ return styles;
833
+ }
834
+ connectedCallback() {
835
+ super.connectedCallback();
836
+ if (typeof document.hidden !== 'undefined') {
837
+ document.addEventListener('visibilitychange', this._onVisibilityChange);
838
+ }
839
+ }
840
+ async firstUpdated() {
841
+ if ('IntersectionObserver' in window) {
842
+ this._intersectionObserver = new IntersectionObserver((entries)=>{
843
+ if (entries[0].isIntersecting) {
844
+ if (!document.hidden && this.currentState === PlayerState.Frozen) {
845
+ this.play();
846
+ }
847
+ } else if (this.currentState === PlayerState.Playing) {
848
+ this._freeze();
849
+ }
850
+ });
851
+ this._intersectionObserver.observe(this.container);
852
+ }
853
+ if (this.src) {
854
+ await this.load(this.src);
855
+ }
856
+ this.dispatchEvent(new CustomEvent(PlayerEvents.Rendered));
857
+ }
858
+ disconnectedCallback() {
859
+ super.disconnectedCallback();
860
+ if (this._intersectionObserver) {
861
+ this._intersectionObserver.disconnect();
862
+ this._intersectionObserver = undefined;
863
+ }
864
+ if (this._lottieInstance) this._lottieInstance.destroy();
865
+ document.removeEventListener('visibilitychange', this._onVisibilityChange);
866
+ }
867
+ renderControls() {
868
+ const isPlaying = this.currentState === PlayerState.Playing, isPaused = this.currentState === PlayerState.Paused, isStopped = this.currentState === PlayerState.Stopped, isError = this.currentState === PlayerState.Error;
869
+ return html`<div class="${`lottie-controls toolbar ${isError ? 'has-error' : ''}`}" aria-label="Lottie Animation controls"><button @click="${this.togglePlay}" data-active="${isPlaying || isPaused}" tabindex="0" aria-label="Toggle Play/Pause">${isPlaying ? html`<svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M14.016 5.016H18v13.969h-3.984V5.016zM6 18.984V5.015h3.984v13.969H6z"/></svg>` : html`<svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M8.016 5.016L18.985 12 8.016 18.984V5.015z"/></svg>`}</button> <button @click="${this.stop}" data-active="${isStopped}" tabindex="0" aria-label="Stop"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M6 6h12v12H6V6z"/></svg></button> ${this._animations?.length > 1 ? html`${this._currentAnimation > 0 ? html`<button @click="${this.prev}" tabindex="0" aria-label="Previous animation"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M17.9 18.2 8.1 12l9.8-6.2v12.4zm-10.3 0H6.1V5.8h1.5v12.4z"/></svg></button>` : nothing} ${this._currentAnimation + 1 < this._animations?.length ? html`<button @click="${this.next}" tabindex="0" aria-label="Next animation"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="m6.1 5.8 9.8 6.2-9.8 6.2V5.8zM16.4 5.8h1.5v12.4h-1.5z"/></svg></button>` : nothing}` : nothing}<form class="progress-container${this.simple ? ' simple' : ''}"><input class="seeker" type="range" min="0" max="100" step="1" value="${this._seeker}" @change="${this._handleSeekChange}" @mousedown="${this._freeze}" aria-valuemin="0" aria-valuemax="100" role="slider" aria-valuenow="${this._seeker}" tabindex="0" aria-label="Slider for search"><progress max="100" value="${this._seeker}"></progress></form>${this.simple ? nothing : html`<button @click="${this.toggleLooping}" data-active="${this.loop ?? nothing}" tabindex="0" aria-label="Toggle looping"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M17.016 17.016v-4.031h1.969v6h-12v3l-3.984-3.984 3.984-3.984v3h10.031zM6.984 6.984v4.031H5.015v-6h12v-3l3.984 3.984-3.984 3.984v-3H6.984z"/></svg></button> <button @click="${this.toggleBoomerang}" data-active="${this.mode === PlayMode.Bounce}" aria-label="Toggle boomerang" tabindex="0"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="m11.8 13.2-.3.3c-.5.5-1.1 1.1-1.7 1.5-.5.4-1 .6-1.5.8-.5.2-1.1.3-1.6.3s-1-.1-1.5-.3c-.6-.2-1-.5-1.4-1-.5-.6-.8-1.2-.9-1.9-.2-.9-.1-1.8.3-2.6.3-.7.8-1.2 1.3-1.6.3-.2.6-.4 1-.5.2-.2.5-.2.8-.3.3 0 .7-.1 1 0 .3 0 .6.1.9.2.9.3 1.7.9 2.4 1.5.4.4.8.7 1.1 1.1l.1.1.4-.4c.6-.6 1.2-1.2 1.9-1.6.5-.3 1-.6 1.5-.7.4-.1.7-.2 1-.2h.9c1 .1 1.9.5 2.6 1.4.4.5.7 1.1.8 1.8.2.9.1 1.7-.2 2.5-.4.9-1 1.5-1.8 2-.4.2-.7.4-1.1.4-.4.1-.8.1-1.2.1-.5 0-.9-.1-1.3-.3-.8-.3-1.5-.9-2.1-1.5-.4-.4-.8-.7-1.1-1.1h-.3zm-1.1-1.1c-.1-.1-.1-.1 0 0-.3-.3-.6-.6-.8-.9-.5-.5-1-.9-1.6-1.2-.4-.3-.8-.4-1.3-.4-.4 0-.8 0-1.1.2-.5.2-.9.6-1.1 1-.2.3-.3.7-.3 1.1 0 .3 0 .6.1.9.1.5.4.9.8 1.2.5.4 1.1.5 1.7.5.5 0 1-.2 1.5-.5.6-.4 1.1-.8 1.6-1.3.1-.3.3-.5.5-.6zM13 12c.5.5 1 1 1.5 1.4.5.5 1.1.9 1.9 1 .4.1.8 0 1.2-.1.3-.1.6-.3.9-.5.4-.4.7-.9.8-1.4.1-.5 0-.9-.1-1.4-.3-.8-.8-1.2-1.7-1.4-.4-.1-.8-.1-1.2 0-.5.1-1 .4-1.4.7-.5.4-1 .8-1.4 1.2-.2.2-.4.3-.5.5z"/></svg></button> <button @click="${this._handleSettingsClick}" @blur="${this._handleBlur}" aria-label="Settings" aria-haspopup="true" aria-expanded="${!!this._isSettingsOpen}" aria-controls="${`${this._identifier}-settings`}"><svg width="24" height="24" aria-hidden="true" focusable="false"><circle cx="12" cy="5.4" r="2.5"/><circle cx="12" cy="12" r="2.5"/><circle cx="12" cy="18.6" r="2.5"/></svg></button><div id="${`${this._identifier}-settings`}" class="popover" style="display:${this._isSettingsOpen ? 'block' : 'none'}">${this._isDotLottie ? nothing : html`<button @click="${this.convert}" aria-label="Convert JSON animation to dotLottie format" tabindex="0"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M17.016 17.016v-4.031h1.969v6h-12v3l-3.984-3.984 3.984-3.984v3h10.031zM6.984 6.984v4.031H5.015v-6h12v-3l3.984 3.984-3.984 3.984v-3H6.984z"/></svg> Convert to dotLottie</button>`} <button @click="${this.snapshot}" aria-label="Download still image" tabindex="0"><svg width="24" height="24" aria-hidden="true" focusable="false"><path d="M16.8 10.8 12 15.6l-4.8-4.8h3V3.6h3.6v7.2h3zM12 15.6H3v4.8h18v-4.8h-9zm7.8 2.4h-2.4v-1.2h2.4V18z"/></svg> Download still image</button></div>`}</div>`;
870
+ }
871
+ render() {
872
+ return html`<figure class="${'animation-container main'}" data-controls="${this.controls ?? nothing}" lang="${this.description ? document?.documentElement?.lang : 'en'}" role="img" aria-label="${this.description ?? 'Lottie animation'}" data-loaded="${this._playerState.loaded}"><div class="animation" style="background:${this.background}">${this.currentState === PlayerState.Error ? html`<div class="error"><svg preserveAspectRatio="xMidYMid slice" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="1920" height="1080" viewBox="0 0 1920 1080"><path fill="#fff" d="M0 0h1920v1080H0z"/><path fill="#3a6d8b" d="M1190.2 531 1007 212.4c-22-38.2-77.2-38-98.8.5L729.5 531.3c-21.3 37.9 6.1 84.6 49.5 84.6l361.9.3c43.7 0 71.1-47.3 49.3-85.2zM937.3 288.7c.2-7.5 3.3-23.9 23.2-23.9 16.3 0 23 16.1 23 23.5 0 55.3-10.7 197.2-12.2 214.5-.1 1-.9 1.7-1.9 1.7h-18.3c-1 0-1.8-.7-1.9-1.7-1.4-17.5-13.4-162.9-11.9-214.1zm24.2 283.8c-13.1 0-23.7-10.6-23.7-23.7s10.6-23.7 23.7-23.7 23.7 10.6 23.7 23.7-10.6 23.7-23.7 23.7zM722.1 644h112.6v34.4h-70.4V698h58.8v31.7h-58.8v22.6h72.4v36.2H722.1V644zm162 57.1h.6c8.3-12.9 18.2-17.8 31.3-17.8 3 0 5.1.4 6.3 1v32.6h-.8c-22.4-3.8-35.6 6.3-35.6 29.5v42.3h-38.2V685.5h36.4v15.6zm78.9 0h.6c8.3-12.9 18.2-17.8 31.3-17.8 3 0 5.1.4 6.3 1v32.6h-.8c-22.4-3.8-35.6 6.3-35.6 29.5v42.3h-38.2V685.5H963v15.6zm39.5 36.2c0-31.3 22.2-54.8 56.6-54.8 34.4 0 56.2 23.5 56.2 54.8s-21.8 54.6-56.2 54.6c-34.4-.1-56.6-23.3-56.6-54.6zm74 0c0-17.4-6.1-29.1-17.8-29.1-11.7 0-17.4 11.7-17.4 29.1 0 17.4 5.7 29.1 17.4 29.1s17.8-11.8 17.8-29.1zm83.1-36.2h.6c8.3-12.9 18.2-17.8 31.3-17.8 3 0 5.1.4 6.3 1v32.6h-.8c-22.4-3.8-35.6 6.3-35.6 29.5v42.3h-38.2V685.5h36.4v15.6z"/><path fill="none" d="M718.9 807.7h645v285.4h-645z"/><text fill="#3a6d8b" style="text-align:center;position:absolute;left:100%;font-size:47px;font-family:system-ui,-apple-system,BlinkMacSystemFont,'.SFNSText-Regular',sans-serif" x="50%" y="848.017" text-anchor="middle">${this._errorMessage}</text></svg></div>` : nothing}</div>${this.controls ? this.renderControls() : nothing}</figure>`;
873
+ }
874
+ constructor(...args){
875
+ super(...args);
876
+ this.background = 'transparent';
877
+ this.controls = false;
878
+ this.currentState = PlayerState.Loading;
879
+ this.direction = 1;
880
+ this.hover = false;
881
+ this.intermission = 0;
882
+ this.loop = false;
883
+ this.mode = PlayMode.Normal;
884
+ this.objectfit = 'contain';
885
+ this.renderer = 'svg';
886
+ this.simple = false;
887
+ this.speed = 1;
888
+ this.subframe = true;
889
+ this._isSettingsOpen = false;
890
+ this._seeker = 0;
891
+ this._currentAnimation = 0;
892
+ this._lottieInstance = null;
893
+ this._identifier = this.id || useId('dotlottie');
894
+ this._errorMessage = 'Something went wrong';
895
+ this._isDotLottie = false;
896
+ this._playerState = {
897
+ prev: PlayerState.Loading,
898
+ count: 0,
899
+ loaded: false
900
+ };
901
+ this._handleSettingsClick = ({ target })=>{
902
+ this._toggleSettings();
903
+ if (target instanceof HTMLElement) {
904
+ target.focus();
905
+ }
906
+ };
907
+ }
908
+ }
909
+ _ts_decorate([
910
+ property({
911
+ type: Boolean,
912
+ reflect: true
913
+ })
914
+ ], DotLottiePlayer.prototype, "autoplay", void 0);
915
+ _ts_decorate([
916
+ property({
917
+ type: String
918
+ })
919
+ ], DotLottiePlayer.prototype, "background", void 0);
920
+ _ts_decorate([
921
+ property({
922
+ type: Boolean,
923
+ reflect: true
924
+ })
925
+ ], DotLottiePlayer.prototype, "controls", void 0);
926
+ _ts_decorate([
927
+ property({
928
+ type: Number
929
+ })
930
+ ], DotLottiePlayer.prototype, "count", void 0);
931
+ _ts_decorate([
932
+ property({
933
+ type: String
934
+ })
935
+ ], DotLottiePlayer.prototype, "currentState", void 0);
936
+ _ts_decorate([
937
+ property({
938
+ type: String
939
+ })
940
+ ], DotLottiePlayer.prototype, "description", void 0);
941
+ _ts_decorate([
942
+ property({
943
+ type: Number
944
+ })
945
+ ], DotLottiePlayer.prototype, "direction", void 0);
946
+ _ts_decorate([
947
+ property({
948
+ type: Boolean
949
+ })
950
+ ], DotLottiePlayer.prototype, "hover", void 0);
951
+ _ts_decorate([
952
+ property({
953
+ type: Number
954
+ })
955
+ ], DotLottiePlayer.prototype, "intermission", void 0);
956
+ _ts_decorate([
957
+ property({
958
+ type: Boolean,
959
+ reflect: true
960
+ })
961
+ ], DotLottiePlayer.prototype, "loop", void 0);
962
+ _ts_decorate([
963
+ property({
964
+ type: String
965
+ })
966
+ ], DotLottiePlayer.prototype, "mode", void 0);
967
+ _ts_decorate([
968
+ property({
969
+ type: String
970
+ })
971
+ ], DotLottiePlayer.prototype, "objectfit", void 0);
972
+ _ts_decorate([
973
+ property({
974
+ type: String
975
+ })
976
+ ], DotLottiePlayer.prototype, "preserveAspectRatio", void 0);
977
+ _ts_decorate([
978
+ property({
979
+ type: String
980
+ })
981
+ ], DotLottiePlayer.prototype, "renderer", void 0);
982
+ _ts_decorate([
983
+ property({
984
+ type: Array
985
+ })
986
+ ], DotLottiePlayer.prototype, "segment", void 0);
987
+ _ts_decorate([
988
+ property({
989
+ type: Boolean
990
+ })
991
+ ], DotLottiePlayer.prototype, "simple", void 0);
992
+ _ts_decorate([
993
+ property({
994
+ type: Number
995
+ })
996
+ ], DotLottiePlayer.prototype, "speed", void 0);
997
+ _ts_decorate([
998
+ property({
999
+ type: String
1000
+ })
1001
+ ], DotLottiePlayer.prototype, "src", void 0);
1002
+ _ts_decorate([
1003
+ property({
1004
+ type: Boolean
1005
+ })
1006
+ ], DotLottiePlayer.prototype, "subframe", void 0);
1007
+ _ts_decorate([
1008
+ query('.animation')
1009
+ ], DotLottiePlayer.prototype, "container", void 0);
1010
+ _ts_decorate([
1011
+ state()
1012
+ ], DotLottiePlayer.prototype, "_isSettingsOpen", void 0);
1013
+ _ts_decorate([
1014
+ state()
1015
+ ], DotLottiePlayer.prototype, "_seeker", void 0);
1016
+ _ts_decorate([
1017
+ state()
1018
+ ], DotLottiePlayer.prototype, "_currentAnimation", void 0);
1019
+ _ts_decorate([
1020
+ state()
1021
+ ], DotLottiePlayer.prototype, "_animations", void 0);
1022
+ DotLottiePlayer = _ts_decorate([
1023
+ customElement('dotlottie-player')
1024
+ ], DotLottiePlayer);
1025
+
1026
+ globalThis.dotLottiePlayer = ()=>new DotLottiePlayer();
1027
+
1028
+ export { DotLottiePlayer, PlayMode, PlayerEvents, PlayerState };